Spring Web MVC的拦截器类似于servlet开发中的filter过滤器,用于对处理器进行预处理和后处理。
想要写一个拦截器只需要让拦截器实现HandlerInterceptor接口,并在springmvc.xml中进行配置即可使用。
拦截器:
HandlerInterceptor接口:
该接口一共有三个方法:
1 2 3 4 5 6 7 8 9 10 11 12
| public interface HandlerInterceptor { default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; }
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { }
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { } }
|
编写拦截器时需要实现此接口根据不同的需要重写不同的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class MyHandlerInterceptor1 implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; }
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { }
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { } }
|
springmvc.xml中配置拦截器:
写好HandlerInterceptor之后需要在springmvc.xml中进行拦截器的配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <mvc:interceptors> <mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="nynu.li.interceptor.MyHandlerInterceptor1"></bean> </mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="nynu.li.interceptor.MyHandlerInterceptor2"></bean> </mvc:interceptor> </mvc:interceptors>
|
注意:preHandle按拦截器定义顺序调用
postHandler按拦截器定义逆序调用
afterCompletion按拦截器定义逆序调用
postHandler在拦截器链内所有拦截器的preHandle都返回成功才调用
afterCompletion只有自身拦截器的preHandle返回true才调用
转换器:
主要用作自定义参数绑定时,前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。可以在springmvc处理器适配器上自定义转换器Converter进行参数绑定。
一般使用<mvc:annotation-driven/>注解驱动加载处理器适配器,可以在此标签上进行配置。
Converter<S,T>接口:
1 2 3 4 5 6 7
| @FunctionalInterface
public interface Converter<S, T> { @Nullable T convert(S var1); }
|
要想自定义一个转换器,只需要实现Converter接口即可:
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class DateConverter implements Converter<String,Date> { public Date convert(String date) { SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date targetDate = null; try { targetDate = sdf.parse(date); } catch (ParseException e) { e.printStackTrace(); } return targetDate; } }
|
springmvc.xml中配置拦截器:
1 2 3 4 5 6 7 8 9 10
| <bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean" name="formattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="nynu.li.converter.DateConverter"></bean> </set> </property> </bean>
<mvc:annotation-driven conversion-service="formattingConversionServiceFactoryBean"/>
|