티스토리 뷰

728x90


http와 https를 혼용해서 운영할때 프로토콜이 바뀌면 세션이 끊어지는 경우가 있습니다.


이를 해결하기 위해 세션을 굽는 필터 클래스 입니다.


먼저 web.xml에 필터를 추가해줍니다.

<filter>

<filter-name>https</filter-name>

<filter-class>HttpsFilter Class Path</filter-class>

</filter>

<filter-mapping>

<filter-name>https</filter-name>

<url-pattern>*.do</url-pattern>

</filter-mapping>

HttpsFilter Class의 Path를 filter-class에 넣어줘야 합니다.


그리고 필터 클래스를 프로젝트에 추가 합니다.

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletRequestWrapper;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;


public class HttpsRequestWrapper extends HttpServletRequestWrapper {

private HttpServletResponse response = null;


public HttpsRequestWrapper(HttpServletRequest request) {

super(request);

}

public void setResponse(HttpServletResponse response) {

this.response = response;

}


public HttpSession getSession() {

HttpSession session = super.getSession();

processSessionCookie(session);

return session;

}

public HttpSession getSession(boolean create) {

HttpSession session = super.getSession(create);

processSessionCookie(session);

return session;

}

private void processSessionCookie(HttpSession session) {

if(session == null || response == null) {

return;

}

Object cookieOverWritten = getAttribute("COOKIE_OVERWRITTEN_FLAG");

if(cookieOverWritten==null 

&& isSecure() 

&& isRequestedSessionIdFromCookie() 

&& session.isNew()

) {

Cookie cookie = new Cookie("JSESSIONID", session.getId());

cookie.setMaxAge(-1);

String contextPath = getContextPath();

if(contextPath!=null && contextPath.length()>0) {

cookie.setPath(contextPath);

} else {

cookie.setPath("/");

}

response.addCookie(cookie);

setAttribute("COOKIE_OVERWRITTEN_FLAG", "true");

}

}

}


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;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class HttpsFilter implements Filter {

  public HttpsFilter() { }


  public void destroy() { }


  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpsRequestWrapper httpsRequest = new HttpsRequestWrapper((HttpServletRequest)request);

    httpsRequest.setResponse((HttpServletResponse)response);

    chain.doFilter(httpsRequest, response);

  }


  public void init(FilterConfig arg0) throws ServletException { }

}











728x90