JSP & Servlet

Servlet 수행 후 Filter를 거쳐서 응답보내기

Jungsoomin :) 2020. 7. 17. 12:35

chain의 doFilter 메서드를 사용하면 필터결과 이후 필터로 넘기고 넘겨 Servlet으로 넘기는 역할을 하게된다.

 

그렇다면, 필터를 거쳐서 다시 거슬러올라가려면 doFilter() 메서드 뒤Statement를 정의하면 된다.

 

Response의 조작 기능HttpSerlvetResponseWrapper클래스를 상속받은 클래스에 정의 되어 있으니, 둘이 같이 사용하는 것이 이롭다고 봐야겠다.

 

들어온 순으로 다시 나가게 되므로 응답은 Serlvet부터 거쳐온 필터를 역으로 거슬러서 올라가게 된다.

public class FilterEx1 implements Filter {


    public FilterEx1() {
        // TODO Auto-generated constructor stub
    }


	public void destroy() {
		// TODO Auto-generated method stub
	}

//chain은 필터목록을 가지고 있다. 다음 필터가 해야하는 일은 chain의 do.Filter메소드로 실행한다.
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//		Http프로토콜이 아닌 서블릿요청 응답이므로 캐스팅을 해야한다.		
		System.out.println("필터 1 통과");

		// pass the request along the filter chain
		chain.doFilter(request, response);
		//마지막 chain의 doFilter 메소드는 Servlet 을 작동시킨다.
		
		System.out.println("다시 필터 1 통과");
	}


	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
public class FilterEx2 implements Filter {

    public FilterEx2() {
        // TODO Auto-generated constructor stub
    }


	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		System.out.println("필터 2 통과");
		//스프링에서는 init와 destory 재정의는 먹히지 않는다.
		chain.doFilter(request, response);
		
		System.out.println("다시 필터 2 통과");
	}


	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

public class ServletEx1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public ServletEx1() {
        super();
        // TODO Auto-generated constructor stub
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("서블릿1작동");
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

결과는 이렇게 도출된다.

 

정보: Server startup in 3009 ms
필터 1 통과
필터 2 통과
서블릿1작동
다시 필터 2 통과
다시 필터 1 통과