JSP 요약 정리

Hyunsu·2023년 11월 18일
0

Today I Learned

목록 보기
36/37
post-thumbnail

📝 목차

  1. JSP 스크립트
  2. request 와 response
  3. 내장 객체
  4. Cookie
  5. Session
  6. 한글 처리

1. JSP 스크립트

선언 태그

JSP 페이지에서 Java 의 멤버변수 또는 메서드를 선언

<%!
	int num = 10;
    String str = "jsp";
    ArrayList<String> list = new ArrayList<>();
    
    public void jspMethod() {
    	System.out.println(" -- jspMethod() -- ");
    }
%>

주석 태그

jsp 주석은 jsp 파일이 서블릿 파일로 변환될 때 제외된다.

<!-- HTML 주석 태그 -->
<%-- JSP 주석 태그 --%>

스크립트릿 태그

JSP 페이지에서 Java 코드를 넣기 위한 태그

<%
	if(num > 0) { // Java 코드
%>
		<p> num > 0 </p> // HTML 코드
<%
	} else {
%>
		<p> num <= 0 </p>
<%
	}
%>

표현식 태그

Java 의 변수 및 메서드의 반환값을 출력하는 태그

num is <%= num %>

지시어

서버에서 jsp 페이지를 처리하는 방법에 대한 정의

  • page : 페이지 기본 설정
<%@ page language="java" contentType="text/html; charset=EUC-KR" 
	pageEncoding="EUC-KR" %>
  • include : 외부 파일을 가져옴
<%@ include file="header.jsp" %>
  • taglib : 외부 라이브러리 태그 설정
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

2. request 와 response

서블릿의 request 및 response 와 같은 객체이다.

request 객체

<form action="mSignUp.jsp" method="get">
	name : <input type="text" name="m_name"> <br>
	password : <input type="password" name="m_pass"> <br>
	hobby : sport <input type="checkbox" name="m_hobby" value="sport">
			cooking <input type="checkbox" name="m_hobby" value="cooking">
			travel <input type="checkbox" name="m_hobby" value="travel"> <br>
	<input type="submit" value="sign up">
</form>

Request 요청

<%
	m_name = request.getParameter("m_name");
    m_pass = request.getParameter("m_pass");
    m_hobby = request.getParameterValues("m_hobby");
%>

response 객체

<body>
  First Page
  
  <% 
     response.sendRedirect("secondPage.jsp"); // secondPage.jsp 를 사용자에게 응답
  %>
</body>

Response 응답

<body>
  Second page
</body>

3. 내장 객체

내장 객체를 바로 사용할 수 있는 이유는 jsp 가 서블릿 파일로 변환될 때 컨테이너가 객체를 자동으로 생성해주기 때문이다.

config 와 application 객체는 web.xml 에 데이터를 명시해놓고 그것을 getInitParameter() 메서드를 이용해 JSP 및 Servlet 에서 데이터를 공유하는 방식이다.

config 객체

맵핑된 JSP 및 Servlet 에서만 데이터를 공유하는 객체

<init-param>
  <param-name>adminId</param-name>
  <param-value>admin</param-value>
</init-param>

<init-param>
  <param-name>adminPw</param-name>
  <param-value>1234</param-value>
</init-param>

// config.getInitParameter() 와 동일
String adminId = getServletConfig().getInitParameter("adminId");
String adminPw = getServletConfig().getInitParameter("adminPw"); 

application 객체

어플리케이션 전체에 데이터를 공유하는 객체

<context-param>
  <param-name>imgDir</param-name>
  <param-value>/upload/img</param-value>
</context-param>

<context-param>
  <param-name>testServerIP</param-name>
  <param-value>127.0.0.1</param-value>
</context-param>

// application.getInitParameter() 와 동일
String imgDir = getServletContext().getInitParameter("imgDir");
String testServerIP = getServletContext().getInitParameter("testServerIP"); 

아래 메서드로 속성을 저장하고 가져올 수도 있다.

