Published 2020. 8. 18. 20:55
728x90
반응형

Filter Interface 

init(FilterConfig config);
웹 컨테이너가 필터를 호출할 경우 해당 메소드가 호출되어 필터 객체를 생성하며 초기화함
매개변수 FilterConfig는 web.xml에 있는 <filter>정보를 가지고 있음
doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
필터가 수행될 때 구동하는 메소드로, 요청 객체와 응답 객체를 사용해 일련의 작업을 수행한 뒤, chain을 통해 가공된 값을 목적지로 전송
destroy();
역할이 끝난 필터는 웹 컨테이너에 의해 해당 메소드를 호출하고 소멸

 

 

예제>

CharsetEncodingFilter Class

public class CharsetEncodingFilter implements Filter {

	@Override
	public void init(FilterConfig config) throws ServletException {}
    
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    
		req.setCharacterEncoding("UTF-8");
		res.setContentType("text/html; charset=UTF-8");
        
		chain.doFilter(req, res);
        
	}

	@Override
	public void destroy() {}

}

 

작성한 Filter를 web.xml에 등록

<filter>
	<filter-name>EncodingFilter</filter-name>
	<filter-class>test.common.filter.CharsetEncodingFilter</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>
	</init-param>
</filter>

<filter-mapping>
	<filter-name>EncodingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

 

 

FilterChain (interface) 

필터는 chain처럼 서로 연결되어 있는데 연결 되어있는 필터를 순차별로 doFilter() 매소드를 이용하여 실행시키는 인터페이스, 마지막 필터가 실행된 후에는 service() 매소드를 실행시켜 서블릿의 매소드 (doGet(), doPost())를 실행

 

doFilter(ServletRequest req, ServletResponse)

chain으로 연결되어있는 다음 필터를 실행하는 매소드

 

 

dispatcher처리

2.4버전부터 dispatcher의 요청도 필터를 적용할 수 있음

 

Filter-Mapping(url패턴과 매핑) 

<filter-mapping> 
	<filter-name>등록된 필터이름</filter-name> 
	<url-pattern>요청한 페이지 형식</url-pattern> 
<dispatcher> 
	REQUEST || INCLUDE || FORWARD || ERROR 
</dispatcher> 
</filter-mapping>  
반응형

'프로그래밍 > JSP' 카테고리의 다른 글

08.20(JSP)  (0) 2020.08.20
08.19(서블릿 래퍼)  (0) 2020.08.19
08.17(서블릿 필터1)  (0) 2020.08.17
08.14(서블릿 리스너2)  (0) 2020.08.14
08.13(서블릿 리스너1)  (0) 2020.08.13
복사했습니다!