Filter mapping
web.xml에 Filter클래스를 등록하고 모든 요청을 우선적으로 접수하는 예
Struts2와 같은 프레임워크의 작동방식을 이해하기 위해 작성해 본 예제
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Hello</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>myFilter</filter-name>
<filter-class>filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
MyFilter.java
package filter;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import javax.servlet.*; // Filter인터페이스가 포함된 패키지
import action.MyAction;
import interceptor.MyInterceptor;
public class MyFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("MyFilter destroy()");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain arg2) throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("MyFilter doFilter()");
MyAction action = new MyAction();
MyInterceptor ic = new MyInterceptor();
try {
ic.processParam(request, action);
} catch (Exception e) {
e.printStackTrace();
}
String result = action.execute(request, response);
if(result.equals("success")){
RequestDispatcher rd = request.getRequestDispatcher("/view.jsp");
rd.forward(request, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
System.out.println("MyFilter init()");
}
}