본문 바로가기

Archived(Programming)/Spring #1(기초)

Spring_Interceptor

# 글 작성 시 LoginSession에 대한 선행(PRE) Interceptor

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.sinc.intern.**" />
	
	<beans:bean id="sample" class="com.sinc.intern.util.interceptor.TestInterceptor"/>
	<beans:bean id="login" class="com.sinc.intern.user.util.LoginInterceptor"/>
	<beans:bean id="check" class="com.sinc.intern.user.util.SessionChkInterceptor"/>
	
	<interceptors>
		...
		<interceptor>
			<mapping path="/registerForm.do"/>
			<beans:ref bean="check"/>
		</interceptor>
	</interceptors>	
</beans:beans>
package com.sinc.intern.user.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class SessionChkInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
	throws Exception {
		System.out.println("session interceptor preH ~~");
		HttpSession session = request.getSession();
		// Attribute를 가져오니 null일 경우
		if(session.getAttribute("loginUser") == null) {
			System.out.println("session is null");
			response.sendRedirect("/loginForm.do");
			return false;
		}
		return true;
	}
}