SpringMVC使用拦截器和过滤器

来源:互联网 发布:js闭包的好处和坏处 编辑:程序博客网 时间:2024/06/04 19:12

1.使用过滤器:场景:过滤乱码

web.xml文件中配置

  <!--字符过滤器及编码utf-8-->    <filter>      <filter-name>characterEncodingFilter</filter-name>      <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>      <init-param>          <param-name>encoding</param-name>          <param-value>UTF-8</param-value>      </init-param>      <init-param>          <param-name>forceEncoding</param-name>          <param-value>true</param-value>      </init-param>    </filter>    <filter-mapping>      <filter-name>characterEncodingFilter</filter-name>      <url-pattern>/*</url-pattern>    </filter-mapping>
2.使用拦截器:Interceptor

首先在***-servlet.xml中配置,注册拦截器

<?xml version="1.0" encoding="UTF-8" standalone="no"?>  <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-3.0.xsd       http://www.springframework.org/schema/context       http://www.springframework.org/schema/context/spring-context-3.0.xsd       http://www.springframework.org/schema/mvc       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
三个MVC是必需的,命名空间之类

<!-- 此处是拦截器,拦截path为“/clients/login”的请求,执行com.damion.controller.TestInterceptor中的拦截方法 -->    <mvc:interceptors><mvc:interceptor><mvc:mapping path="/clients/login"></mvc:mapping><bean class="com.damion.controller.TestInterceptor"></bean></mvc:interceptor></mvc:interceptors> 
TestInterceptor

public class TestInterceptor implements HandlerInterceptor{public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {//使用场景:过滤字符编码request.setCharacterEncoding("utf-8");//使用场景:判断用户是否登陆,用户未登录返回登录页面if(request.getSession().getAttribute("user")==null) {request.getRequestDispatcher("/clients/login").forward(request, response);return false;}System.out.println("执行到此处preHandle");//返回值表示拦截到此处,是否继续执行//false表示停止执行,true表示继续执行return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {modelAndView.addObject("msg", "从postHandle获得的msg");System.out.println("执行到此处postHandle");}public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {System.out.println("执行到此处afterCompletion");}}






原创粉丝点击