- JSP 스크립트
- request 와 response
- 내장 객체
- Cookie
- Session
- 한글 처리
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 language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR" %>
<%@ include file="header.jsp" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
서블릿의 request 및 response 와 같은 객체이다.
<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");
%>
<body>
First Page
<%
response.sendRedirect("secondPage.jsp"); // secondPage.jsp 를 사용자에게 응답
%>
</body>
Response 응답
<body>
Second page
</body>
내장 객체를 바로 사용할 수 있는 이유는 jsp 가 서블릿 파일로 변환될 때 컨테이너가 객체를 자동으로 생성해주기 때문이다.
config 와 application 객체는 web.xml 에 데이터를 명시해놓고 그것을 getInitParameter()
메서드를 이용해 JSP 및 Servlet 에서 데이터를 공유하는 방식이다.
맵핑된 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");
어플리케이션 전체에 데이터를 공유하는 객체
<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.print("<h1>Hello Java World</h1>");
%>
예외 처리 객체로 에러가 발생하면 해당페이지로 이동한다.
<%
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");
쿠키와 마찬가지로 클라이언트와 서버의 연결을 유지시켜주는 방법이다.
쿠키와의 차이점은 세션은 웹 컨테이너 즉 서버에 기존 연결 정보를 저장한다.
// 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();
영문은 1 byte 한글은 2 byte 크기를 갖는다.
한글을 정상적으로 출력하기 위해 다음 코드를 추가한다.
request.setCharacterEncoding("UTF-8");
<Connector URIEncoding="UTF-8"/>
브라우저와 웹 서버의 통신에서 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>