[SERVER] TIL 047 - 23.09.19

유진·2023년 9월 19일
0


-> ojdbc, lombok, taglib3개 다운로드 받기(Google Drive)

-> 자주 쓰는 폴더는 tools > lib 폴더에 정리해두기

Server 참고사항!

index.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSP 전용 언어/태그/객체</title>
</head>
<body>
    <ul>
        <!-- 절대 경로 (최상위 주소 / 기준으로 작성) -->
        <!-- a 태그 : get 방식(페이지 단순 이동) -->
        <!-- Get, Post = 두 방식 모두 Controller 거쳐야 함! -->
        <li><a href="/elTest">EL (Expression Language)</a></li>
        
        <!-- 상대 경로 (현재 주소(위치)를 기준으로 작성) -->
        <li><a href="scope">Servlet/JSP 내장 객체와 범위(scope)</a></li>
        
        <li><a href="jstl/main">JSTL 라이브러리</a></li>
    </ul>
</body>
</html>

ELTestController.java

package edu.kh.jsp.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 edu.kh.jsp.model.dto.Book;

// WebServlet 안에 적는 경로는 절대 경로로, 앞에 /(최상위 경로) 가 꼭 붙어야 함!
@WebServlet("/elTest")
public class ELTestController extends HttpServlet{

	
	// a태그 요청 ( get방식 )
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		// jsp 경로는 어디기준? webapp 기준
		RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/el/elTest.jsp");
		
		dispatcher.forward(req, resp);
	}
	
	// form 태그 요청 ( post 방식 )
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		// POST 방식 -> req 문자 인코딩 부터 변경
		req.setCharacterEncoding("UTF-8");
		
		// 새로운 값을 req에 세팅
		
		req.setAttribute("address", "서울시 중구 남대문로 120"); // KEY, VALUE 형식
		req.setAttribute("score", 100);
		
		
		List<String> strList = new ArrayList<String>();
		strList.add("가가가");
		strList.add("나나나");
		strList.add("다다다");
		
		req.setAttribute("strList", strList);
		
		
		
		Book book = new Book("어린왕자", "생택쥐베리", 4000);
		
		req.setAttribute("book", book);
		
		
		// 밑 두개는 다른 것
		List<String> list1 = null; // null
		List<String> list2 = new ArrayList<String>(); // 비어있음
		
		req.setAttribute("list1", list1);
		req.setAttribute("list2", list2);
		
		
		
		
		// 요청 위임
		RequestDispatcher dis
			= req.getRequestDispatcher("/WEB-INF/views/el/elResult.jsp");
		
		dis.forward(req, resp);
		
		
	}
}

elTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>EL</title>
</head>
<body>
	<h1>EL(Expression Language)</h1>
	
	<pre>
		JSP의 표현식을 <%-- <%= %> --%>
		조금더 간단히 작성할 수 있도록 고안된 언어
		(JSP에 내장되어 있음)
		
		화면(HTML)에 출력하고자하는 자바 코드를
		
		<%-- \$ 로 작성하면 화면에 잘 출력됨 --%>
		\${ key } 형식으로 작성하면
		해당 위치에 알맞은 value가 출력됨
	</pre>
	
	<h3>EL의 특징 1번 : get이라는 단어를 사용하지 않는다.</h3>
	<pre>
		EL은 자바 코드를 얻어와 출력하는 언어
		-> 출력 전용 언어(set 불가)
		-> get밖에 남지 않으므로 생략
	</pre>
	
	테스트 1 (JSP 표현식) : <%= request.getParameter("test") %>
	<br>
	테스트 2 (EL) : ${param.test}
	
	
	<hr>
	
	<h3>EL의 특징 2번 : null, NullPointerException을 빈칸으로 처리</h3>
	
	테스트 1 (JSP 표현식) : <%= request.getParameter("num") %> <!-- null -->
	<br>
	테스트 2 (EL) : ${param.num} <!-- 빈칸 -->
	
	<hr>
	
	<form action="/elTest" method="post">
		이름 : <input name="inputName">
		<br>
		나이 : <input type="number" name="inputAge">
		
		a <input type="checkbox" name="opt" value="a">
		b <input type="checkbox" name="opt" value="b">
		c <input type="checkbox" name="opt" value="c">
		
		<button>제출</button>
	</form>
	
