SpringMVC拦截器例子
1 界面登录验证
1.1 准备工作
1.1.1 导入servlet-api依赖
< dependency>
< groupId> org.apache.tomcat</ groupId>
< artifactId> servlet-api</ artifactId>
< version> 6.0.53</ version>
</ dependency>
1.1.2 创建员工控制类(EmpController类)
package com. controller ;
import org. springframework. stereotype. Controller ;
import org. springframework. web. bind. annotation. RequestMapping ;
import javax. servlet. http. HttpSession ;
@Controller
@RequestMapping ( "emps" )
public class EmpController {
@RequestMapping ( "find" )
public String find ( ) {
System . out. println ( "查询员工" ) ;
return "index" ;
}
@RequestMapping ( "delete" )
public String delete ( ) {
System . out. println ( "删除员工" ) ;
return "index" ;
}
@RequestMapping ( "add" )
public String add ( ) {
System . out. println ( "添加员工" ) ;
return "index" ;
}
}
1.2 在EmpController类里面创建登录和注销方法
@RequestMapping ( "login" )
public String login ( HttpSession session) {
session. setAttribute ( "users" , "张三" ) ;
return "index" ;
}
@RequestMapping ( "logout" )
public String logout ( HttpSession session) {
session. removeAttribute ( "users" ) ;
return "index" ;
}
1.3 创建登录拦截类(LoginInterceptor)
package com. interceptor ;
import org. springframework. web. servlet. HandlerInterceptor ;
import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpServletResponse ;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle ( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object users = request. getSession ( ) . getAttribute ( "users" ) ;
if ( users== null ) {
System . out. println ( "被登录拦截器拦截了" ) ;
request. setAttribute ( "msg" , "请先登录" ) ;
request. getRequestDispatcher ( "/index.jsp" ) . forward ( request, response) ;
return false ;
}
return true ;
}
}
1.4 在主配置文件SpringMvc2.xml里面进行拦截器的配置
< mvc: interceptor>
< mvc: mapping path = " /emps/**" />
< mvc: exclude-mapping path = " /emps/find*" />
< mvc: exclude-mapping path = " /emps/log*" />
< bean class = " com.interceptor.LoginInterceptor" > </ bean>
</ mvc: interceptor>
1.5 编写首页index.jsp页面
<%--
Created by IntelliJ IDEA.
User: SSS翱翔万里
Date: 2022/11/13
Time: 15:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>进入了首页</h1>
消息:${msg}<br>
${users==null ?'未登录':'已登录 用户:'}${users}
<a href="/emps/login">登录</a>
<a href="/emps/logout">注销</a><br>
<a href="/emps/find">查询用户</a>
<a href="/emps/delete">删除用户</a>
<a href="/emps/add">添加用户</a>
</body>
</html>
1.6 测试运行截图
1.6.1 未登录时点击删除用户
a 点击前
b 点击后
c 控制台信息截图
1.6.2 已登录时点击删除用户
a 点击前
b 点击后
c 控制台信息截图
1.6.3 未登录时点击查询用户
a 点击前
b 点击后
c 控制台信息截图
1.6.4 已登录时点击查询用户
a 点击前
b 点击后
c 控制台信息截图
1.6.5 未登录时点击添加用户
a 点击前
b 点击后
c 控制台信息截图
1.6.6 已登录时点击添加用户
a 点击前
b 点击后
c 控制台信息截图