// application.setAttribute() 와 동일
getServletContext().setAttribute("connectedIP", "165.62.58.23");
getServletContext().setAttribute("connectedUser", "bang");

// application.getAttribute() 와 동일
(String)getServletContext().getAttribute("connectedIP");
(String)getServletContext().getAttribute("connectedUser");

out 객체

출력 객체

<%
	out.print("<h1>Hello Java World</h1>");
%>

exception 객체

예외 처리 객체로 에러가 발생하면 해당페이지로 이동한다.

<%
	out.print(str.toString()); // 초기화 X
%>

<%
	response.setStatus(200);
    String msg = exception.getMessage();
%>

<h1> error message : <%= msg %> </h1>

쿠키란 브라우저가 보관하고 있는 데이터로 서버와 클라이언트의 기존 연결 정보를 저장하고 있다.

웹 서버에 요청을 보낼 때 쿠키들을 헤더에 담아서 전송하며 온 쿠키들을 보고 서버에서 특정 쿠키가 저장되어 있는지 확인한다. 만약 없다면 쿠키를 생성한다.

서버는 쿠키를 무조건 저장할 수 있긴 하지만 클라이언트에게 쿠키 허용을 물어봐야 하며 결국 쿠키를 저장할지 안할지는 사용자에게 달려있다.

Cookie[] cookies = request.getCookies(); // 쿠키 가져오기
Cookie cookie = null;

for (Cookie c : cookies) {
	System.out.println("c.getName() : " + c.getName() + "c.getValue() : " + c.getValue());
    
    if (c.getName().equals("memberId")) {
    	cookie = c; // memberId 쿠키가 있다면 cookie 객체에 저장
    }
}

if (cookie == null) {
	System.out.println("cookie is null");
    cookie = new Cookie("memberId", mId); // memberId 쿠키가 없다면 생성
}

response.addCookie(cookie); // 클라이언트에게 쿠키 응답
cookie.setMaxAge(60*60); // 쿠키 만료기간은 1h

response.sendRedirect("loginOk.jsp");

5. Session

쿠키와 마찬가지로 클라이언트와 서버의 연결을 유지시켜주는 방법이다.
쿠키와의 차이점은 세션은 웹 컨테이너 즉 서버에 기존 연결 정보를 저장한다.

// session == null 이면 로그인 유도
HttpSession session = request.getSession();
session.setAttribute("memberId", mId);

response.sendRedirect("loginOk.jsp");

// session != null 이면 로그인 정보 출력
session = request.getSession();
out.print("memberId : " + session.getAttribute("memberId") + "<br>");

// 로그아웃
session.invalidate();

6. 한글 처리

영문은 1 byte 한글은 2 byte 크기를 갖는다.
한글을 정상적으로 출력하기 위해 다음 코드를 추가한다.

  • post 방식 : 서블릿에 request.setCharacterEncoding("UTF-8");
  • get 방식 : server.xml 에 <Connector URIEncoding="UTF-8"/>

Filter

브라우저와 웹 서버의 통신에서 Filter 를 이용해 한글 처리를 더 쉽게 할 수 있다.
Filter 는 인터페이스이기 때문에 따로 클래스를 만들어서 이를 구현해야 한다.

public class TempFilter implements Filter {
	
    // 필터 생성
    @Override
    public void init(FilterConfig arg0) throws ServletException { }
    
    // 필터 작동
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    
    	// request filter
        req.setCharacterEncoding("UTF-8"); // 사용자로부터 오는 데이터가 깨지지 않도록 서버에서 한글 처리
        chain.doFilter(req, res); // 필터를 거쳐 다시 response 로 나감
        
        // response filter 는 특별히 할 일 X
        
    }
    
    // 필터 종료
    @Override
    public void destroy() { }
    
}

생성한 Filter 는 web.xml 에 등록해서 사용한다.

<filter>
  	<filter-name>tempFilter</filter-name>
  	<filter-class>com.servlet.filter.TempFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>tempFilter</filter-name>
  	<url-pattern>/*</url-pattern>
</filter-mapping>
profile
현수의 개발 저장소

0개의 댓글