</body>
</html>

Book.java

package edu.kh.jsp.model.dto;

public class Book {
	private String title;
	private String writer;
	private int price;
	
	// 생성자 단축키 : ctrl + space
	public Book() {}

	// 매개변수 생성자 단축키 : alt + shift + s -> o
	public Book(String title, String writer, int price) {
		super();
		this.title = title;
		this.writer = writer;
		this.price = price;
	}

	// Getter/Setter 단축키 : alt + shift + s -> r
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getWriter() {
		return writer;
	}

	public void setWriter(String writer) {
		this.writer = writer;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}
	
}

elResult.jsp

<%@page import="edu.kh.jsp.model.dto.Book"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>EL 결과</title>
</head>
<body>
	<h1>EL을 이용해서 출력하기</h1>
	
	<h3>파라미터</h3>
	<ul>
		<li> \${ param.name속성값 } : request 담긴 파라미터 얻어오기 (1개) </li>
		<li> \${ paramValues } : 모든 파라미터를 배열로 얻어오기 </li>
		<li> \${ paramValues.name속성값[인덱스] } :
			name이 일치하는 파라미터 중 지정된 인덱스번째 value
		</li>
	</ul>
	
	<p>
		이름 : ${param.inputName} <br>
		나이 : ${param.inputAge} <br>
		
		opt : ${param.opt} <br> <!-- 0번째 인덱스만 나옴 -->
		
		opt[0] : ${paramValues.opt[0]} <br>
		opt[1] : ${paramValues.opt[1]} <br>
		opt[2] : ${paramValues.opt[2]} <br>
	</p>
	
	<hr>
	
	<h3>세팅된 속성(attribute) 출력하기</h3>
	
	<ul>
		<li>기본 : \${ key }    (key는 세팅한 속성의 key값)</li>
		
		<li>배열 또는 List : \${ key[index] }</li>
		
		<li>DTO 또는 Map : \${ key.필드명 }</li>
	</ul>
	
	
	<p>
		address(JSP) : <%= request.getAttribute("address") %> <br> <%-- 서울시 중구 남대문로 120 --%>
		address(EL)  : ${address} <br> <%-- 서울시 중구 남대문로 120 --%>
		
		score : ${score} <br> <%-- 100 --%>
		strList : ${strList} <br> <%-- [가가가,나나나,다다다] --%>
		book : ${book} <br> <%-- edu.kh.jsp.model.dto.Book@3ce4a2cc --%>
		
		<br><br>
		
		strList[0] : ${strList[0]} <br> <%-- 가가가 --%>
		strList[1] : ${strList[1]} <br> <%-- 나나나 --%>
		strList[2] : ${strList[2]} <br> <%-- 다다다 --%>
		
		<br><br>
		
		<%-- <%= ((Book)request.getAttribute("book")).getTitle() %> --%>
		
		book의 title : ${book.title} <br> <%-- 어린왕자 --%>
		book의 writer : ${book.writer} <br> <%-- 생택쥐베리 --%>
		book의 price : ${book.price} <br> <%-- 4000 --%>
	</p>
	
	
	<hr>
	
	<h1>EL은 null, 비어있다를 같은 것으로 생각한다!</h1>
	
	${list1}  /  ${list2}
	
	<h4>empty 연산자</h4> <!-- 자주 사용! -->
	
	${empty list1}  /  ${empty list2}
	
	<%-- true        /     true --%>
	
	
</body>
</html>

ScopeController.java

package edu.kh.jsp.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;

