springmvc拦截器和过滤器使用(SpringMVC拦截器使用)
导读:SpringMVC拦截器 拦截器是用来干什么的?...
SpringMVC拦截器
拦截器是用来干什么的?
在一个登录功能中 ,如果用户没有登录却尝试通过地址栏直接访问内部服务器资源 ,这显然是非法的 。怎样对这些的非法访问进行拦截? SpringMVC的拦截器可以解决这个问题 。
使用拦截器
编写拦截器
创建拦截器类,实现HandlerInterceptor接口按需要实现preHanlder 、postHanlder 、afterCompeletion方法 ,这些方法的返回值是boolean型 ,为true表示不进行拦截 ,false表示进行拦截 ,这些方法有默认实现 ,按需求实现即可
preHanlder方法:在访问资源之前执行
postHanlder方法:在进行响应之前执行
afterCompeletion方法:在进行响应之后执行
public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(request.getSession().getAttribute("name") == null){//用户未登录 request.setAttribute("msg","您还没有登录 ,请先登录!"); return false;//进行拦截 }else{ return true;//不进行拦截 } } }修改配置文件
修改springmvc.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.tzq"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--注册拦截器--> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/><!--要拦截哪些路径,/**表示拦截所有路径--> <mvc:exclude-mapping path="/showLogin"/><!--不进行拦截的路径--> <mvc:exclude-mapping path="/login"/> <!--拦截器实现类 ,可以有多个 ,形成拦截链 ,责任链设计模式--> <bean class="com.tzq.springmvc.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> </beans>在浏览器地址栏中输入http:localhost:8080/main后,由于进行了拦截 ,出现404错误无法访问
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!