1. 필터(Filter)란?
필터(Filter)란, 브라우저에서 서블릿에 요청하거나 응답할 때 미리 요청이나 응답과 관련해 여러 가지 작업을 처리하는 기능이다.
- JSP로 만든 폼에 한글 입력하기
- form.java
package sec02.ex01;
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("/form")
public class Form extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("form.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String val1 = req.getParameter("val1");
String val2 = req.getParameter("val2");
System.out.println(val1);
System.out.println(val2);
}
}
- form.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>
</head>
<body>
<form method="post">
<input name="val1">
<input name="val2">
<button>submit</button>
</form>
</body>
</html>
2. Filter를 이용한 한글 인코딩
- CharsetFilter.java
package sec02.ex01;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
@WebFilter("/*")
public class CharsetFilter implements Filter{
private String charset = "utf-8";
private FilterConfig fc;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
fc = filterConfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 전처리
System.out.println("전처리");
request.setCharacterEncoding(charset);
HttpServletRequest req = (HttpServletRequest) request;
long start = System.currentTimeMillis();
chain.doFilter(request, response); // 실제 서블릿이 수행할 일
System.out.println(req.getRequestURI() + "의 소요시간 : " + (System.currentTimeMillis() - start) + "ms");
// 후처리
System.out.println("후처리");
}
@Override
public void destroy() {
}
}