过滤器与拦截器的区别:拦截器是AOP思想的具体应用。
过滤器
- servlet规范中的一部分,任何java web工程都可以使用
- 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截
拦截器
- 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
- 拦截器只会拦截访问的控制器方法, 如果访问的是jsp/html/css/image/js是不会进行拦截的
自定义拦截器
1.新建一个moudle,增加web支持
2.配置好web.xml和applicationContext.xml文件
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:appliactionContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--字符编码过滤器-->
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描包下的注解-->
<context:component-scan base-package="com.kuang.controller"/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.编写一个拦截器
public class MyInterceptor implements HandlerInterceptor {
//请求处理方法前执行
//return true 放行
//return false 拦截
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("======>执行前");
return true;
}
//请求处理方法后执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("======>执行后");
}
//dispatcherServlet处理后执行,做清理工作
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("======>清理");
}
}
4.在配置文件中拦截器
<mvc:interceptors>
<mvc:interceptor>
<!--/*拦截的是路径及其子路径的所有-->
<!--/kuang/* 只拦截/kuang/add这种,而/kuang/add/user不拦截-->
<!--/kuang/** 拦截kuang包下的所有-->
<mvc:mapping path="/**"/>
<bean class="com.kuang.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
5.编写index.jsp
<a href="${pageContext.request.contextPath}/interceptor">测试拦截器</a>
6.结果
验证用户是否登录 (认证用户)
1.编写index.jsp界面
现在可以直接进入登录界面和主界面,加完拦截器没登录就不能直接进入主界面了。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/interceptor">测试拦截器</a>
<hr/>
<a href="${pageContext.request.contextPath}/tologin">登录页面</a>
<a href="${pageContext.request.contextPath}/toMain">主页面</a>
</body>
</html>
2.编写登录界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
登录:<br>
<form action="${pageContext.request.contextPath}/login">
用户名:<input type="text" name="username"> <br>
密码:<input type="password" name="pwd"> <br>
<input type="submit" value="提交">
</form>
</body>
</html>
3.编写主界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
主页面
<br/>
${login}
<br/>
<a href="${pageContext.request.contextPath}/logout">注销</a>
</body>
</html>
4.编写控制器
@Controller
public class TestController {
@RequestMapping("/tologin")
public String toLogin(){
return "login";
}
@RequestMapping("/toMain")
public String toMain(){
return "main";
}
//登录
@RequestMapping("/login")
public String login(HttpSession session,String username){
System.out.println("登录成功");
session.setAttribute("login",username);
return "main";
}
//注销
@RequestMapping("logout")
public String logout(HttpSession session) throws Exception {
// session 过期
session.invalidate();
return "login";
}
}
5.编写拦截器
public class LoginInterceptor implements HandlerInterceptor {
//请求前拦截
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
//如果session中有东西,表示登录成功,放行
if (session.getAttribute("login")!=null){
return true;
}
//如果请求的url包括login表示是要去登录界面和正在登录,都放行
if (request.getRequestURI().contains("login")){
return true;
}
// 用户没有登陆跳转到登陆页面
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
return false;
}
}
6.配置拦截器
<mvc:interceptors>
<mvc:interceptor>
<!--/*拦截的是路径及其子路径的所有-->
<!--/kuang/* 只拦截/kuang/add这种,而/kuang/add/user不拦截-->
<!--/kuang/** 拦截kuang包下的所有-->
<mvc:mapping path="/**"/>
<bean class="com.kuang.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
然后可以测试了,在index.jsp中点击主界面会跳转的登录界面让你登录,登录成功后跳到main.jsp,关闭当前界面,不关闭浏览器,在打开index.jsp,点击主界面链接,可以直接进入主界面,是因为浏览器没关,session还在,拦截器判断session不为空,放行了。