<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<mvc:default-servlet-handler/>
<!-- Controller包(自动注入) -->
<context:component-scan base-package="com.**.controller"/>
<!-- 配置拦截器 -->
<mvc:interceptors>
<!-- 配置一个全局拦截器,拦截所有请求 -->
<mvc:interceptor>
<!-- 配置拦截器作用的路径 -->
<mvc:mapping path="/**" />
<!-- 配置不需要拦截作用的路径 -->
<mvc:exclude-mapping path="/" />
<mvc:exclude-mapping path="/login" />
<!-- 定义<mvc:interceptor>元素中,表示匹配指定路径的请求才进行拦截 -->
<bean class="com.hwxx.common.web.AccessInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
先配置xml中的配置类,然后再 创建?/eam/src/main/java/com/hwxx/common/web/AccessInterceptor.java 类
package com.hwxx.common.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import com.hwxx.system.entity.SysUsers;
/**
* MVC拦截器- 拦截所有的页面- 除了login 登录页面
* @author
* 2022-3-13
*/
public class AccessInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String url = request.getRequestURL().toString();
if(url.endsWith("/login") || url.endsWith("/") || url.endsWith("/index"))
return true;
//判断是否已经登录
HttpSession session = request.getSession();
SysUsers sysUsers = (SysUsers)session.getAttribute("sysUsers");
if(sysUsers == null) {
response.sendRedirect("http://localhost/eam/login");
}
System.out.println("MVC拦截器111111111");
return false; //false拦截所有的, true是放行
}
}
还有一种方法: 是通过注解配置类的方式拦截,这两种二选其一
package com.hwxx.common.web;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class SpringMebConfig implements WebMvcConfigurer{
//配置spring mvc拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AccessInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login"); //放行哪个不拦截
}
}
|