일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- Java
- set
- 리소스모니터링
- math
- 스택
- priority_queue
- deque
- sql
- javascript
- 힙덤프
- JPA
- scanner
- dfs
- alter
- 스프링부트
- 큐
- map
- BFS
- date
- Union-find
- string
- Properties
- NIO
- List
- CSS
- spring boot
- html
- GC로그수집
- Calendar
- union_find
- Today
- Total
매일 조금씩
01/07 - JSP(12) : controller만들어서 Model2 게시판 만들기(url 방식), 표현언어(EL) 기본객체 사용법 본문
01/07 - JSP(12) : controller만들어서 Model2 게시판 만들기(url 방식), 표현언어(EL) 기본객체 사용법
mezo 2021. 1. 17. 15:03Servlet
- 활용방안
=> MVC model2 pattern
m - beans
v - jsp(데이터와 직접연결은 없음 : beans에서 처리된 결과)
c - controller(요청 - m/v)
게시판
controller 요청 방법
파라메터 방식
controller?파라메터=기능
url 방식 (훨씬 편함)
기능.확장
*.do - 많이 씀
*.naver
view1.do view1.jsp
view2.do view2.jsp
[ url 방식 ]
annotation을 사용한 servlet으로 controller를 구현한다.
- annotation에서 @WebServlet("*.do")로 한다. (파라메터 방식에선 @WebServlet("/controller") )
- 파라메터 방식과 다르게 jsp 페이지에서 action파라메터 전달을 위한 태그를 추가하지 않아도 된다.
- form태그의 action 경로를 ok.jsp페이지에서 ok.do페이지로 바꾸면 된다.
ControllerEx01.java
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ControllerEx01
*/
@WebServlet("*.do")
public class ControllerEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// http://localhost:8081/프로젝트명/view1.do - view1.jsp
// http://localhost:8081/프로젝트명/view2.do - view2.jsp
// /프로젝트명/*.do
// /프로젝트명/view1.do
// /프로젝트명/view1.do
//System.out.println(request.getRequestURI());
// /프로젝트명
//System.out.println(request.getContextPath());
// '/프로젝트명'을 자름
// '/프로젝트명/*.do' -> '/*.do'
// '/프로젝트명/view1.do' -> '/view1.do'
// '/프로젝트명/view2.do' -> '/view2.do'
String path = request.getRequestURI().replaceAll(request.getContextPath(), "");
String url = "";
if(path.equals("/*.do") || path.contentEquals("/view1.do")) {
}else if(path.equals("/view2.do")) {
}else {
}
}
}
이렇게 까지만 다르고 나머진 파라메터 방식과 똑같이 채워주면 된다.
그럼 이렇게 된다.
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ControllerEx01
*/
@WebServlet("*.do")
public class ControllerEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// http://localhost:8081/프로젝트명/view1.do - view1.jsp
// http://localhost:8081/프로젝트명/view2.do - view2.jsp
// /프로젝트명/*.do
// /프로젝트명/view1.do
// /프로젝트명/view1.do
//System.out.println(request.getRequestURI());
// /프로젝트명
//System.out.println(request.getContextPath());
// '/프로젝트명'을 자름
// '/프로젝트명/*.do' -> '/*.do'
// '/프로젝트명/view1.do' -> '/view1.do'
// '/프로젝트명/view2.do' -> '/view2.do'
String path = request.getRequestURI().replaceAll(request.getContextPath(), "");
String url = "";
if(path.equals("/*.do") || path.contentEquals("/view1.do")) {
url = "/WEB-INF/views/view1.jsp";
}else if(path.equals("/view2.do")) {
url = "/WEB-INF/views/view2.jsp";
}else {
}
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
실습1) 동이름 검색으로 주소 찾기를 url 방식으로 구현
(1) Controller 구현
ZipcodeModel2Ex02
ControllerEx01.java
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model2.ActionModel;
import model2.ZipcodeAction;
import model2.ZipcodeOkAction;
/**
* Servlet implementation class ControllerEx01
*/
// 파라메터 방식
//@WebServlet("/controller")
// url 방식
@WebServlet("*.do")
public class ControllerEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 파라메터 방식
// String action = request.getParameter("action");
// url 방식
String path = request.getRequestURI().replaceAll(request.getContextPath(), "");
String url = "";
ActionModel model = null;
// 파라메터 방식
//if(action == null || action.equals("") || action.equals("zipcode")) {
// url 방식
if(path.equals("/*.do") || path.equals("/zipcode.do")) {
// 특별한 일이 없음
model = new ZipcodeAction();
model.execute(request, response);
url = "/WEB-INF/views/zipcode.jsp";
// 파라메터 방식
//}else if(action.equals("zipcode_ok")) {
// url 방식
}else if(path.equals("/zipcode_ok.do")) {
// 데이터베이스 선택
model = new ZipcodeOkAction();
model.execute(request, response);
url = "/WEB-INF/views/zipcode_ok.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
(2) zipcode.jsp 수정
파라메터방식에서 필요했던 action값이 담긴 input태그를 없애고
form 태그를 다음과 같이 수정한다.
<form action="./zipcode_ok.do" method="post" name="frm">
실습2) url 방식으로 model2 게시판 만들기
list.do board_list1.jsp
ListAction
view.do board_view1.jsp
ViewAction
write.do board_write1.jsp
WriteAction
write_ok.do board_write1_ok.jsp
WriteOkAction
modify.do board_modify1.jsp
ModifyAction
modify_ok.do board_modify1_ok.jsp
ModifyOkAction
delete.do board_delete1.jsp
DeleteAction
delete_ok.do board_delete1_ok.jsp
DeleteOkAction
(1) Model2Ex01 복사하기
Model2Ex01은 파라메터 방식으로 구현된 model2 게시판이다. 이걸 수정해서 url방식을 구현한다.
(2) Controller 수정
Model2Ex02
ControllerEx01.java
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model2.BoardAction;
import model2.DeleteAction;
import model2.DeleteOkAction;
import model2.ListAction;
import model2.ModifyAction;
import model2.ModifyOkAction;
import model2.ViewAction;
import model2.WriteAction;
import model2.WriteOkAction;
/**
* Servlet implementation class ControllerEx01
*/
@WebServlet("*.do")
public class ControllerEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 이거 하나로 모든 페이지가 한글 처리가 됨
request.setCharacterEncoding("utf-8");
String path = request.getRequestURI().replaceAll(request.getContextPath(), "");
// String action = request.getParameter("action");
String url = "";
BoardAction boardAction = null;
if(path.equals("/*.do") || path.equals("/list.do")) {
boardAction = new ListAction();
boardAction.execute(request, response);
url = "/WEB-INF/views/board_list1.jsp";
}else if(path.equals("/view.do")) {
// 데이터베이스 선택
boardAction = new ViewAction();
boardAction.execute(request, response);
url = "/WEB-INF/views/board_view1.jsp";
}else if(path.equals("/write.do")) {
// 데이터베이스 선택
boardAction = new WriteAction();
boardAction.execute(request, response);
url = "/WEB-INF/views/board_write1.jsp";
}else if(path.equals("/write_ok.do")) {
// 데이터베이스 선택
boardAction = new WriteOkAction();
boardAction.execute(request, response);
url = "/WEB-INF/views/board_write1_ok.jsp";
}else if(path.equals("/delete.do")) {
// 데이터베이스 선택
boardAction = new DeleteAction();
boardAction.execute(request, response);
url = "/WEB-INF/views/board_delete1.jsp";
}else if(path.equals("/delete_ok.do")) {
// 데이터베이스 선택
boardAction = new DeleteOkAction();
boardAction.execute(request, response);
url = "/WEB-INF/views/board_delete1_ok.jsp";
}else if(path.equals("/modify.do")) {
// 데이터베이스 선택
boardAction = new ModifyAction();
boardAction.execute(request, response);
url = "/WEB-INF/views/board_modify1.jsp";
}else if(path.equals("/modify_ok.do")) {
// 데이터베이스 선택
boardAction = new ModifyOkAction();
boardAction.execute(request, response);
url = "/WEB-INF/views/board_modify1_ok.jsp";
}else {
// 경로가 잘못표시 됐을때 오류 메세지
}
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
(3) jsp 수정
input 태그 action을 전부 지우고
모든 jsp파일을 ./controller?action=write 와 같이 되어있던 것을 지우고
전부 ./do파일명으로 바꿔준다.
ex) boad_write1.jsp 에서의 form태그 action 주소
./controller -> ./write_ok.do
실습3) 페이징 있는 model1게시판을 model2 로 만들기
Model2Ex02와 비슷하지만 cpage가 필요한 페이지는
cpage도 함께 넘겨 받도록 추가해줘야하고 list는 추가할 것이 많다.
list
(1) listTO만 넘길때
board_list1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardListTO" %>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardDAO" %>
<%@ page import="java.util.ArrayList" %>
<%
// cpage값이 없으면 1로 셋 하고 아니면 해당 페이지로 넘어가라
int cpage = (Integer)request.getAttribute("cpage");
// ---------------- listTO만 받을 때
BoardListTO listTO = (BoardListTO)request.getAttribute("listTO");
int recordPerPage = listTO.getRecordPerPage();
int totalRecord = listTO.getTotalPage();
// 전체 페이지 갯수 (0이 될수 없음)
int totalPage = listTO.getTotalPage();
int blockPerPage = listTO.getBlockPerPage();
int startBlock = listTO.getStartBlock();
int endBlock = listTO.getEndBlock();
ArrayList<BoardTO> lists = listTO.getBoardLists();
StringBuffer sbHtml = new StringBuffer();
for(BoardTO to: lists){
String seq = to.getSeq();
String subject = to.getSubject();
String writer = to.getWriter();
String wdate = to.getWdate();
String hit = to.getHit();
int wgap = to.getWgap();
sbHtml.append("<tr>");
sbHtml.append(" <td> </td>");
sbHtml.append(" <td>"+ seq +"</td>");
sbHtml.append(" <td class='left'>");
sbHtml.append( "<a href='./view.do?cpage="+ cpage +"&seq=" + seq + "'> "+ subject + "</a> ");
if(wgap == 0){
sbHtml.append( "<img src='./images/icon_hot.gif' alt='HOT'></td>");
}
sbHtml.append(" <td>"+ writer +"</td>");
sbHtml.append(" <td>"+ wdate +"</td>");
sbHtml.append(" <td>"+ hit +"</td>");
sbHtml.append(" <td> </td>");
sbHtml.append("</tr>");
}
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="./css/board_list.css">
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<div class="contents_sub">
<div class="board_top">
<div class="bold">총 <span class="txt_orange">1</span>건</div>
</div>
<!--게시판-->
<div class="board">
<table>
<tr>
<th width="3%"> </th>
<th width="5%">번호</th>
<th>제목</th>
<th width="10%">글쓴이</th>
<th width="17%">등록일</th>
<th width="5%">조회</th>
<th width="3%"> </th>
</tr>
<%=sbHtml %>
</table>
</div>
<!--//게시판-->
<div class="align_right">
<input type="button" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" onclick="location.href='./write.do?cpage=<%=cpage %>'" />
</div>
<!--페이지넘버-->
<div class="paginate_regular">
<div align="absmiddle">
<%
// << 구현
if(startBlock == 1){
out.println("<span><<</span>");
}else{
out.println("<span><a href='./list.do?cpage="+ (startBlock - blockPerPage) +"'><<</a></span>");
}
out.println(" ");
if(cpage == 1){
out.println("<span><a><</a></span>");
}else{
out.println("<span><a href='./list.do?cpage="+ (cpage-1) +"'><</a></span>");
}
out.println(" ");
for(int i=startBlock; i<=endBlock; i++){
if(i == cpage){
// 현재 페이지
out.println("<span>[" + i + "]</span>");
}else{
out.println("<span><a href='./list.do?cpage="+ i +"'>"+ i + "</a></span>");
}
}
out.println(" ");
if(cpage == totalPage){
out.println("<span><a>></a></span>");
}else{
out.println("<span><a href='board_list1.jsp?cpage="+ (cpage+1) +"'>></a></span>");
}
// >> 구현
out.println(" ");
if(endBlock == totalPage){
out.println("<span>>></span>");
}else{
out.println("<span><a href='./list.do?cpage="+ (startBlock + blockPerPage) +"'>>></a></span>");
}
%>
</div>
</div>
<!--//페이지넘버-->
</div>
</div>
<!--//하단 디자인 -->
</body>
</html>
ListAction.java
package model2;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model1.BoardDAO;
import model1.BoardListTO;
import model1.BoardTO;
public class ListAction implements BoardAction {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
System.out.println("ListAction 호출");
int cpage = 1;
if(request.getParameter("cpage") != null && !request.getParameter("cpage").equals("")){
cpage = Integer.parseInt(request.getParameter("cpage"));
}
BoardListTO listTO = new BoardListTO();
listTO.setCpage(cpage);
BoardDAO dao = new BoardDAO();
listTO = dao.boardList(listTO);
request.setAttribute("cpage", cpage);
// listTO로 넘길때
request.setAttribute("listTO", listTO);
}
}
(2) 각각 넘길 때
board_list1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardListTO" %>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardDAO" %>
<%@ page import="java.util.ArrayList" %>
<%
// cpage값이 없으면 1로 셋 하고 아니면 해당 페이지로 넘어가라
int cpage = (Integer)request.getAttribute("cpage");
// ----------------- 각각 받을때
int recordPerPage = (Integer)request.getAttribute("recordPerPage");
int totalRecord = (Integer)request.getAttribute("totalRecord");
// 전체 페이지 갯수 (0이 될수 없음)
int totalPage = (Integer)request.getAttribute("totalPage");
int blockPerPage = (Integer)request.getAttribute("blockPerPage");
int startBlock = (Integer)request.getAttribute("startBlock");
int endBlock = (Integer)request.getAttribute("endBlock");
ArrayList<BoardTO> lists = (ArrayList)request.getAttribute("lists");
StringBuffer sbHtml = new StringBuffer();
for(BoardTO to: lists){
String seq = to.getSeq();
String subject = to.getSubject();
String writer = to.getWriter();
String wdate = to.getWdate();
String hit = to.getHit();
int wgap = to.getWgap();
sbHtml.append("<tr>");
sbHtml.append(" <td> </td>");
sbHtml.append(" <td>"+ seq +"</td>");
sbHtml.append(" <td class='left'>");
sbHtml.append( "<a href='./view.do?cpage="+ cpage +"&seq=" + seq + "'> "+ subject + "</a> ");
if(wgap == 0){
sbHtml.append( "<img src='./images/icon_hot.gif' alt='HOT'></td>");
}
sbHtml.append(" <td>"+ writer +"</td>");
sbHtml.append(" <td>"+ wdate +"</td>");
sbHtml.append(" <td>"+ hit +"</td>");
sbHtml.append(" <td> </td>");
sbHtml.append("</tr>");
}
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="./css/board_list.css">
</head>
<body>
<!-- 상단 디자인 -->
<div class="con_title">
<h3>게시판</h3>
<p>HOME > 게시판 > <strong>게시판</strong></p>
</div>
<div class="con_txt">
<div class="contents_sub">
<div class="board_top">
<div class="bold">총 <span class="txt_orange">1</span>건</div>
</div>
<!--게시판-->
<div class="board">
<table>
<tr>
<th width="3%"> </th>
<th width="5%">번호</th>
<th>제목</th>
<th width="10%">글쓴이</th>
<th width="17%">등록일</th>
<th width="5%">조회</th>
<th width="3%"> </th>
</tr>
<%=sbHtml %>
</table>
</div>
<!--//게시판-->
<div class="align_right">
<input type="button" value="쓰기" class="btn_write btn_txt01" style="cursor: pointer;" onclick="location.href='./write.do?cpage=<%=cpage %>'" />
</div>
<!--페이지넘버-->
<div class="paginate_regular">
<div align="absmiddle">
<%
// << 구현
if(startBlock == 1){
out.println("<span><<</span>");
}else{
out.println("<span><a href='./list.do?cpage="+ (startBlock - blockPerPage) +"'><<</a></span>");
}
out.println(" ");
if(cpage == 1){
out.println("<span><a><</a></span>");
}else{
out.println("<span><a href='./list.do?cpage="+ (cpage-1) +"'><</a></span>");
}
out.println(" ");
for(int i=startBlock; i<=endBlock; i++){
if(i == cpage){
// 현재 페이지
out.println("<span>[" + i + "]</span>");
}else{
out.println("<span><a href='./list.do?cpage="+ i +"'>"+ i + "</a></span>");
}
}
out.println(" ");
if(cpage == totalPage){
out.println("<span><a>></a></span>");
}else{
out.println("<span><a href='board_list1.jsp?cpage="+ (cpage+1) +"'>></a></span>");
}
// >> 구현
out.println(" ");
if(endBlock == totalPage){
out.println("<span>>></span>");
}else{
out.println("<span><a href='./list.do?cpage="+ (startBlock + blockPerPage) +"'>>></a></span>");
}
%>
</div>
</div>
<!--//페이지넘버-->
</div>
</div>
<!--//하단 디자인 -->
</body>
</html>
ListAction.java
package model2;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model1.BoardDAO;
import model1.BoardListTO;
import model1.BoardTO;
public class ListAction implements BoardAction {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
System.out.println("ListAction 호출");
int cpage = 1;
if(request.getParameter("cpage") != null && !request.getParameter("cpage").equals("")){
cpage = Integer.parseInt(request.getParameter("cpage"));
}
BoardListTO listTO = new BoardListTO();
listTO.setCpage(cpage);
BoardDAO dao = new BoardDAO();
listTO = dao.boardList(listTO);
request.setAttribute("cpage", cpage);
// 각각 넘길때
request.setAttribute("recordPerPage", listTO.getRecordPerPage());
request.setAttribute("totalRecord", listTO.getTotalPage());
request.setAttribute("totalPage", listTO.getTotalPage());
request.setAttribute("blockPerPage", listTO.getBlockPerPage());
request.setAttribute("startBlock", listTO.getStartBlock());
request.setAttribute("endBlock", listTO.getEndBlock());
request.setAttribute("lists", listTO.getBoardLists());
}
}
표현언어
1. 표현언어
▷ p250 chapter.11 표현언어
뷰를 java를 안쓰고 html태그와 비슷하게 표현하는 것.
jsp코드에 기본적으로 포함되어 있는 다이렉티브에
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
이렇게 isELIgnored를 추가한다. false가 default이다.
표현식은 이클립스가 잘 처리 못하는 경우가 있다. 그래도 실행은 잘되니까 그냥 무시해라.
껐다 켜면 사라지는 경우가 많다.
앞에 '\ '쓰면 무효화된다.
ELEx01
실습1)
1. 문자열 표현
2. 숫자 표현
3. 숫자 연산
4. 문자 연산 : 연산자 중심이여서 피연산자에 문자가 들어가 있어도 숫자로 읽어서 연산된다.
ex) "10" + 1 = 11, "10" + "1" = 11
ex01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table width="800" border="1">
<tr>
<td>표현식</td>
<td>값</td>
</tr>
<tr>
<td>표현식</td>
<td><%=2 %></td>
</tr>
<tr>
<td>표현언어</td>
<td>${ "2" }</td>
</tr>
<tr>
<td>표현언어</td>
<td>${ 2 }</td>
</tr>
<tr>
<td>\${ 2 + 5 }</td>
<td>${ 2 + 5 }</td>
</tr>
<tr>
<td>\${ 2 div 5 }</td>
<td>${ 2 div 5 }</td>
</tr>
<tr>
<td>\${ 2 mod 5 }</td>
<td>${ 2 mod 5 }</td>
</tr>
<tr>
<td>\${ "10" + 1 }</td>
<td>${ "10" + 1 }</td>
</tr>
<tr>
<td>\${ "10" + "1" }</td>
<td>${ "10" + "1" }</td>
</tr>
</table>
</body>
</html>
실습2)
5. 비교연산
6. 삼항연산
ex02.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table width="800" border="1">
<tr>
<td>표현식</td>
<td>값</td>
</tr>
<tr>
<td width="50%">\${ 2 < 3 }</td>
<td>${ 2 < 3 }</td>
</tr>
<tr>
<td width="50%">\${ 2 lt 3 }</td>
<td>${ 2 lt 3 }</td>
</tr>
<tr>
<td width="50%">\${ empty data }</td>
<td>${ empty data }</td>
</tr>
<tr>
<td width="50%">\${ (2<3) ? "작다":"크다" }</td>
<td>${ (2<3) ? "작다":"크다" }</td>
</tr>
</table>
</body>
</html>
2. EL의 기본 객체
▷ p254 EL의 기본 객체
실습1)
7.값 가져오기
변수는 읽지 못한다. 객체로 정의한 변수만 읽어올수있다.
이렇게 자바를 쓰지 않고 html 코드를 쓸수있다.
ex03.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String name1 = "홍길동";
//pageContext, request, session, application
pageContext.setAttribute("name2", "박문수");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
out.println(name1 + "<br />");
%>
<%=name1 %><br />
name2 : <%=pageContext.getAttribute("name2") %><br />
name2 : ${ name2 }<br />
name2 : ${ pageScope.name2 }<br />
name2 : ${ pageScope['name2'] }<br />
</body>
</html>
실습2)
8. 객체종류별로 값 가져오기 구현
만약 같은 변수이름으로 객체종류별로 만들면? 가장 가까운 객체를 가져온다. (java에서 젤 위에거)
Scope로 같은 변수 이름이여도 다른 객체면 구분해서 가져올 수도 있다.
ex04.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
pageContext.setAttribute("name", "홍길동");
request.setAttribute("name", "박문수");
session.setAttribute("name", "성춘향");
application.setAttribute("name", "이몽룡");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${ name1 }<br />
${ name2 }<br />
${ name3 }<br />
${ name4 }<br />
<hr /><br />
<br />
${ name }<br />
${ pageScope.name }<br />
${ requestScope.name }<br />
${ sessionScope.name }<br />
${ applicationScope.name }<br />
</body>
</html>
실습3)
9. request로 헤더정보 가져와서 출력
java로 하던걸 표현언어로도 출력할 수 있다.
ex05.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.Enumeration" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
// 이렇게 java로 하던걸..
Enumeration e = request.getHeaderNames();
while(e.hasMoreElements()){
String name = (String)e.nextElement();
String value = request.getHeader(name);
out.println(name + "/" + value);
}
%>
<br /><br /><br />
<!-- 객체 사용해서 표현언어로 출력만 하게 할수 있다. -->
${ header['host'] }<br /><br />
${ header['user-agent'] }<br /><br />
${ header.host }<br /><br />
<!-- '-'가 특수 기호여서 안된다. 특수기호가 없는 것들은 이렇게 .으로 쓸수 있다. -->
\${ header.user-agent }<br /><br />
</body>
</html>
실습4)
10. param으로 값 받기
param 객체로 다른 페이지에서 값을 받을 수 있다.
(원랜 java태그로 그 안에서 request.getParameter를 써야했음)
같은 name으로여러개가 정의되어있는 경우엔 받을 때 paramValues객체를 사용한다.
paramsValues로 name에 배열을 써서 인덱스로 가져올 수 있다.
form.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="form_ok.jsp" method>
아이디: <input type="text" name="id" />
비밀번호: <input type="password" name="password" />
선택:<br />
<input type="checkbox" name="language" value="c" />c 언어 <br />
<input type="checkbox" name="language" value="c++" />c++ 언어 <br />
<input type="checkbox" name="language" value="c#" />c# 언어 <br />
<input type="submit" value="전송" />
</form>
</body>
</html>
form_ok.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
아이디 : ${ param.id }<br />
비밀번호 : ${ param.password }<br />
아이디 : ${ param['id'] }<br />
비밀번호 : ${ param['password'] }<br />
${ paramValues.language[0] }<br />
${ paramValues.language[1] }<br />
${ paramValues.language[2] }<br />
</body>
</html>
실습5)
11. 자바 객체클래스를 이용하는 것도 가능하다. (직접 접근 아님)
BoardTO.java
package model1;
public class BoardTO {
private String subject;
private String writer;
public String getSubject() {
System.out.println("getSubject() 호출");
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getWriter() {
System.out.println("getWriter() 호출");
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
}
ex06.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="model1.BoardTO"%>
<%
BoardTO to = new BoardTO();
to.setSubject("제목");
to.setWriter("작성자");
// "to"를 통해서 표현언어가 getter메소드에 접근해서 값을가져올수 있다.
//pageContext.setAttribute("to", to);
request.setAttribute("to", to);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--
"to"를 통해서 java코드에 접근하고 getter메소드를 통해 값을 가져올수 있다.
멤버변수에 직접 접근이 아니다!
-->
제목 : ${ to.subject }<br />
작성자 : ${ to.writer }<br />
</body>
</html>
실습6)
12. 11번을 객체 배열에 담아서 값 가져오기
null이면 null이라고 안뜨고 공백이 나옴
BoardTO.java
ex07.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="model1.BoardTO"%>
<%
BoardTO to1 = new BoardTO();
to1.setSubject("제목1");
to1.setWriter("작성자1");
BoardTO to2 = new BoardTO();
to2.setSubject("제목2");
to2.setWriter("작성자2");
BoardTO[] lists = { to1, to2 };
request.setAttribute("lists", lists);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
제목 : ${ lists[0].subject }<br />
작성자 : ${ lists[0].writer }<br />
제목 : ${ lists[1].subject }<br />
작성자 : ${ lists[1].writer }<br />
제목 : ${ lists[2].subject }<br />
작성자 : ${ lists[2].writer }<br />
</body>
</html>
실습7)
13. 12번을 ArrayList로 가져 오기
BoardTO.java
ex08.jsp
<%@page import="java.util.HashMap"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="model1.BoardTO"%>
<%@page import="java.util.ArrayList" %>
<%
BoardTO to1 = new BoardTO();
to1.setSubject("제목1");
to1.setWriter("작성자1");
BoardTO to2 = new BoardTO();
to2.setSubject("제목2");
to2.setWriter("작성자2");
ArrayList<BoardTO> lists = new ArrayList();
lists.add(to1);
lists.add(to2);
request.setAttribute("lists", lists);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
제목 : ${ lists[0].subject }<br />
작성자 : ${ lists[0].writer }<br />
제목 : ${ lists[1].subject }<br />
작성자 : ${ lists[1].writer }<br />
제목 : ${ lists[2].subject }<br />
작성자 : ${ lists[2].writer }<br />
</body>
</html>
실습8)
14. 13번을 HashMap으로 가져오기
ArrayList까지는 배열처럼 하면 됐는데 이건 객체로 보면된다.
이름값이 있기 때문에 인덱스가 아닌 이름값을 사용한다.
두가지 방법이 있다.
1) 객체명으로 가져오기
2) 배열로 가져오기
BoardTO.java
ex081.jsp
<%@page import="java.util.HashMap"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="model1.BoardTO"%>
<%@page import="java.util.ArrayList" %>
<%
BoardTO to1 = new BoardTO();
to1.setSubject("제목1");
to1.setWriter("작성자1");
BoardTO to2 = new BoardTO();
to2.setSubject("제목2");
to2.setWriter("작성자2");
HashMap<String, BoardTO> lists = new HashMap();
lists.put("to1", to1);
lists.put("to2", to2);
request.setAttribute("lists", lists);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 객체명으로 가져오기 -->
제목 : ${ lists.to1.subject }<br />
작성자 : ${ lists.to1.writer }<br />
제목 : ${ lists.to2.subject }<br />
작성자 : ${ lists.to2.writer }<br />
<!-- 배열형태로 가져오기 -->
제목 : ${ lists['to1'].subject }<br />
작성자 : ${ lists['to1']['writer'] }<br />
</body>
</html>
실습9)
15. 클래스 불러오기
FormatUtil.java
package util;
import java.text.DecimalFormat;
public class FormatUtil {
// number를 받아서 pattern화 해주는거
// 숫자사이에 점을 찍어준다든가 그런..
public static String changeFormat(long number, String pattern) {
DecimalFormat format = new DecimalFormat(pattern);
return format.format(number);
}
}
ex09.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="util.FormatUtil" %>
<%
pageContext.setAttribute("price", 12345L);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
가격 : ${ price }<br />
가격 : ${ FormatUtil.changeFormat(price, '#,##0') }<br />
</body>
</html>
이렇게 html사이에 java 코드를 넣지 않고 표현언어를 써서 구현할 수 있다.
응용 실습1) 자료실용 model2 게시판 만들기 (url 방식)
- controller 똑같고
- write에서 form에서 method, enctype적는거 유의!
- 파일 저장결로랑 파일 크기 제한 그런거 전부 WriteOkAction에서 처리
- request를 multi로 바꾸는거 유의
pdsModel2Ex02
board_write1.jsp
<form action="./write_ok.do" method="post" name="wfrm" enctype="multipart/form-data">
board_write1_ok.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="model1.BoardTO" %>
<%@ page import="model1.BoardDAO" %>
<%
int flag = (Integer)request.getAttribute("flag");
out.println("<script type='text/javascript'>");
if(flag == 0){
out.println("alert('글쓰기에 성공했습니다.');");
out.println("location.href='./list.do';");
}else{
out.println("alert('글쓰기에 실패했습니다.');");
out.println("history.back();");
}
out.println("</script>");
%>
WriteOkAction.java
package model2;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model1.BoardDAO;
import model1.BoardTO;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.oreilly.servlet.MultipartRequest;
import java.io.File;
import java.io.IOException;
public class WriteOkAction implements BoardAction {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
System.out.println("WriteOkAction 호출");
// -------------- write할 값을 to객체 안에 모두 set하기
try {
// 파일 업로드를 위함
String uploadPath = "C:/Java/java/jsp-workspace/PdsModel1Ex01/WebContent/upload";
int maxFileSize = 1024 * 1024 * 2;
String encType = "utf-8";
MultipartRequest multi
= new MultipartRequest(request, uploadPath, maxFileSize, encType, new DefaultFileRenamePolicy());
BoardTO to = new BoardTO();
to.setSubject(multi.getParameter("subject"));
to.setWriter(multi.getParameter("writer"));
// 필수 입력 항목이 아닌 경우
to.setMail("");
if(!multi.getParameter("mail1").equals("") && !multi.getParameter("mail2").equals("")){
to.setMail(multi.getParameter("mail1") + "@" + multi.getParameter("mail2"));
}
to.setPassword(multi.getParameter("password"));
to.setContent(multi.getParameter("content"));
to.setWip(request.getRemoteAddr());
to.setFilename(multi.getFilesystemName("upload"));
File file = multi.getFile("upload");
to.setFilesize(0);
if(file != null){
to.setFilesize(file.length());
}
// -------------- to 객체를 가지고 실제 db와 실행시킨후 제대로 됐는지 flag값 받아오기
BoardDAO dao = new BoardDAO();
int flag = dao.boardWriteOk(to);
request.setAttribute("flag", flag);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
※ 정리
serlvet클래스를 만드는 방법은 web.xml을 직접 작성하는 방법과 annotation을 사용하는 방법이 있다. annotation 방법이 귀찮은 web.xml 방법을 보완한 것이기 때문에 우린 annotation을 사용해서 controller를 만든다. 이 annotation을 이클립스에서 자동화 시켜놨다. servlet으로 만든 controller가 요청을 받는 방법은 파라메터방식, url방식 이렇게 두가지가 있다. url 방식이 훨씬 간단하므로 우린 url방식을 사용한다. 따라서 우린 annotation과 url 방식으로 controller를 만든다.