您的位置:首页 > 编程语言 > Java开发

Spring拦截器

2015-09-20 18:41 525 查看
Spring Interceptors具备前处理和后处理web请求的能力,每一个拦截器类应当继承HandlerInterceptorAdapter类,你可以覆写任意preHandle(),postHandle()或afterCompletion()这三个回调方法。正如这个名字一样preHandler()方法会在处理请求之前被调用,postHandle()方法会在处理请求之后调用,而afterCompletion()将会在显示视图后被调用。

在每个方法里我们将使用log4j记录日志信息,首先应该实例化一个静态日志记录器,然后建立基本配置使得日志信息能显示在控制台。

LoggerInterceptor 类如下:

[java] view plaincopy

package com.zcl.spring.interceptor;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.BasicConfigurator;

import org.apache.log4j.Logger;

import org.springframework.web.servlet.ModelAndView;

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

public class LoggerInterceptor extends HandlerInterceptorAdapter {

static Logger logger = Logger.getLogger(LoggerInterceptor.class) ;

static{

BasicConfigurator.configure() ;

}

@Override

public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception{

logger.info("Before handling the request") ;

return super.preHandle(request, response, handler) ;

}

@Override

public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView) throws Exception{

logger.info("After handling the request") ;

super.postHandle(request, response, handler, modelAndView) ;

}

@Override

public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex) throws Exception{

logger.info("After rendering the view") ;

super.afterCompletion(request, response, handler, ex) ;

}

}

现在你需要关联你已经创建的logger拦截器到映射处理,这里我们使用BeanNameUrlHandlerMapping,假如你需要的不止一个映射处理那么你需要将拦截器和它们每一个相关联。下面的配置即是如何关联拦截器到映射处理。

[html] view plaincopy

<?xml version="1.0" encoding="UTF-8"?>

<beans 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"
xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://www.springframework.org/schema/beans">

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">

<value>/WEB-INF/jsp/</value>

</property>

<property name="suffix">

<value>.jsp</value>

</property>

</bean>

<!--<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"

p:basename="message" />-->

<bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" p:interceptors-ref="loggerInterceptor" />

<bean id="loggerInterceptor" class="com.zcl.spring.interceptor.LoggerInterceptor" />

<!--<context:component-scan base-package="com.zcl.spring.validation" />-->

<bean id="userService" class="com.zcl.spring.validation.UserServiceImpl" />

<!-- <bean id="userValidator" class="com.zcl.spring.validation.UserValidator" />-->

<bean name="/userRegistration.html" class="com.zcl.spring.validation.UserController"

p:userService-ref="userService" p:formView="userForm"

p:successView="userSuccess" />

</beans>

这里我们也要注意一下UserController如下:

[java] view plaincopy

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.SimpleFormController;

@SuppressWarnings("deprecation")

public class UserController extends SimpleFormController {

private UserService userService ;

public UserController(){

setCommandClass(User.class) ;

setCommandName("user") ;

}

public void setUserService(UserService userService){

this.userService = userService ;

}

@Override

protected ModelAndView onSubmit(Object command) throws Exception{

User user = (User)command ;

userService.add(user) ;

return new ModelAndView("userSuccess","user",user) ;

}

}

运行后我们会在控制台看到如下信息:

[plain] view plaincopy

<span style="font-family:'Courier New', Courier, monospace;font-size:16px;"><span style="line-height: 1.5;">51242 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' determining Last-Modified value
for [/spring3/userRegistration.html]

51243 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping@116aeb] in DispatcherServlet with name 'dispatcher'

51248 [http-8888-2] DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping - Mapping [/userRegistration.html] to handler 'com.zcl.spring.validation.UserController@1e13ce3'

51248 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter@1be9101]

51251 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter@ce4dda]

51253 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/spring3/userRegistration.html] is: -1

51276 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Bound request context to thread: org.apache.catalina.connector.RequestFacade@6ea9d2

51276 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' processing GET request for [/spring3/userRegistration.html]

51280 [http-8888-2] INFO com.zcl.spring.interceptor.LoggerInterceptor - Before handling the request

51280 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter@1be9101]

51280 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter@ce4dda]

51280 [http-8888-2] DEBUG com.zcl.spring.validation.UserController - Displaying new form

51281 [http-8888-2] DEBUG com.zcl.spring.validation.UserController - Creating new command of class [com.zcl.spring.validation.User]

51312 [http-8888-2] INFO com.zcl.spring.interceptor.LoggerInterceptor - After handling the request

51318 [http-8888-2] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'userForm'

51318 [http-8888-2] DEBUG org.springframework.web.servlet.view.InternalResourceViewResolver - Cached view [userForm]

51318 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'userForm'; URL [/WEB-INF/jsp/userForm.jsp]] in DispatcherServlet with name 'dispatcher'

51318 [http-8888-2] DEBUG org.springframework.web.servlet.view.JstlView - Rendering view with name 'userForm' with model {org.springframework.validation.BindingResult.user=org.springframework.validation.BeanPropertyBindingResult: 0 errors, user=com.zcl.spring.validation.User@c26acd}
and static attributes {}

51319 [http-8888-2] DEBUG org.springframework.web.servlet.view.JstlView - Added model object 'user' of type [com.zcl.spring.validation.User] to request in view with name 'userForm'

51319 [http-8888-2] DEBUG org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.user' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'userForm'

51378 [http-8888-2] DEBUG org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/jsp/userForm.jsp] in InternalResourceView 'userForm'

