본문 바로가기
JSP

[ JSP ] Servlet Filter 사용한 접근 제한 구현

by 정윤재 2013. 5. 21.

Servlet Filter 를 이용해서 특정 조건에 해당 하는 


request 들에 대해서 제한을 걸기에 좋은 예제를 아래와 같이 첨부 한다.


html 버전과 xml 버전을 모두 구현한다.


ErrorDTO 는 setter, getter 가 있는 일반적인 DTO  이다.


package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletResponse;


public class TestFilter implements Filter{


private String param1;

public static enum ReturnCode{

Filter403(403,"Filter403","You don't have permission to access on this server.");

private int returnStatus;

private String returnCode;

private String returnDesc;

ReturnCode(int returnStatus,String returnCode,String returnDesc){

this.returnStatus=returnStatus;

this.returnCode=returnCode;

this.returnDesc=returnDesc;

}

public int getReturnStatus(){

return returnStatus;

}

public String getReturnCode(){

return returnCode;

}

public String getReturnDesc(){

return returnDesc;

}

}

@Override

public void init(FilterConfig config) throws ServletException {

// TODO Auto-generated method stub

param1 = config.getInitParameter("param1");


}


@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);

//403 error occur code

sendError((HttpServletResponse)response);

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

}

@Override

public void destroy() {

// TODO Auto-generated method stub

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

}


public void sendError(HttpServletResponse response){

PrintWriter writer = null;

response.setStatus(ReturnCode.Filter403.getReturnStatus());

//xml 로 response 할 경우

//response.setContentType("text/xml");

//ErrorDTO errorDTO = new ErrorDTO();

//html 로 response 할 경우

response.setContentType("text/html");

response.setCharacterEncoding("UTF-8");

//xml 로 response 할 경우

//errorDTO.setHttpStatus(ReturnCode.Filter403.getReturnStatus());

//errorDTO.setCode(ReturnCode.Filter403.getReturnCode());

//errorDTO.setMessage(ReturnCode.Filter403.getReturnDesc());

try{

//xml로 response 할 경우

//writer = response.getWriter();

//new XStream().toXML(errorDTO,writer);

//html 접근 권한 없음 에러

response.sendError(HttpServletResponse.SC_FORBIDDEN);

}catch(IOException ie){

try{

response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

//500 error

}catch(IOException ie2){

ie2.printStackTrace();

}

}finally{

if(writer != null){

writer.close();

}

}

}



}




댓글