设为首页 加入收藏

TOP

SpringMVC拦截器使用
2023-07-25 21:41:24 】 浏览:40
Tags:SpringMVC

SpringMVC拦截器

拦截器是用来干什么的?

在一个登录功能中,如果用户没有登录却尝试通过地址栏直接访问内部服务器资源,这显然是非法的。怎样对这些的非法访问进行拦截? SpringMVC的拦截器可以解决这个问题。

使用拦截器

编写拦截器

创建拦截器类,实现HandlerInterceptor接口按需要实现preHanlder、postHanlder、afterCompeletion方法,这些方法的返回值是boolean型,为true表示不进行拦截,false表示进行拦截,这些方法有默认实现,按需求实现即可

preHanlder方法:在访问资源之前执行

postHanlder方法:在进行响应之前执行

afterCompeletion方法:在进行响应之后执行
image

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错误无法访问
image

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java 认证与授权(JAAS)介绍 下一篇学习笔记——Maven的基本配置、Ma..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目