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

+ Recent posts