728x90
관련 포스팅 : Spring - Filter, Interceptor, AOP
인터셉터를 간단하게 테스트 해보자.
1. servlet-context.xml
인터셉터 설정
<!-- 인터셉터 bean 설정 -->
<beans:bean id="sampleInterceptor" class="com.example.spring02.interceptor.SampleInterceptor"/>
<interceptors>
<interceptor>
<!-- 인터셉터 매핑 -->
<mapping path="/doA"/>
<mapping path="/doB"/>
<beans:ref bean="sampleInterceptor"/>
</interceptor>
</interceptors>
2. 인터셉터 클래스
SampleInterceptor - 인터셉터 요청을 처리할 클래스 작성
package com.example.spring02.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class SampleInterceptor extends HandlerInterceptorAdapter{
// 요청전에 실행
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("pre hanlde.....");
return true;
}
// 요청 후에 실행
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("post handle....");
}
}
3. 컨트롤러
HomeController
package com.example.spring02;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
// doA 매핑
@RequestMapping("/doA")
public String doA(){
logger.info("doA.....");
return "home";
}
// doB 매핑
@RequestMapping("/doB")
public String doB(Model model){
logger.info("doB.....");
model.addAttribute("result", "do b result");
return "home";
}
}
4. 요청 후 콘솔 확인
Interceptor : pre hanlde.....
14:54:25.891 [http-nio-80-exec-2] INFO [com.example.spring02.HomeController.doA:30]-
doA.....
Interceptor : post handle....
doA요청 후 콘솔확인
Interceptor : pre hanlde.....
14:55:05.672 [http-nio-80-exec-5] INFO [com.example.spring02.HomeController.doB:37]-
doB.....
Interceptor : post handle....
doB요청 후 콘솔 확인