// 서블릿 매핑에서 유효하지 않은 url pattern
// -> 매핑할 주소 제일 앞에 "/" 반드시 작성
// -> 쓰지 않으면 에러납니다
@WebServlet("/scope")
public class ScopeController extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/scope/scope.jsp");
		
		
		// 1. page scope -> JSP 에서 확인
		
		
		// 2. request scope -> 요청받은 페이지 + 위임받은 페이지
		req.setAttribute("reqValue", "1234");
		
		
		// 3. session scope -> 브라우저당 1개
		//					-> 브라우저 종료 또는 session 만료까지 유지 (로그인에서 많이 사용)
		
		// session 객체 얻어오는 방법
		HttpSession session = req.getSession();
		session.setAttribute("sessionValue", "999");
		
		
		
		// 4. application scope -> 서버가 켜져있는 동안 유지
		
		// application 객체를 얻어오는 방법
		// -> request, session 객체에서 얻어오기 가능
		ServletContext application = req.getServletContext();
		//ServletContext application = session.getServletContext();
		application.setAttribute("appValue", 10000);
		
		// ** 모든 scope는 속성을 세팅하고 얻어오는 방법 동일!!! **
		
		
		
		
		
		// 모든 범위에 같은 key로 속성 세팅
		req.setAttribute("str", "request 범위에 세팅된 문자열");
		
		session.setAttribute("str", "session 범위에 세팅된 문자열");
		
		application.setAttribute("str", "application 범위에 세팅된 문자열");
		
		
		
		
		
		
		dispatcher.forward(req, resp);
	}
}

scope.jsp

<%@page import="edu.kh.jsp.model.dto.Book"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Servlet/JSP 내장 객체와 범위</title>
</head>
<body>
	<h1>Servlet/JSP 내장 객체와 범위</h1>
	
	<pre>
		Servlet/JSP에는 4종류의 범위를 갖는 내장 객체 존재
		-> 각 종류마다 영향을 끼치는 범위가 다름
		-> 개발자가 객체를 별도 생성하지 않아도 JSP에서 바로 사용할 수 있는 객체
		
		
		1. page : 현재 페이지(한 페이지)
			-> 현재 JSP에서만 사용 가능
			
		
		2. request : '요청 받은 페이지와
					이를 위임 받은 페이지'에서 사용 가능	 
		 		
		3. session : 현재 사이트에 접속한 브라우저 당 1개씩 생성
					브라우저가 종료되거나, session 만료될때 까지 유효
					
					
		4. application : 하나의 웹 애플리케이션마다 1개씩 생성되는 객체
						서버 켜질때 생성되어 종료될때 없어짐
						
						
						
		***************************
		** 내장 객체의 우선 순위 **
		***************************
		
		
		page > request > session > application				
		
	</pre>
	
	<ul>
		<li>
			page scope <br>
			
			<%
				// pageContext : page scope 객체
				pageContext.setAttribute("pageValue", 555);
			
				pageContext.setAttribute("str", "page 범위에 세팅된 문자열");
			%>
			
			pageValue : ${pageScope.pageValue} <!-- 555 -->
		</li>
		
		<br>
		
		<li>
			request scope <br>
			reqValue : ${requestScope.reqValue} <!-- 1234 -->
		</li>
		
		<br>
		
		<li>
			session scope <br>
			sessionValue : ${sessionScope.sessionValue} <!-- 999 -->
		</li>
		
		<br>
		
		<li>
			application scope <br>
			appValue : ${applicationScope.appValue} <!-- 10000 -->
		</li>
	</ul>
	
	
	
	<hr>
	
	<h3>
		<a href="scopeCheck">내장 객체별 생명주기 확인</a>
	</h3>
	
	
	<hr>
	
	<h3>우선 순위 확인</h3>
	
	<h4>각각의 범위에 세팅된 str</h4>
	${pageScope.str} <br>
	${requestScope.str} <br>
	${sessionScope.str} <br>
	${applicationScope.str} <br>
	
	<h4>${str}</h4>
	<%-- 우선순위에 의해 가장 우선순위가 높은 page 가 나온다 --%>
	
</body>
</html>

ScopeCheckController.java

package edu.kh.jsp.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("/scopeCheck")
public class ScopeCheckController extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		req.getRequestDispatcher("/WEB-INF/views/scope/scopeCheck.jsp").forward(req, resp);
	}
}

scopeCheck.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>scope 생명주기 확인</title>
</head>
<body>
	<h3>page : ${pageScope.str}</h3> <!-- 값X -->
	
	<h3>request : ${requestScope.str}</h3> <!-- 값X -->
	
	<h3>session : ${sessionScope.str}</h3> <!-- session 범위에 세팅된 문자열 -->
	
	<h3>application : ${applicationScope.str}</h3> <!-- application 범위에 세팅된 문자열 -->
	
	<!-- 흐름 : 1) index.html - 2) ScopeController.java(Servlet) - 3) scope.jsp - 
	4) ScopeCheckController(Servlet) - 5) scopeCheck.jsp 
	
	2) req.setAttribute("str", "req로 만들어진..")
	   session.
	   application.
	   
	3) pageContext.setAtt... = 여기서 생성되고, 죽음.
	-->
