본문 바로가기
JSP

[ Servlet ] Servlet Filter 사용법

by 정윤재 2013. 5. 14.

웹 개발을 하다보면


http request 를 받아서 bussiness logic 이 실행 되기 전에 


뭔가 선 작업 처리를 해 주어야 하는 경우가 있다.


예를 들어 http header 값을 보고 access 를 reject 시킨다던가


parameter 의 encoding 을 UTF-8 로 바꿔준다던가...


(실제로 filter 의 실용예 중 거의 대부분이 후자인 UTF-8 encoding 이다)


실제 servlet filter 예제를 만들어서 아래와 같이 올리니 참고 하길 바란다.


1. 웹 프로젝트 구조 (eclipse 의 dynamic web project 구조)





2. web.xml


<?xml version="1.0" encoding="UTF-8"?>

<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_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>HelloServlet</display-name>

  <servlet>

    <servlet-name>helloservlet</servlet-name>

    <servlet-class>com.test.HelloServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>helloservlet</servlet-name>

    <url-pattern>/HelloServlet</url-pattern>

  </servlet-mapping>

  <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 definition -->

  <filter>

  <filter-name>TestFilter</filter-name>

  <filter-class>com.test.TestFilter</filter-class>

  <init-param>

  <param-name>param1</param-name>

  <param-value>param1-value</param-value>

  </init-param>

  </filter>

  

  <!-- filter url mapping -->

  <filter-mapping>

  <filter-name>TestFilter</filter-name>

  <url-pattern>/HelloServlet</url-pattern>

  </filter-mapping>

</web-app>


3. HelloServlet.java


package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


/**

 * Servlet implementation class HelloServlet

 */

@WebServlet("/HelloServlet")

public class HelloServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public HelloServlet() {

        super();

        // TODO Auto-generated constructor stub

    }


/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

        System.out.println("Hello Servlet . GET");



       System.out.println("get enter");

        PrintWriter writer = response.getWriter(); 

       writer.println("<html><body>");

        writer.println("get enter");

        writer.println("</body></html>");




}


/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

        System.out.println("Hello Servlet . POST");

       


       System.out.println("post enter");

        PrintWriter writer = response.getWriter(); 

       writer.println("<html><body>");

        writer.println("post enter"); 

       writer.println("</body></html>");




}


}



4. TestFilter.java


package com.test;


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;


public class TestFilter implements Filter{


private String param1;


@Override

public void destroy() {

// TODO Auto-generated method stub

System.out.println("destroy method running");

}


@Override

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

// TODO Auto-generated method stub

System.out.println("before servlet running");

System.out.println("param1==="+param1);

//init parameter using

chain.doFilter(request, response);

System.out.println("after servlet running");

}


@Override

public void init(FilterConfig config) throws ServletException {

// TODO Auto-generated method stub

param1 = config.getInitParameter("param1");


}

}



5. 이렇게 하고 http://localhost:8080/FilterTest/HelloServlet 을 브라우저에서 호출 하면


 System.out 으로 console 에 찍힌 로그는 아래와 같다.


console 결과 :


before servlet running

param1===param1-value

Hello Servlet . GET

get enter

after servlet running




소스를 천천히 읽어보면 내용을 이해하실 겁니다.




댓글