53139 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Getting BeanInfo for class [com.zcl.spring.validation.User]

53144 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Caching PropertyDescriptors for class [com.zcl.spring.validation.User]

53144 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Found bean property 'aboutYou' of type [java.lang.String]

53144 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Found bean property 'class' of type [java.lang.Class]

53144 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Found bean property 'community' of type [[Ljava.lang.String;]

53144 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Found bean property 'country' of type [java.lang.String]

53144 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Found bean property 'gender' of type [java.lang.String]

53144 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Found bean property 'mailingList' of type [boolean]

53144 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Found bean property 'name' of type [java.lang.String]

53144 [http-8888-2] DEBUG org.springframework.beans.CachedIntrospectionResults - Found bean property 'password' of type [java.lang.String]

53146 [http-8888-2] DEBUG org.springframework.beans.BeanUtils - No property editor [java.lang.StringEditor] found for type java.lang.String according to 'Editor' suffix convention

53157 [http-8888-2] DEBUG org.springframework.beans.BeanUtils - No property editor [booleanEditor] found for type boolean according to 'Editor' suffix convention

53157 [http-8888-2] INFO com.zcl.spring.interceptor.LoggerInterceptor - After rendering the view

53158 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@6ea9d2

53158 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request

53158 [http-8888-2] DEBUG org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in context [org.springframework.web.context.support.XmlWebApplicationContext@d7c6bf]: ServletRequestHandledEvent: url=[/spring3/userRegistration.html];
client=[0:0:0:0:0:0:0:1]; method=[GET]; servlet=[dispatcher]; session=[388885EBAC9B01B2FB0DC28FE9EBDCDD]; user=[null]; time=[1905ms]; status=[OK]

75058 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Bound request context to thread: org.apache.catalina.connector.RequestFacade@6145c5

75058 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' processing POST request for [/spring3/userRegistration.html]

75059 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping@116aeb] in DispatcherServlet with name 'dispatcher'

75059 [http-8888-2] DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping - Mapping [/userRegistration.html] to handler 'com.zcl.spring.validation.UserController@1e13ce3'

75059 [http-8888-2] INFO com.zcl.spring.interceptor.LoggerInterceptor - </span></span><span style="color:#ff0000;font-family: 'Courier New', Courier, monospace; font-size: 10pt; line-height: 1.5; ">Before handling the request</span><span style="font-family:'Courier
New', Courier, monospace;font-size:16px;"><span style="line-height: 1.5;">

75059 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter@1be9101]

75059 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter@ce4dda]

75059 [http-8888-2] DEBUG com.zcl.spring.validation.UserController - Creating new command of class [com.zcl.spring.validation.User]

75064 [http-8888-2] DEBUG org.springframework.beans.TypeConverterDelegate - Converting String to [boolean] using property editor [org.springframework.beans.propertyeditors.CustomBooleanEditor@1d1f3f2]

75065 [http-8888-2] DEBUG com.zcl.spring.validation.UserController - No errors -> processing submit

</span></span><span style="color:#ff0000;font-family: 'Courier New', Courier, monospace; font-size: 10pt; line-height: 1.5; ">User add Success</span><span style="font-family:'Courier New', Courier, monospace;font-size:16px;"><span style="line-height: 1.5;">

75065 [http-8888-2] INFO com.zcl.spring.interceptor.LoggerInterceptor - </span></span><span style="color:#ff0000;font-family: 'Courier New', Courier, monospace; font-size: 10pt; line-height: 1.5; ">After handling the request</span><span style="font-family:'Courier
New', Courier, monospace;font-size:16px;"><span style="line-height: 1.5;">

75065 [http-8888-2] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'userSuccess'

75065 [http-8888-2] DEBUG org.springframework.web.servlet.view.InternalResourceViewResolver - Cached view [userSuccess]

75065 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'userSuccess'; URL [/WEB-INF/jsp/userSuccess.jsp]] in DispatcherServlet with name 'dispatcher'

75065 [http-8888-2] DEBUG org.springframework.web.servlet.view.JstlView - Rendering view with name 'userSuccess' with model {user=com.zcl.spring.validation.User@e6a73d} and static attributes {}

75065 [http-8888-2] DEBUG org.springframework.web.servlet.view.JstlView - Added model object 'user' of type [com.zcl.spring.validation.User] to request in view with name 'userSuccess'

75065 [http-8888-2] DEBUG org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/jsp/userSuccess.jsp] in InternalResourceView 'userSuccess'

75369 [http-8888-2] INFO com.zcl.spring.interceptor.LoggerInterceptor - </span></span><span style="color:#ff0000;font-family: 'Courier New', Courier, monospace; font-size: 10pt; line-height: 1.5; ">After rendering the view</span><span style="font-family:'Courier
New', Courier, monospace;"><span style="font-size:16px;"><span style="line-height: 1.5;">

75369 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@6145c5

75369 [http-8888-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request</span></span>

75370 [http-8888-2] DEBUG org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in context [org.springframework.web.context.support.XmlWebApplicationContext@d7c6bf]: ServletRequestHandledEvent: url=[/spring3/userRegistration.html];
client=[0:0:0:0:0:0:0:1]; method=[POST]; servlet=[dispatcher]; session=[388885EBAC9B01B2FB0DC28FE9EBDCDD]; user=[null]; time=[311ms]; status=[OK]</span>

上即是记录的日志信息

如果我们要使用annotation,我们需要修改下UserController和配置文件。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: