SSM框架实战3--拦截器和过滤器
程序员文章站
2022-05-23 08:38:04
...
目的
设置拦截器和过滤器,实现用户登录的验证,防止用户在没有登录的情况下进行一些动作或进入其他页面
结构目录
## 步骤:
拦截器
创建一个interceptor包,包内创建一个LoginInterceptor类。实现org.springframework.web.servlet下的HandlerInterceptor接口,并实现它的三个方法。
package com.gongmao.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//点击被实现的接口HandlerInterceptor,右键点击Generate...,选择Override Methods...,选择以下的三个方法
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在拦截点执行拦截,如果返回的true则不执行拦截点后的操作(拦截成功)
//1、判断当前的User用户不为空;获取当前的登录方法
HttpSession session=request.getSession();
if (session.getAttribute("userInfo")!=null){
//不拦截
return true;
}else {
//进行拦截,返回登录页面
response.sendRedirect(request.getContextPath() + "/user/doLogin.do");
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//在处理中,进行拦截
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//执行完毕,返回前拦截
}
}
在spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 1、扫描注解位置(注解支持) -->
<context:component-scan base-package="com.gongmao.controller"/>
<!-- 2、配置映射处理器和适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!-- 也可以用这种 -->
<!--<mvc:annotation-driven></mvc:annotation-driven>-->
<!-- 3、视图的解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 4、配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截所有的mvc控制器 -->
<mvc:mapping path="/**"/>
<!-- 放行机制,可以测试/指定对某一个页面不进行拦截 -->
<mvc:exclude-mapping path="/user/doLogin.do"/>
<!-- 指定使用哪一个拦截器 -->
<bean class="com.gongmao.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
拦截器放行路径的两个操作
如上在spring-mvc.xml中配置放行路径,也可以不在配置文件中进行配置放行路径,而在拦截类中判断用户是否登录的的时候,通过if判断允许某些路径不用登陆就可以直接访问
String url=request.getRequestURI();
//if条件判断,indexOf()-->求字符串内路径出现对应字符串的下标
if (session.getAttribute("userInfo")!=null||url.indexOf("user/doLogin.do")!=-1){
//不进行拦截
return true;
}else {
//进行拦截,返回登录页面
response.sendRedirect(request.getContextPath() + "/user/doLogin.do");
return false;
}
过滤器
创建一个filter包,包内创建一个LoginFilter类,实现javax.servlet下的Filter接口,实现它的三个方法
package com.gongmao.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//接口Filter要选择servlet的
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//过滤器出生
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//servletRequest是接口,HttpServletRequest是实现,但是有些方法是HttpServletRequest独有的,你如说getSession
//HttpServletRequest接口是继承自servletRequest接口,增加了和Http相关的方法
//强转得到想要的request和response
HttpServletRequest request= (HttpServletRequest) servletRequest;
HttpServletResponse response= (HttpServletResponse) servletResponse;
//获取Session,indexOf()-->求字符串内路径出现对应字符串的下标
HttpSession session=request.getSession();
if(session.getAttribute("userInfo")==null&&request.getRequestURL().indexOf("/user/doLogin,do")==-1){
//没有登录
response.sendRedirect(request.getContextPath()+"/user/doLogin.do");
}else {
//已经登录,继续下一个请求(继续访问)
filterChain.doFilter(request,response);
}
}
@Override
public void destroy() {
}
}
在web.xml中配置Filter
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- 配置加载类路径文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- 解决中文乱码 -->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 前端控制器,制定加载spring-mvc.xml -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!-- 让服务器启动的时候,就进行创建servlet对象 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!--
* ,会用户端所有的请求都当做requestMapper制定的路径去处理,都会进controller
/ ,页面不会去拦截
*.do ,
-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 使用filter实现登录控制,拦截路径 -->
<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>com.gongmao.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/pages/*</url-pattern>
<url-pattern>*.jsp</url-pattern>
<url-pattern>/css/*</url-pattern>
<url-pattern>/img/*</url-pattern>
</filter-mapping>
</web-app>
区别
Filter是基于函数回调的,而Interceptor则是基于Java反射的。
Filter依赖于Servlet容器,而Interceptor不依赖于Servlet容器。
Filter对几乎所有的请求起作用,而Interceptor只能对action请求起作用。
Interceptor可以访问Action的上下文,值栈里的对象,而Filter不能。
在action的生命周期里,Interceptor可以被多次调用,而Filter只能在容器初始化时调用一次。
执行顺序
过滤前-拦截前-action执行-拦截后-过滤后
上一篇: (学习笔记)过滤器Filter
下一篇: Java 学习笔记 Filter过滤器