2013년 11월 27일 수요일

[스프링3.X 인터셉터]Spring3 MVC Interceptor, 스프링인터셉터, HandlerInterceptor, postHandle,preHandle

[스프링3.X 인터셉터]Spring3 MVC Interceptor, 스프링인터셉터,  HandlerInterceptor, postHandle,preHandle



Spring3 MVC는 서블릿 필터와 유사하게 HTTP Request(요청)를 앞단/뒤단에서 가로챌 수 있는 메커니즘을 제공한다.(org.springframework.web.servlet.HandlerInterceptor )
 
인터셉터가 되기 위해서는 HandlerInterceptor를 구현해야 하는데 preHandle(), postHandle(), afterCompletion() 세개의 메소드를 구현해야 한다.
 
  preHandle() : 컨트롤러가 실행되기 전에 실행되며 bool형 리턴 한다. 실행체인에서 계속 실행할지 중단할지를 true, false로 전달한다. false가 리턴되면 디스패처 서블릿은 핸들러가 직접 요청을 처리하여, 뷰를 직접 다룬다고 생각하고 다른 인터셉터나 핸들러의 실행을 중단한다.
 
 postHandle() : 컨트롤러 실행 후
 
afterCompletion() : 모든 요청 처리 후에 실행
 
 xml 설정 파일에는 구현한 인터셉터를 정의해야 한다.
 
<mvc:interceptors>
    <bean class=“onj.edu.interceptor.HelloWorldInterceptor" />
</mvc:interceptors>
 
1. spring mvc 프로젝트를 만들자.
 
top-lovel package명의 마지막을 interceptor로 줘서 웹사이트 context명이 interceptor이다.

pom.xml
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
</dependency>
<dependency>      
   <groupId>org.springframework</groupId>      
   <artifactId>spring-webmvc</artifactId>      
   <version>3.2.3.RELEASE</version>  
</dependency>

2. HelloController.java
 
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HelloController {
   @RequestMapping(value = "/hello", method = RequestMethod.GET)
   public String sayHello() {
      System.out.println("여긴 컨트롤러...");
      //hello가 리턴되어 view가 /jsp/hello.jsp가 된다.
      return "hello";
   }
}
 
3. HelloInterceptor.java

package interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class HelloInterceptor implements HandlerInterceptor {
 public boolean preHandle(HttpServletRequest req,
                    HttpServletResponse res,
                    Object handler) {
  System.out.println("preHandle~~~");
  return true;
 }

 public void postHandle(HttpServletRequest req,
                           HttpServletResponse res,
                           Object handler,
                           ModelAndView mv) {
  System.out.println("postHAndle~~~");
 }

 public void afterCompletion(HttpServletRequest req,
                                HttpServletResponse res,
                                Object handler,
                                Exception ex) {
  System.out.println("afterCompletion~~~");
 }

}
 
4. webapps/jsp/hello.jsp
 
<html>
<head>
<title>OnJProgramming, OracleJava Community</title>
</head>
<body>
<h1>Hello!!</h1>
</body>
</html>
 
5. /WEB-INF/web.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
    <servlet-name>onj</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>onj</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
</web-app>

6. /WEB-INF/onj-servlet.xml
 
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 <context:annotation-config />
 <context:component-scan base-package="controller" />

 <mvc:interceptors>
  <bean class="interceptor.HelloInterceptor" />
 </mvc:interceptors>

 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>
</beans>
 
7. 실행
 

10월 24, 2013 11:14:59 오후 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
10월 24, 2013 11:14:59 오후 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
10월 24, 2013 11:14:59 오후 org.apache.catalina.startup.Catalina start
INFO: Server startup in 2062 ms
preHandle~~~
여긴 컨트롤러...
postHAndle~~~
afterCompletion~~~
 
 

댓글 없음:

댓글 쓰기