<%@ include file="" %> 정적으로 해당 jsp파일이 컴파일 될 때 포함됩니다

<jsp:include> 동적으로 해당 jsp가 실행 될 때 포함됩니다 

<c:import>jsp가 실행 될 때 url로 명기된 해당페이지를 text로 읽어와 해당 페이지에 합칩니다.




1. include 지시자 <%@ include file="header.html" %>

- 정적인 방식으로 서블릿 소스 파일 변환 시, file 속성에 명기한 파일을 현재 컨텐츠에 포함. 지시자 태그의 위치가 중요

 

2. <jsp:include> 표준 액션 <jsp:include page="header.jsp" />

- 동적인 방식으로 요청이 들어오는 시점에 page속성에 명기한 파일을 현재 컨텐츠에 포함.<jsp:param>태그를 사용하여 포함될 페이지에 값을 넘겨줄 수 있다.

 

3. <c:import> JSTL태그 <c:import url="http://~~~" />

- 요청이 들어오는 시점에 url속성에 명기한 파일을 현재 컨텐츠에 포함. 위 두개의 방식과는 현재 컨테이너 자원뿐만 아니라 외부 자원도 가능하다.<c:param>태그를 사용하여 포함될 페이지에 값을 넘겨줄 수 있다.

 

@ 포함될 html조각에는 <html><body>의 시작, 마침 태그가 있어서는 안된다.



출처: https://priceless.tistory.com/277 [Pasture]

'디지털 컨버전스 > JSP' 카테고리의 다른 글

[JSP] EL/JSTL 적용  (0) 2020.05.06
[JSP] JSTL - Jsp Standard Tag Library  (0) 2020.05.06
[JSP] EL - Expression language  (0) 2020.05.06
[JSP] Redirect & Forward  (0) 2020.04.28
[JSP] MVC2 - delete  (0) 2020.04.28

message 프로젝트

 

OutputView.jsp에 EL/JSTL 적용

<%@page import="kh.backend.dto.MessagesDTO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="C"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<table border=1 align=center>
		<tr>
			<td>글번호</td>
			<td>작성자</td>
			<td>글내용</td>
			<td>작성일</td>
		</tr>
		<C:forEach var="i" items="${list}">
			<tr>
				<td>${i.seq}
				<td>${i.name}
				<td>${i.msg}
				<td>${i.write_date}
			</tr>
		</C:forEach>
		<tr>
			<td colspan=4 align=center><button id="back">돌아가기</button>
		</tr>
	</table>
	<script>
		document.getElementById('back').onclick = function() {
			location.href = 'index.jsp';
		}
	</script>
</body>
</html>

더보기

index.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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<button id="toInput">toInput</button>
	<button id="toOutput">toOutput</button>
	<button id="toDelete">toDelete</button>
	<button id="toPractice">연습2</button>
	<script>
		$("#toInput").on("click",function(){
			location.href="input.jsp";
		
		})
		$("#toOutput").on("click",function(){
			location.href="output.msg";
		})
		$("#toDelete").on("click",function(){
			location.href="delete.msg";
		})
		$("#toPractice").on("click", function() {
			location.href = "practice2.prc";
	})
	</script>
</body>
</html>

 

FrontController

package kh.backend.controller;

import java.io.IOException;
import java.util.List;

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 kh.backend.dao.MessagesDAO;
import kh.backend.dto.MessagesDTO;

// delete.msg / input.msg / out.msg
@WebServlet("*.msg")
public class FrontController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		String contextPath = request.getContextPath();
		String requestURI = request.getRequestURI();
		String cmd = requestURI.substring(contextPath.length());
		MessagesDAO dao = new MessagesDAO();

		try {
        
        
			if(cmd.contentEquals("/output.msg")) {
				List<MessagesDTO> list =dao.selectAll(); //지역변수가 outputView.jsp에서 보이지 않음
				request.setAttribute("list", list);	
				RequestDispatcher rd =
						request.getRequestDispatcher("outputView.jsp");
				rd.forward(request, response);
                
                
			}else if(cmd.contentEquals("/delete.msg")){
				List<MessagesDTO> list =dao.selectAll();
				request.setAttribute("list", list);
				RequestDispatcher rd =
						request.getRequestDispatcher("deleteView.jsp");
				rd.forward(request, response);
			}else if(cmd.contentEquals("/input.msg")) {
				String name = request.getParameter("name");
				String msg = request.getParameter("msg");
				int result = dao.insert(new MessagesDTO(0,name,msg,null));
				System.out.println(result);
				response.sendRedirect("index.jsp");
			}else if(cmd.contentEquals("/deleteProc.msg")) {
				String del_num = request.getParameter("del_num");
				int del_result = dao.delete(del_num);
				response.sendRedirect("delete.msg");
			}
		}catch(Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 

DAO

package kh.backend.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import kh.backend.dto.MessagesDTO;

public class MessagesDAO {
	private Connection getConnection() throws Exception{
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String id = "kh";
		String pw = "kh";
		Class.forName("oracle.jdbc.driver.OracleDriver");
		return DriverManager.getConnection(url,id,pw);
	}
	
	public int insert(MessagesDTO dto) throws Exception{
		String sql = "insert into messages values(messages_seq.nextval, ?,?,sysdate)";
		
		try(Connection con = this.getConnection();	
		PreparedStatement pstat = con.prepareStatement(sql)){
			pstat.setString(1, dto.getName());
			pstat.setString(2, dto.getMsg());
			int result = pstat.executeUpdate();
			con.commit();
			return result;
		}
	}
	public List<MessagesDTO> selectAll() throws Exception{
		String sql = "select * from messages";
		try(Connection con = this.getConnection();
			PreparedStatement pstat = con.prepareStatement(sql);
			ResultSet rs = pstat.executeQuery();){
			
			List<MessagesDTO> result = new ArrayList<>();
			while(rs.next()) {
				int seq = rs.getInt("seq");
				String name = rs.getString("name");
				String msg = rs.getString("msg");
				Timestamp write_date = rs.getTimestamp("write_date");
				MessagesDTO dto = new MessagesDTO(seq,name,msg,write_date);
				result.add(dto);
			}
			return result;
		}
	}
	
	public int delete(String seq) throws Exception {

		String sql = "delete from messages where seq=?";
		try(Connection con = this.getConnection();	
				PreparedStatement pstat = con.prepareStatement(sql);) {
			pstat.setString(1, seq);
			int result = pstat.executeUpdate();
			con.commit();
			return result;
		}
	}
	
	public int update(String seq, String name, String msg) throws Exception {

		String sql = 
				"update messages set name = ? , msg=?  where seq=?";
		try(Connection con = this.getConnection();	
				PreparedStatement pstat = con.prepareStatement(sql);) {
			pstat.setString(1, name);
			pstat.setString(2, msg);
			pstat.setString(3, seq);
			int result = pstat.executeUpdate();
			con.commit();
			return result;
		}
	}
	
}





EL/JSTL 는 서버측 코드

 

클라이언트 브라우저에서는 확인 할 수 없다.

'디지털 컨버전스 > JSP' 카테고리의 다른 글

[JSTL] <c:import>  (0) 2020.06.24
[JSP] JSTL - Jsp Standard Tag Library  (0) 2020.05.06
[JSP] EL - Expression language  (0) 2020.05.06
[JSP] Redirect & Forward  (0) 2020.04.28
[JSP] MVC2 - delete  (0) 2020.04.28

라이브러리 다운로드 필요

http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/

 

Index of /dist/jakarta/taglibs/standard/binaries

 

archive.apache.org

jstl.jar
0.02MB
standard.jar
0.38MB


taglib : 태그 라이브러리, html태그 처럼 생겼음

    <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix="C"  %>

CDN 방식은 아님 , 태그라이브러리의 설정문서가 제목 : uri : 기능 순으로 되어있음

어떤 제목의 기능들을 쓰겠다고 선언 (import와 유사)

 

 


JSTL에서는 속성값에 "을 빼면 에러

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix="C"  %>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSTL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<c:if test="${empty list}">
		리스트가 비어있습니다.
	</c:if>
</body>
</html>

 


index.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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<button id="toInput">toInput</button>
	<button id="toOutput">toOutput</button>
	<button id="toDelete">toDelete</button>
	<button id="toPractice">연습2</button>
	<script>
		$("#toInput").on("click",function(){
			location.href="input.jsp";
		
		})
		$("#toOutput").on("click",function(){
			location.href="output.msg";
		})
		$("#toDelete").on("click",function(){
			location.href="delete.msg";
		})
		$("#toPractice").on("click", function() {
			location.href = "practice2.prc";
		
	})
	</script>
</body>
</html>

 

PracticeController.java

package kh.backend.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 kh.backend.dto.MessagesDTO;

@WebServlet("*.prc")
public class PracticeController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURL = request.getRequestURI();
		String ctxPath = request.getContextPath();
		String cmd = requestURL.substring(ctxPath.length());
		System.out.println(cmd);
		
		if(cmd.contentEquals("/practice1.prc")) {

		}else if(cmd.contentEquals("/practice2.prc")) {

			List<MessagesDTO> list = new ArrayList<>();
			list.add(new MessagesDTO(1002,"Tom","Cat",null));
			list.add(new MessagesDTO(1003,"Jane","JSTL",null));
			list.add(new MessagesDTO(1004,"Mike","Servlet",null));
			request.setAttribute("list", list);
			
			RequestDispatcher rd = request.getRequestDispatcher("practice2.jsp");
			rd.forward(request, response);
			
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

<C:choose>

, when , otherwise

JSPL문법에서 if, else if 대신 사용

 

practice2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="C"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSTL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<%-- 	<c:if test="${empty list}">
		리스트가 비어있습니다.
	</c:if> --%>

	<C:choose>
		<C:when test="${empty list}">
			리스트가 비어있습니다.
		</C:when>
		<C:otherwise>
			리스트가 비어있지 않습니다.
		</C:otherwise>
	</C:choose>
    
</body>
</html>

 

else if 처럼 조건항목을 추가하고 싶다면 when 을 반복해서 사용하면 된다.


<C:forEach>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="C"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSTL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	<C:forEach var="i" begin="0" step="1" end="10">
		${i}
	</C:forEach>
    
</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="C"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSTL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	<C:forEach var="i" begin="0" step="1" end="10">
		${list[i].name} : ${list[i].msg} <br>
	</C:forEach>
    
</body>
</html>

불필요하게 10번 반복되지 않도록 하기

 

자바의 foreach 처럼 실행하려면

	for(MessagesDTO i : list){
	}

 

	<C:forEach var="i" items="${list}">
	</C:forEach>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="C"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSTL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	
	<C:forEach var="i" items="${list}">
	${i.name} : ${i.msg} <br>
	</C:forEach>

</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="C"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSTL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	<C:choose>
		<C:when test="${empty list}">
			출력할 내용이 없습니다.
		</C:when>
		<C:otherwise>
			<C:forEach var="i" items="${list}">
				${i.name} : ${i.msg} <br>
			</C:forEach>
		</C:otherwise>
	</C:choose>

</body>
</html>

 

'디지털 컨버전스 > JSP' 카테고리의 다른 글

[JSTL] <c:import>  (0) 2020.06.24
[JSP] EL/JSTL 적용  (0) 2020.05.06
[JSP] EL - Expression language  (0) 2020.05.06
[JSP] Redirect & Forward  (0) 2020.04.28
[JSP] MVC2 - delete  (0) 2020.04.28

세션

- 로그인

- 장바구니

- 여러 페이지에 유지해야하는 데이터

- 서버쪽에서 특정데이터를 개인별로 따로 보관해 줄수 있다.

 

프론트컨트롤러

 

MVC 2 라는 구조는 구축했지만 아직 완성되진 않음

 

클라이언트 -> 서버 > 프론트 컨트롤러 > DAO > DB

 

 

스크립틀릿은 JAVA -> 퍼블리셔 역할 아님

VIEW 페이지(JSP)에는 자바언어가 없어야 함

EL (표현언어) / JSTL (라이브러리) : 가장 범용적이고 표준에 가까운 기능

 

리다이렉트(데이터 날리기) / 포워드(데이터보내기) : 반드시 구분지어야 함


메세지프로젝트

index.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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<button id="toInput">toInput</button>
	<button id="toOutput">toOutput</button>
	<button id="toDelete">toDelete</button>
	<button id="toPractice">연습</button>
	<script>
		$("#toInput").on("click",function(){
			location.href="input.jsp";
		
		})
		$("#toOutput").on("click",function(){
			location.href="output.msg";
		})
		$("#toDelete").on("click",function(){
			location.href="delete.msg";
		})
		$("#toPractice").on("click", function() {
			location.href = "practice1.prc";
		
	})
	</script>
</body>
</html>

EL : 내장되어있는 기능

${키값} 

DTO , arr , List 표현 방법

package kh.backend.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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 kh.backend.dto.MessagesDTO;

@WebServlet("*.prc")
public class PracticeController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURL = request.getRequestURI();
		String ctxPath = request.getContextPath();
		String cmd = requestURL.substring(ctxPath.length());
		
		System.out.println(cmd);
		if(cmd.contentEquals("/practice1.prc")) {
		request.setAttribute("data1", 10);
		request.setAttribute("data2", "Hello");
		request.setAttribute("data3", 3.14);
		
		MessagesDTO dto = new MessagesDTO(1001,"jack","EL",null);
		request.setAttribute("data4", dto);
		
		String[] arr = new String[] {"Apple","Orange","Mango"};
		request.setAttribute("data5", arr);
		
		List<String> list = new ArrayList<>();
		list.add("Java");list.add("Javascript");list.add("JSP");
		request.setAttribute("data6", list);
		
		
		RequestDispatcher rd = request.getRequestDispatcher("practice1.jsp");
		rd.forward(request, response);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	${data1}<br>
	${data2}<br>
	${data3}<br>
	${data4.name} : ${data4.msg}<br>
	${data5[0]} : ${data5[1]} : ${data5[2]}<br>
	${data6[0]} : ${data6[1]} : ${data6[2]}
</body>
</html>

 

 

리스트와 배열의 사용방법 같다.


DTO 리스트

 

 

package kh.backend.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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 kh.backend.dto.MessagesDTO;

@WebServlet("*.prc")
public class PracticeController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURL = request.getRequestURI();
		String ctxPath = request.getContextPath();
		String cmd = requestURL.substring(ctxPath.length());
		
		System.out.println(cmd);
		if(cmd.contentEquals("/practice1.prc")) {
		
		List<MessagesDTO> list2 = new ArrayList<>();
		list2.add(new MessagesDTO(1002,"Tom","Cat",null));
		list2.add(new MessagesDTO(1003,"Jane","JSTL",null));
		list2.add(new MessagesDTO(1004,"Mike","Servlet",null));
		request.setAttribute("data7", list2);
		
		RequestDispatcher rd = request.getRequestDispatcher("practice1.jsp");
		rd.forward(request, response);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	${data7[0].seq} :${data7[0].name} :${data7[0].msg}<br>
	${data7[1].seq} :${data7[1].name} :${data7[1].msg}<br>
	${data7[2].seq} :${data7[2].name} :${data7[2].msg}<br> 	
</body>
</html>

Map

DTO와 사용방법 동일

package kh.backend.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 kh.backend.dto.MessagesDTO;

@WebServlet("*.prc")
public class PracticeController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURL = request.getRequestURI();
		String ctxPath = request.getContextPath();
		String cmd = requestURL.substring(ctxPath.length());
		
		System.out.println(cmd);
		if(cmd.contentEquals("/practice1.prc")) {

		Map<String, String> map = new HashMap<>();
		map.put("friend1", "Tom");
		map.put("friend2", "Susan");
		map.put("friend3", "Jack");
		request.setAttribute("data8", map);
		
		RequestDispatcher rd = request.getRequestDispatcher("practice1.jsp");
		rd.forward(request, response);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body> 	
	${data8['friend1']} :${data8["friend2"]} :${data8.friend3}
</body>
</html>

 

 

 


${data8['friend1']}

${data8["friend1"]}

${data8.friend1}

// 같은 표현

 


[인덱스]값이 들어갈 자리에 .인덱스 로 표현 할 수는 없음

${data5[0]} // 실행가능
${data5.0} // 실행불가

키값이 숫자인 경우 대괄호로 표현해야 함

		map.put(10, "Jack");
${data8.10} // 실행불가
${data8["10"]} // 실행가능

EL은 Session의 데이터도 접근 가능

 

 

포워딩된 데이터는 포워딩된 페이지에서만 사용가능 하지만 세션은 모든 페이지에서 접근 가능

package kh.backend.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 kh.backend.dto.MessagesDTO;

@WebServlet("*.prc")
public class PracticeController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURL = request.getRequestURI();
		String ctxPath = request.getContextPath();
		String cmd = requestURL.substring(ctxPath.length());
		System.out.println(cmd);
        
		if(cmd.contentEquals("/practice1.prc")) {
		
		request.getSession().setAttribute("sdata","Works!!");
		
		RequestDispatcher rd = request.getRequestDispatcher("practice1.jsp");
		rd.forward(request, response);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	${sdata}
</body>
</html>

키값을 중복되게 지정할 경우

 

request라면 나중에 넣은 값이 들어감

Session에서 중복되게 지정할 경우?

package kh.backend.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 kh.backend.dto.MessagesDTO;

@WebServlet("*.prc")
public class PracticeController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURL = request.getRequestURI();
		String ctxPath = request.getContextPath();
		String cmd = requestURL.substring(ctxPath.length());
		System.out.println(cmd);
        
		if(cmd.contentEquals("/practice1.prc")) {
        
		request.setAttribute("data1", 10);
		request.getSession().setAttribute("data1","Works!!");
		
		RequestDispatcher rd = request.getRequestDispatcher("practice1.jsp");
		rd.forward(request, response);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	${data1}<br>
</body>
</html>

 

request 값이 출력된다.

 

 

우선순위 : request > session > application


특정 저장소의 값을 꺼내고 싶다면

package kh.backend.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 kh.backend.dto.MessagesDTO;

@WebServlet("*.prc")
public class PracticeController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestURL = request.getRequestURI();
		String ctxPath = request.getContextPath();
		String cmd = requestURL.substring(ctxPath.length());
		System.out.println(cmd);
        
		if(cmd.contentEquals("/practice1.prc")) {
			
		//Request 영역에 저장
		request.setAttribute("data1", 10);
		
		//Session 영역에 저장
		request.getSession().setAttribute("data1","Works!!");
		
		//Application 영역에 저장
		request.getServletContext().setAttribute("data1","App!!");
		
		RequestDispatcher rd = request.getRequestDispatcher("practice1.jsp");
		rd.forward(request, response);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	${applicationScope.data1} :${sessionScope.data1} : ${requestScope.data1}
    
</body>
</html>

 

 

실제로 키값을 중복되게 지정할 경우는 거의 없지만 알아는 두자!


EL은

스크립틀릿 영역에 자바언어를 쓰는 것에 비해 퍼블리셔에게 편리

 

EL은 디벨로퍼가 퍼블리셔에게 설명해주기 편리


없는 키값을 꺼내려고 할때

 

아무것도 나오지 않음

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	${key}<br>
	
</body>
</html>

주의 할 것!


El 표현 내에서 연산 가능

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	${data1+5}<br>
	${data1}+5
	
</body>
</html>

비교 가능

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	숫자 비교 : ${data1 == 10}<br>
	문자열 비교 : ${data2 == "Hello"}<br>
	숫자연산 : ${data1+5}<br>
	
</body>
</html>

 

 


비어있는지 점검 : empty

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	비어있는지 점검 : ${empty data6} <br>
	
</body>
</html>

 

비어있지 않다.

 

 

 

 

		List<String> list = new ArrayList<>();
//		list.add("Java");list.add("Javascript");list.add("JSP");
		request.setAttribute("data6", list);
		List<String> list //= new ArrayList<>();
//		list.add("Java");list.add("Javascript");list.add("JSP");
		request.setAttribute("data6", list);

 

 

 

요소가 없는것, 요소가 null 값인것 모두 검출


컨트롤러 거치지 않고 바로 JSP로 보낼때 (mvc1)

- 권장하지 않는 상황이지만 알아는 두자

 

input.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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	<form action="practice1.jsp" method="post">
    
		<input type=text name=name><br>
		<input type=text name=msg><br>
		<input type=submit>
	</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>EL Practice</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>

	${param.name}

</body>
</html>

 

 

 

param 객체에서 바로 꺼내야 함

'디지털 컨버전스 > JSP' 카테고리의 다른 글

[JSP] EL/JSTL 적용  (0) 2020.05.06
[JSP] JSTL - Jsp Standard Tag Library  (0) 2020.05.06
[JSP] Redirect & Forward  (0) 2020.04.28
[JSP] MVC2 - delete  (0) 2020.04.28
[JSP] MVC 2 구성  (0) 2020.04.28

 

Forward를 써야하는데 Redirect 를 해버리면

-- 데이터가 없어서 티가 난다

 

 

Redirect 를 써야 하는데 Forward를 쓰면

-- 입력한 후 제출을 누르면 내용이 리퀘스트에 담겨 인풋컨트롤러로 이동

-- forward로 이동하는 경우 url은 inputcontroller로 유지

-- 입력한 내용이 리퀘스트 안에서도 유지되는 상황

-- F5를 누르면

-- 중복입력

 

입력이 성공적으로 완료시

Redirect 로 리퀘스트를 비워줘야 한다.

'디지털 컨버전스 > JSP' 카테고리의 다른 글

[JSP] JSTL - Jsp Standard Tag Library  (0) 2020.05.06
[JSP] EL - Expression language  (0) 2020.05.06
[JSP] MVC2 - delete  (0) 2020.04.28
[JSP] MVC 2 구성  (0) 2020.04.28
[JSP] MVC 모델  (0) 2020.04.28

컨트롤러 한개만 해도 동작은 함

더보기

 

package kh.backend.controller;

import java.io.IOException;
import java.util.List;

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 kh.backend.dao.MessagesDAO;
import kh.backend.dto.MessagesDTO;


@WebServlet("/DeleteController")
public class DeleteController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MessagesDAO dao = new MessagesDAO();
		try {
			//출력
			List<MessagesDTO> list =dao.selectAll();
			request.setAttribute("list", list);
			RequestDispatcher rd =
					request.getRequestDispatcher("deleteView.jsp");
			
			//삭제할 글번호 받아오기
			String del_num = request.getParameter("del_num");
			int del_result = dao.delete(del_num);
			if(del_result>0) {
				rd = request.getRequestDispatcher("DeleteController");
			}
					
			rd.forward(request, response);

			
		}catch(Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
<%@page import="kh.backend.dto.MessagesDTO"%>
<%@page import="java.util.List"%>
<%@ 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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<form action="DeleteController" method="post">
<table border=1 align=center>
		<tr>
			<td>글번호</td>
			<td>작성자</td>
			<td>글내용</td>
			<td>작성일</td>
		</tr>
		<%
		List<MessagesDTO> list = (List<MessagesDTO>) request.getAttribute("list");
		for (MessagesDTO dto : list) {
		%>
		<tr>
			<td><%=dto.getSeq()%>
			<td><%=dto.getName()%>
			<td><%=dto.getMsg()%>
			<td><%=dto.getWrite_date()%>
		</tr>
		<%
		}
		%>
		<tr>
		<input type=text name= del_num placeholder="삭제할 번호">
		<input type=submit value="삭제">
			<td colspan=4 align=center><input type=button id="back" value="돌아가기">
		</tr>
	</table>
	</form>
	<script>
		document.getElementById('back').onclick = function() {
			location.href = 'index.jsp';
		}
	</script>
</body>
</html>

1. index.jsp

인덱스에서 DeleteController(서블릿)으로 이동

데이터를 뽑아올 필요 없다면 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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<button id="toInput">toInput</button>
	<button id="toOutput">toOutput</button>
	<button id="toDelete">toDelete</button>
	<script>
		$("#toInput").on("click",function(){
			location.href="input.jsp";
		})
		$("#toOutput").on("click",function(){
			location.href="OutputController";
		})
		$("#toDelete").on("click",function(){
			location.href="DeleteController";
		})
	</script>
</body>
</html>

2. DeleteController

deleteView로 보내주는 컨트롤러

package kh.backend.controller;
import java.io.IOException;
import java.util.List;
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 kh.backend.dao.MessagesDAO;
import kh.backend.dto.MessagesDTO;

@WebServlet("/DeleteController")
public class DeleteController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MessagesDAO dao = new MessagesDAO();
		try {
			List<MessagesDTO> list =dao.selectAll();
			request.setAttribute("list", list);
			RequestDispatcher rd =
					request.getRequestDispatcher("deleteView.jsp");
			rd.forward(request, response);
		}catch(Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

3. deleteView.jsp 

삭제페이지

 

목록 출력

 

<%@page import="kh.backend.dto.MessagesDTO"%>
<%@page import="java.util.List"%>
<%@ 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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<form action="DeleteProcController" method="post">
<table border=1 align=center>
		<tr>
			<td>글번호</td>
			<td>작성자</td>
			<td>글내용</td>
			<td>작성일</td>
		</tr>
		<%
		List<MessagesDTO> list = (List<MessagesDTO>) request.getAttribute("list");
		for (MessagesDTO dto : list) {
		%>
		<tr>
			<td><%=dto.getSeq()%>
			<td><%=dto.getName()%>
			<td><%=dto.getMsg()%>
			<td><%=dto.getWrite_date()%>
		</tr>
		<%
		}
		%>
		<tr>
		<input type=text name= del_num placeholder="삭제할 번호">
		<input type=submit value="삭제">
			<td colspan=4 align=center><input type=button id="back" value="돌아가기">
		</tr>
	</table>
	</form>
	<script>
		document.getElementById('back').onclick = function() {
			location.href = 'index.jsp';
		}
	</script>
</body>
</html>

4. DeleteProcController

삭제 수행

package kh.backend.controller;

import java.io.IOException;
import java.util.List;

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 kh.backend.dao.MessagesDAO;
import kh.backend.dto.MessagesDTO;


@WebServlet("/DeleteProcController")
public class DeleteProcController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MessagesDAO dao = new MessagesDAO();
		String del_num = request.getParameter("del_num");
		try {
			int del_result = dao.delete(del_num);	//삭제할 글번호 받아오기

			response.sendRedirect("DeleteController");
			//deleteView로 보내면 DeleteController를 거치지 않고 이동 -> 데이터 없음
            
		}catch(Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 

redirectforward 구분해서 사용해야 함!


삭제되었다는 것을 알릴 필요 없다면 redirect
데이터를 가져와야 한다면 forward


forward 는 클라이언트 측에서 url 변화 없음 // JSP 파일 숨길 수 있다

'디지털 컨버전스 > JSP' 카테고리의 다른 글

[JSP] EL - Expression language  (0) 2020.05.06
[JSP] Redirect & Forward  (0) 2020.04.28
[JSP] MVC 2 구성  (0) 2020.04.28
[JSP] MVC 모델  (0) 2020.04.28
[JSP] Delete 기능  (0) 2020.04.28

 


1. index.jsp / input.jsp

JSP 기능을 안쓰더라도 나중에 기능이 추가될 수 있음

HTML 대신 JSP로 만들기


2. 서블릿 InputController 생성

package kh.backend.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/InputController")
public class InputController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String msg = request.getParameter("msg");
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

3. 라이브러리, DAO, DTO 가져오기


InputController 

package kh.backend.controller;

import java.io.IOException;

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 kh.backend.dao.MessagesDAO;
import kh.backend.dto.MessagesDTO;

@WebServlet("/InputController")
public class InputController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String msg = request.getParameter("msg");

		MessagesDAO dao = new MessagesDAO();
		try {

			int result = dao.insert(new MessagesDTO(0,name,msg,null));
			request.setAttribute("result", result);

		}catch(Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 

request.setAttribute("result", result);

클라이언트가 보낸 가방(request)에 내용을 채워넣기

 


redirect

response.sendRedirect("error.jsp");

클라이언트에게 방향을 다시 지시

 

서버가 서블릿에게 response를 받아서 클라이언트에 전달

 

  • 클라이언트가 요청가방에 A페이지 넣어서 서버에 전달
  • 서버가 서블릿에 전달
  • 서블릿이 가방에 에러페이지 리다이렉트 넣어서 전달
  • 서버가 클라이언트에게 전달
  • 클라이언트가 에러페이지 리다이렉트 전달받고 새로운 요청가방에 에러페이지 요청

 

redirect는 페이지를 전환 시킬 수는 있으나 데이터를 유지해주는 기능은 없다.

리다이렉트요청은 클라이언트로 가고 클라이언트는 새로운 요청가방을 보내기 때문


forward

			RequestDispatcher rd =
					request.getRequestDispatcher("inputView.jsp");
			rd.forward(request, response);

페이지 별로 리퀘스트가 만들어짐
리다이렉트 하면 리퀘스트 가방에 넣어진 리스트는 버려짐


package kh.backend.controller;
import java.io.IOException;
import java.util.List;
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 kh.backend.dao.MessagesDAO;
import kh.backend.dto.MessagesDTO;

@WebServlet("/OutputController")
public class OutputController extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MessagesDAO dao = new MessagesDAO();
		try {
			List<MessagesDTO> list =dao.selectAll(); //지역변수가 outputView.jsp에서 보이지 않음
			request.setAttribute("list", list);
			RequestDispatcher rd =
					request.getRequestDispatcher("outputView.jsp");
			rd.forward(request, response);
		}catch(Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

 

<%@page import="kh.backend.dto.MessagesDTO"%>
<%@page import="java.util.List"%>
<%@ 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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<%
	List<MessagesDTO> list =
		(List<MessagesDTO>) request.getAttribute("list");
	System.out.println(list.size());
	%>
</body>
</html>

index.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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<button id="toInput">toInput</button>
	<button id="toOutput">toOutput</button>
	<script>
		$("#toInput").on("click",function(){
			location.href="input.jsp";
		})
		$("#toOutput").on("click",function(){
			location.href="OutputController";
		})
	</script>
</body>
</html>

input.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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<form action="InputController" method="post">
		<input type=text name=name><br>
		<input type=text name=msg><br>
		<input type=submit>
	</form>

</body>
</html>

InputController.java

package kh.backend.controller;

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 kh.backend.dao.MessagesDAO;
import kh.backend.dto.MessagesDTO;

@WebServlet("/InputController")
public class InputController extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String msg = request.getParameter("msg");

		MessagesDAO dao = new MessagesDAO();
		try {

			int result = dao.insert(new MessagesDTO(0,name,msg,null));
			System.out.println(result);
			response.sendRedirect("index.jsp");

		}catch(Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

OutputController.java

package kh.backend.controller;

import java.io.IOException;
import java.util.List;

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 kh.backend.dao.MessagesDAO;
import kh.backend.dto.MessagesDTO;


@WebServlet("/OutputController")
public class OutputController extends HttpServlet {


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		MessagesDAO dao = new MessagesDAO();
		try {
			List<MessagesDTO> list =dao.selectAll(); //지역변수가 outputView.jsp에서 보이지 않음
			request.setAttribute("list", list);
			
			RequestDispatcher rd =
					request.getRequestDispatcher("outputView.jsp");
			rd.forward(request, response);
			
		}catch(Exception e) {
			e.printStackTrace();
			response.sendRedirect("error.jsp");
		}
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 

outputView.jsp

<%@page import="kh.backend.dto.MessagesDTO"%>
<%@page import="java.util.List"%>
<%@ 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>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
	<table border=1 align=center>
		<tr>
			<td>글번호</td>
			<td>작성자</td>
			<td>글내용</td>
			<td>작성일</td>
		</tr>
		<%
		List<MessagesDTO> list = (List<MessagesDTO>) request.getAttribute("list");
		for (MessagesDTO dto : list) {
		%>
		<tr>
			<td><%=dto.getSeq()%>
			<td><%=dto.getName()%>
			<td><%=dto.getMsg()%>
			<td><%=dto.getWrite_date()%>
		</tr>
		<%
		}
		%>
		<tr>
			<td colspan=4 align=center><button id="back">돌아가기</button>
		</tr>
	</table>
	<script>
		document.getElementById('back').onclick = function() {
			location.href = 'index.jsp';
		}
	</script>
</body>
</html>

참고 : https://doublesprogramming.tistory.com/63

 

Redirect VS, Forward (Redirect와 forward의 차이)

Redirect VS, Forward (Redirect와 forward의 차이) JSP환경에서 현재 작업중인 페이지에서 다른페이지로 이동하는 두가지 방식의 페이지 전환기능 사례를 통해 redirect와 forward의 차이점에 대해 감을 잡아보자..

doublesprogramming.tistory.com

 

'디지털 컨버전스 > JSP' 카테고리의 다른 글

[JSP] Redirect & Forward  (0) 2020.04.28
[JSP] MVC2 - delete  (0) 2020.04.28
[JSP] MVC 모델  (0) 2020.04.28
[JSP] Delete 기능  (0) 2020.04.28
[JSP] output 기능  (0) 2020.04.27

데이터처리

DAO를 따로 구분하는 것 : 디자인패턴

 

HTML

 

코드를 분류하자!


MVC 모델 1

데이터에 접근하는 코드를 따로 빼둔다.

  •  Model
    • 클라이언트에게 보여지게 될 데이터를 추출 또는 생성하는 코드
    • DAO (데이터 액세스 오브젝트) - 데이터베이스뿐 아니라 모든 데이터에 접근하는 오브젝트
  • View
    • JSP
  • Control
    • JSP

(모델조차 나누지 않고 막코딩 하는 경우 -> 테스트용)

 

MVC 1 패턴은 여전히 숙제가 남아있음

누가 JSP를 담당하는가? (디벨로퍼?, 퍼블리셔?)

비전문 IT기업인 경우 (인하우스 개발, 회사내 사용)


MVC 모델 2

다시 서블릿이 등장

  •  Model
    • DAO : 데이터
  • View
    • JSP : 완성된 데이터를 바탕으로 클라이언트 화면을 꾸미는 코드
  • Control
    • Servlet : 제어

 

'디지털 컨버전스 > JSP' 카테고리의 다른 글

[JSP] MVC2 - delete  (0) 2020.04.28
[JSP] MVC 2 구성  (0) 2020.04.28
[JSP] Delete 기능  (0) 2020.04.28
[JSP] output 기능  (0) 2020.04.27
[JSP] input 기능  (0) 2020.04.27

+ Recent posts