Front-End/JSP

[JSP] FILTER(필터)

LightSource 2022. 5. 20. 19:12

Filter(필터)

필터의 기본구조

  • 필터는 클라이언트로 가는 응답과 최종 자원 사이에 위치
  • 최종 자원의 요청 결과를 알맞게 변경하는 역할을 할 수 있다.
  • init() 메서드 : 서버를 켰을때, 서블릿이 실행되기 전에 먼저 실행이 된다. 주로 필터 초기화 작업을 시작한다.
  • doFilter() 메서드 : 필터 기능을 수행하는 메서드.
  • destroy() 메서드 : 서버가 종료될때 호출된다.

필터 체인의 구성

  • 필터 여러개가 모여서 하나의 필터 체인을 형성한다.

예시)

  • 게시판 목록은 들어가진다.
  • 회원목록은 로그인을 해야 볼 수 있도록 하기 위해서 로그인이 안되어 있는 경우 필터를 작동 시키는 예
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
  <display-name>p75</display-name>
  <welcome-file-list>
    <welcome-file>menu.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>kr.co.seoulit.common.filter.LoginFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/member/*</url-pattern>  <!-- 회원목록(member)과 관련된 곳을 갈때, 필터작동 -->
  </filter-mapping>
</web-app>
  • web.xml에서 fillter-mapping 태그에서 url이 “/member/” 가 있으면 LoginFilter가 작동한다
<a href="member/list.jsp">회원목록</a><br/>
<a href="board/list.jsp">게시판목록</a><br/>
<a href=<%=s1%>><%=s2%></a><br/>
  • 회원목록은 url주소가 member 로 시작하므로 filter의 영향을 받는다
  • 게시판 목록은 board로 시작하므로 영향x
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here

        // pass the request along the filter chain
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
        HttpSession session=req.getSession();
        if(session.getAttribute("id")==null){     // id세션이 null 일경우
            String context=req.getContextPath();  // 프로젝트 이름을 가져오고
            String path=context+"/loginForm.jsp"; // 프로젝트 이름+/loginForm.jsp 주소를 
            resp.sendRedirect(path);              // 리턴한다.
        }else
            chain.doFilter(request, response);    // 다음필터가 없고, 서블릿이 없으므로 list.jsp를 실행
    }
  • do Filter 메서드에서 session.getAttribute로 id값이 있는지 확인하고 없을경우, loginForm.jsp로 보내버린다.
  • 로그인 상태인경우 필터를 거친후 else문에서 chain.doFilter를 실행하는데, 다음 필터가 없으므로 list.jsp를 실행하게 된다.
반응형