[Spring] 세션 인터셉터 설정을 해보자
다음 코드는 프로젝트를 진행하면서 작성한 세션 인터셉터 코드이다. (재활용..)
public class SessionInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (request.getSession().getAttribute("no") == null) {
response.sendRedirect("./");
return false;
} // if End
return true; // 꼭 써줘야 한다.
} // method End
// // 서블릿 지나서 서비스 클래스 가기 전에 인터셉트 한 후 작업 (잘 쓰이지 않는다.)
// @Override
// public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
// ModelAndView modelAndView) throws Exception {
// System.out.println("postHandle");
// modelAndView.addObject("msg", "postHandle!!");
// } // method End
} // class End
이렇게 작성을 해준 뒤.. 혹시 "no"가 아닌 다른 방법으로 인터셉터에 넣을려면 id 뭐 name 상관없다 이건 맘대로 나는 왜 no 를 했냐면
세션에 no를 담았기 때문에,,,
request.getSession().setAttribute("no", no); // 세션에 회원번호를 담는다.
그 다음엔 servlet-context.xml 에 인터셉터 설정을 꼭!! 해줘야한다. 설명은 됐으니 코드를 보자
<!-- Session Interceptor -->
<interceptors>
<interceptor>
<!-- mapping의 모든 요청은 Controller에 도착하기 전에 가로챈다. -->
<mapping path="/*" />
<!-- exclude-mapping의 요청은 가로채지 않는다. -->
<!-- "/" 추가하지 않으면 무한 루프 -->
<exclude-mapping path="/" />
<exclude-mapping path="/loginProcess" />
<exclude-mapping path="/loginForm" />
<exclude-mapping path="/joinChoiceForm" />
<exclude-mapping path="/personalJoinAgreement" />
<exclude-mapping path="/personalJoinForm" />
<exclude-mapping path="/personalJoin" />
<exclude-mapping path="/emailConfirmOffer" />
<exclude-mapping path="/emailConfirmSuccess" />
<exclude-mapping path="/admin" />
<exclude-mapping path="/adminLogin" />
<exclude-mapping path="/businessBasicInfo" />
<exclude-mapping path="/businessGallery" />
<exclude-mapping path="/businessDetailNoticeList" />
<exclude-mapping path="/businessNoticeDetail"/>
<exclude-mapping path="/dashboard" />
<exclude-mapping path="/businessDetailPage" />
<exclude-mapping path="/favoriteChange" />
<exclude-mapping path="/personalCalendar" />
<exclude-mapping path="/businessJoinAgreement" />
<exclude-mapping path="/businessJoinForm" />
<exclude-mapping path="/emailCheck" />
<exclude-mapping path="/taxIdCheck" />
<exclude-mapping path="/businessJoin" />
<exclude-mapping path="/businessList" />
<exclude-mapping path="/searchList" />
<exclude-mapping path="/findMyIdForm" />
<exclude-mapping path="/findMyId" />
<exclude-mapping path="/findMyPw" />
<exclude-mapping path="/resetMyPwForm" />
<exclude-mapping path="/updateMyPw" />
<exclude-mapping path="/tagSelectList" />
<exclude-mapping path="/butTagSelectList" />
<exclude-mapping path="/tagSelectListAddr" />
<exclude-mapping path="/butTagSelectListPaging" />
<!-- Intercepter에 의해 가로챈 요청을 체크하는 클래스 -->
<beans:bean
class="com.teamx.respets.userClass.SessionInterceptor"></beans:bean>
</interceptor>
</interceptors>
exclude-mapping 엔 세션검사를 하지 않아도 되는 url을 넣어주면 된다.
그리고 마지막으로 내가 만든 세션인터셉터 클래스의 위치를 써주면 인터셉터 설정이 완료 된다.
간단하고 참으로 편한 방법이다. 매번 세션 검사를 안해줘도 되니까ㅎ