</body>
</html>

JSTLController.java

package edu.kh.jsp.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("/jstl/main")
public class JSTLController extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		req.getRequestDispatcher("/WEB-INF/views/jstl/main.jsp").forward(req, resp);
	}
}

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!-- c : core의 준말 -->
    
<%--
	
	<%@ %> : 지시자 태그
	
	taglib : 태그 라이브러리 추가
	
	prefix : 접두사, 태그명 앞에 작성되는 단어  <c:if>
	
	uri(Uniform Resource Identifier , 통합 자원 식별자)
		-> 자원을 식별하는 고유 문자열 (ID)
		
	(참고) url(Uniform Resource Locator)
		-> 자원의 위치를 나타내는 문자열(경로)
 --%>
  
  
  
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>JSTL(Jsp Standard Tag Library)</title>
</head>
<body>
	
	<h1>JSTL(Jsp Standard Tag Library, JSP 표준 태그 라이브러리)</h1>
	
	<pre>
		JSP에서 자주 사용되거나 공통적으로 사용되는
		Java 코드 (if, for, 변수 선언, 형변환)를
		
		스크립틀릿대신 html 태그 형식을 태그화하여
		표준으로 제공하는 라이브러리
		(if, for 간단히 쓰고싶으면 이거 써라..)
	</pre>
	
	<h3>JSTL 라이브러리 등록 방법</h3>
	
	<ol>
		<li>
			<a href="https://tomcat.apache.org/download-taglibs.cgi">
				JSTL 다운로드 페이지 이동
			</a>
			JSTL 다운로드
		</li>
		
		<li>
			/webapp/WEB-INF/lib 폴더에 라이브러리 파일(.jar) 추가
		</li>
		
		<li>
			JSTL 라이브러리를 사용하고자 하는 JSP 파일 상단에
			tablib JSP 지시자 태그를 추가
		</li>
	</ol>
	
	<hr>
	
	<h1>1. 변수 선언 (c:set 태그)</h1>
	
	<pre>
		- 변수 선언 위한 태그
		
		- c:set 에 작성 가능한 속성
		
		1) var : 변수명(속성 key)
		2) value : 대입할 값
		3) scope : page, request, session, application 중 하나 지정
				(기본값 page)
	</pre>
	
	<%
		// 스크립틀릿으로 page scope 에 속성 세팅하는 방법
		pageContext.setAttribute("num1", 10);
	%>
	
	<%-- JSTL로 page scope에 속성 세팅하는 방법 --%>
	<c:set var="num2" value="20" scope="page" />
	
	num1 : ${num1} <%-- 10 --%>
	<br>
	num2 : ${num2} <%-- 20 --%>
	
	
	<hr>
	
	<h1>2. 변수 제거 (c:remove)</h1>
	<pre>
		- 변수 제거 : 내장 객체에 세팅된 속성을 제거
			(  removeAttribute("num1")  )
			
		- c:remove 속성
		1) var : 삭제할 변수명
		2) scope : 내장 객체 범위 (기본값 : 모든 scope)
	</pre>
	
	<%
		pageContext.removeAttribute("num1");
	%>
	num1 제거 확인 : ${num1}
	
	<br>
	
	<c:remove var="num2" />
	
	num2 제거 확인 : ${num2}
	
	
	<hr>
	
	<h1>3. 변수 출력 (c:out 태그)</h1>
	
	<pre>
		/${key} EL 구문 비슷함
		
		- 단, escapeXml="true" (기본값) 설정 시
			html 태그가 해석 X
			
		- escapeXml="false" : html 태그 해석 O
	</pre>
	
	<c:set var="temp" value="<h1>곧 점심시간</h1>"/>
	
	html 태그 해석 X : <c:out value="${temp}" />
	
	<br>
	
	html 태그 해석 O : <c:out value="${temp}" escapeXml="false" />
	
	
	
	
	
</body>
</html>


EL 링크 클릭 시,
제출 버튼 클릭 시,

Servlet/JSP 링크 클릭 시,
내장 객체별 생명주기 확인 클릭 시,


JSTL 라이브러리 링크 클릭 시,

0개의 댓글