1. 필터의 개요
01. 필터(filter)
- 클라이언트와 서버 사이에서 request와 response 객체를 먼저 받아 사전/사우 작업 등 공통적으로 필요한 부분을 처리하는 것
- 클라이언트의 요청이 웹 서버의 서블릿, JSP, HTML 페이지 같은 정적리소스에 도달하기 전과, 반대로 정적 리소스에서 클라이언트로 응답하기 전에 필요한 전처리를 가능하게 함
- 필터는 HTTP 요청과 응답을 변경할 수 있는 코드로 재사용 가능
- 클라이언트와 정적 리소스 사이에 여러 개의 필터로 이루어진 필터 체인을 제공하기도 함
2. Filter 인터페이스의 구현 클래스
01. Filter 인터페이스
- 필터 기능을 구현하는 데핵심적인 역할을 함
- 클라이언트와 서버의 리소스 사이에 위치한 필터의 기능을 제공하기 위해 자바 클래스로 구현해야 함
02. init() 메소드
- JSP 컨테이너가 필터를 초기화할 때 호출되는 메소드
- init() 메소드는 JSP 컨테이너 내에서 초기화 작업을 수행할 필터 인스턴스를 생성한 후 한 번만 호출
- init() 메소드는 JSP 컨테이너에 의해 호출되어 피렅의 서비스가 시작되고 있음을 나타냄
03. doFilter() 메소드
- JSP 컨테이너가 필터를 리소스에 적용할 때마다 호출되는 메소드
- init() 메소드 후에 호출되며, 필터가 어떤 기능을 수행할 필요가 있을 때마다 호출
- 첫 번째 매개변수 ServletRequest 객체는 체인을 따라 전달하는 요청이고,
- 두 번째 매개변수 ServletResponse 객체는 체인을 따라 전달하는 응답
- 세 번째 매개변수 FilterChain 객체는 체인에서 다음 피렅를 호출하는데 사용
- 만약 호출 필터가 체인의 마지막 필터임ㄴ 끝에서 리소스를 호출
04. destory() 메소드
- 필터 인스턴스를 종료하기 전에 호출하는 메소드
- JSP 컨테이너가 필요 인스턴스턴스를 삭제하기 전에 청소 작업을 수행하는 데 사용되며, 이는 필터로 열린 리소스를 모두 닫을 수 있는 방법
- destory() 메소드는 필터의 수명 동안 한 번만 호출
3. web.xml 파일의 필터 구성
01. web.xml 파일에 필터를 설정
- 필터를 사용하려면 어떤 필터가 어떤 필터가 어떤 리소스에 대해 적용되는지 JSP 컨테이너에 알려주어야 함
- <filter>와 <filter-mapping> 요소를 사용
- web.xml 파일에 여러 개의 필터가 설정되어 있으면 선언된 순서대로 실행
02. <filter> 요소
- <filter> 요소는 웹 애플리케이션에서 자바 필터와 매개변수를 설정하는 데 사용
03. <init-param> 요소
- 설정된 매개변수와 값을 자바 또는 JSP 코드에서 접근
- 위의 예에서 <init-param> 요소에 설정된 매개변수와 값을 자바 클래스에서 접근하려면 다음과 같이 작성
04. <filter-mapping> 요소
- 특정 리소스에 대해 어떤 필터를 사용할지 설정하는 데 사용
예제 01.
- 폼 페이지에서 전송된 요청 파라미터를 필터로 처리하기
package ch12.com.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class AuthenFilter implements Filter{
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("Filter01 초기화...");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
System.out.println("Filter01.jsp 수행...");
String name = request.getParameter("name");
if(name == null || name.equals("")) {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html charset=UTF-8");
PrintWriter writer = response.getWriter();
String message = "입력된 name 값은 null 입니다";
writer.println(message);
return;
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
System.out.println("Filter01 해제...");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<security-role>
<role-name>guest</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>JSPBook</web-resource-name>
<url-pattern>/Book/addBook.jsp</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<description></description>
<role-name>guest</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/Book/login.jsp</form-login-page>
<form-error-page>/Book/login_failed.jsp</form-error-page>
</form-login-config>
</login-config>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/ch11/exceptionType_error.jsp</location>
</error-page>
<filter>
<filter-name>Filter01</filter-name>
<filter-class>ch12.com.filter.AuthenFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter01</filter-name>
<url-pattern>/ch12/filter01_process.jsp</url-pattern>
</filter-mapping>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="filter01_process.jsp">
<p> 이름 : <input type="text" name="name"></p>
<p><input type="submit" value="전송"></p>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name =request.getParameter("name");
%>
<p>입력된 name 값 : <%=name %></p>
</body>
</html>
예제 02.
- 필터 처리로 매개변수와 값을 전달받아 로그인 인증 처리하기
package ch12.com.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class InitParamFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("Filter02 초기화...");
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("Filter02 수행...");
String id = request.getParameter("id");
String passwd = request.getParameter("passwd");
String param1 = filterConfig.getInitParameter("param1");
String param2 = filterConfig.getInitParameter("param2");
String message;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter writer = response.getWriter();
if(id.equals(param1)&&passwd.equals(param2))
message = "로그인 성공했습니다";
else
message = "로그인 실패했습니다";
writer.println(message);
filterChain.doFilter(request, response);
}
private FilterConfig filterConfig = null;
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("Filter02 해제");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<security-role>
<role-name>guest</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>JSPBook</web-resource-name>
<url-pattern>/Book/addBook.jsp</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<description></description>
<role-name>guest</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/Book/login.jsp</form-login-page>
<form-error-page>/Book/login_failed.jsp</form-error-page>
</form-login-config>
</login-config>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/ch11/exceptionType_error.jsp</location>
</error-page>
<filter>
<filter-name>Filter01</filter-name>
<filter-class>ch12.com.filter.AuthenFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter01</filter-name>
<url-pattern>/ch12/filter01_process.jsp</url-pattern>
</filter-mapping>
<filter>
<filter-name>Filter02</filter-name>
<filter-class>ch12.com.filter.InitParamFilter</filter-class>
<init-param>
<param-name>param1</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>param2</param-name>
<param-value>1234</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Filter02</filter-name>
<url-pattern>/ch12/filter02_process.jsp</url-pattern>
</filter-mapping>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="filter02_process.jsp">
<p> 아이디 : <input type="text" name="id"></p>
<p> 비밀번호 : <input type="password" name="passwd"></p>
<p><input type="submit" value="전송"></p>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String id = request.getParameter("id");
String passwd = request.getParameter("passwd");
%>
<p> 입력된 id 값 : <%=id %></p>
<p> 입력된 pw 값 : <%=passwd %></p>
</body>
</html>
예제 03.
- 에제 02.의 웹 페이지를 이용하여 필터로 로그 기록하기
package ch12.com.filter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class LogFileFilter implements Filter {
PrintWriter writer;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
String filename = filterConfig.getInitParameter("filename");
if (filename == null)
throw new ServletException("로그 파일의 이름을 찾을수 없습니다");
try {
writer = new PrintWriter(new FileWriter(filename, true), true);
} catch (IOException e) {
throw new ServletException("로그 파일을 열 수 없습니다");
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
// TODO Auto-generated method stub
writer.printf("현재 일시 : %s %n", getCurrentTime());
String clientAddr = request.getRemoteAddr();
writer.printf("클라이언트 주소 : %s %n", clientAddr);
filterChain.doFilter(request, response);
String contentType = response.getContentType();
writer.printf("문서의 콘텐츠 유형 : %s %n", contentType);
writer.println("---------------------------------");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
writer.close();
}
private String getCurrentTime() {
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
return formatter.format(calendar.getTime());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<security-role>
<role-name>guest</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>JSPBook</web-resource-name>
<url-pattern>/Book/addBook.jsp</url-pattern>
<http-method>GET</http-method>
</web-resource-collection>
<auth-constraint>
<description></description>
<role-name>guest</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/Book/login.jsp</form-login-page>
<form-error-page>/Book/login_failed.jsp</form-error-page>
</form-login-config>
</login-config>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/ch11/exceptionType_error.jsp</location>
</error-page>
<filter>
<filter-name>Filter01</filter-name>
<filter-class>ch12.com.filter.AuthenFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter01</filter-name>
<url-pattern>/ch12/filter01_process.jsp</url-pattern>
</filter-mapping>
<filter>
<filter-name>Filter02</filter-name>
<filter-class>ch12.com.filter.InitParamFilter</filter-class>
<init-param>
<param-name>param1</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>param2</param-name>
<param-value>1234</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Filter02</filter-name>
<url-pattern>/ch12/filter02_process.jsp</url-pattern>
</filter-mapping>
<filter>
<filter-name>Filter02_2</filter-name>
<filter-class>ch12.com.filter.LogFileFilter</filter-class>
<init-param>
<param-name>filename</param-name>
<param-value>c:\\logs\\monitor.log</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Filter02_2</filter-name>
<url-pattern>/ch12/filter02_process.jsp</url-pattern>
</filter-mapping>
</web-app>
4. 웹 쇼핑몰 로그 기록하기
package filter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
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.http.HttpServletRequest;
public class LogFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println(" 접속한 클라이언트 IP : " + request.getRemoteAddr());
long start = System.currentTimeMillis();
System.out.println(" 접근한 URL 경로 : " + getURLPath(request));
System.out.println(" 요청 처리 시작 시각 : " + getCurrentTime());
chain.doFilter(request, response);
long end = System.currentTimeMillis();
System.out.println(" 요청 처리 종료 시각 : " + getCurrentTime());
System.out.println(" 요청 처리 소요 시간 : " + (end-start) + "ms ");
System.out.println("======================================");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("WebMarket 초기화...");
}
private String getURLPath(ServletRequest request){
HttpServletRequest req;
String currentPath = "";
String queryString = "";
if(request instanceof HttpServletRequest){
req = (HttpServletRequest)request;
currentPath = req.getRequestURI();
queryString = req.getQueryString();
queryString = queryString == null ? "" : "?" + queryString;
}
return currentPath + queryString;
}
private String getCurrentTime(){
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
return formatter.format(calendar.getTime());
}
}
package filter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
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.http.HttpServletRequest;
public class LogFileFilter implements Filter{
PrintWriter writer;
@Override
public void destroy() {
writer.close();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
writer.println(" 접속한 클라이언트 IP : " + request.getRemoteAddr());
long start = System.currentTimeMillis();
writer.println(" 접근한 URL 경로 : " + getURLPath(request));
writer.println(" 요청 처리 시작 시각 : " + getCurrentTime());
chain.doFilter(request, response);
long end = System.currentTimeMillis();
writer.println(" 요청 처리 종료 시각 : " + getCurrentTime());
writer.println(" 요청 처리 소요 시간 : " + (end - start) + "ms ");
writer.println("=========================================");
}
@Override
public void init(FilterConfig config) throws ServletException {
String filename = config.getInitParameter("filename");
if(filename == null){
throw new ServletException("로그 파일의 이름을 찾을 수 없습니다");
}
try{
writer = new PrintWriter(new FileWriter(filename, true), true);
}catch(IOException e){
throw new ServletException("로그 파일을 열 수 없습니다.");
}
}
private String getURLPath(ServletRequest request){
HttpServletRequest req;
String currentPath = "";
String queryString = "";
if(request instanceof HttpServletRequest){
req = (HttpServletRequest)request;
currentPath = req.getRequestURI();
queryString = req.getQueryString();
queryString = queryString == null ? "" : "?" + queryString;
}
return currentPath + queryString;
}
private String getCurrentTime(){
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
return formatter.format(calendar.getTime());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<security-role>
<description></description>
<role-name>admin</role-name>
</security-role>
<security-constraint>
<display-name>WebMarket Security</display-name>
<web-resource-collection>
<web-resource-name>WebMarket</web-resource-name>
<description></description>
<url-pattern>/addProduct.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<description>권한 관리자명</description>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/login_failed.jsp</form-error-page>
</form-login-config>
</login-config>
<error-page>
<error-code>404</error-code>
<location>/exceptionNoPage.jsp</location>
</error-page>
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>filter.LogFilter</filter-class>
</filter>
<filter>
<filter-name>LogFileFilter</filter-name>
<filter-class>filter.LogFileFilter</filter-class>
<init-param>
<param-name>filename</param-name>
<param-value>c:/logs/webmarket.log</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LogFileFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>