✅作者简介:Java-小白后端开发者 公认外号:球场上的黑曼巴
个人主页:不会飞的小飞侠24
个人信条:谨 · 信
当前专栏:高级内容
本文内容: SpringMVC【拦截器】登录验证
更多内容点击
小飞侠的博客>>>>欢迎大家!!!
SpringMVC中的Interceptor拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的
处理。比如通过它来进行权限验证,或者是来判断用户是否登录等操作。对于SpringMVC拦截器的定义方式有两
种
(1)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<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:springmvc03-config.xml</param-value>
</init-param>
<!--tomcat启动就创建该实例对象-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
(2)pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
<!--引入json格式转换的依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.14.1</version>
</dependency>
(3)springmvc-config.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
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 代替以上 配置 支持json数据格式的解析 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!--配置内部视图解析器 InternalResourceViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/" ></property>
<!--后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
<!--开启包扫描-->
<context:component-scan base-package="cn.syb.springmvc03"></context:component-scan>
<!--静态资源的处理 不需要经过前端控制器 tomcat-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!--设置拦截路径-->
<mvc:mapping path="/**"/>
<!--设置不要拦截的路径-->
<mvc:exclude-mapping path="/user/login"/>
<mvc:exclude-mapping path="/user/getcode"/>
<!--自定义拦截器-->
<bean class="cn.syb.springmvc03.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>
package cn.syb.springmvc03.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("-------拦截器---------------");
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
if(user==null){
response.sendRedirect("/login.jsp");
}
return true;
}
}
java public class MyInterceptor2 extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
} }
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页</title>
<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form>
<p><input type="text" name="username" placeholder="请输入用户名" id="username"></p>
<p><input type="password" name="password" placeholder="请输入密码" id="password"></p>
<p><input type="text" name="code" placeholder="请输入验证码" id="code"></p>
<p><input type="button" value="登录" id="login"></p>
</form>
<%--//异常提示信息--%>
<span id="msg" style="color: red"></span>
<script>
//给login 添加点击事件
$("#login").click(function (){
//赋值
let username = $("#username").val()
let password = $("#password").val()
let code = $("#code").val()
//简写的JSon
$.get("/user/login",{username,password,code},function (res){
if(res.code==200){
window.location.href="/userIndex.jsp"
}else {
//拿信息
let info = res.msg;
//获取信息
$("#msg").text(info)
}
})
})
</script>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户主页面</title>
</head>
<body>
<h2>用户信息主页面</h2>
<p>
<a href="/user/add?username=jack&password=123">添加</a>
</p>
<p>
<a href="/user/delete?id=10">删除</a>
</p>
<p>
<a href="/user/logout">退出登录</a>
</p>
</body>
</html>
package cn.syb.springmvc03.UserController;
import cn.syb.springmvc03.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* @Author: 课工场
* @Version: v1.0 2023/3/1
* @Description:
* @CookieValue 获取cookie中执行key的值
* @SessionAttribute 获取session中指定key的值
*/
@Controller
@RequestMapping("user")
public class UserController {
@RequestMapping("login")
@ResponseBody
// , @SessionAttribute("code") String attribute
public Map<String, Object> login(User user, HttpSession session,@SessionAttribute("code") String attribute) {
HashMap<String, Object> map = new HashMap<>();
// String attribute = (String) session.getAttribute("code");
System.out.println("attribute = " + attribute);
String code = user.getCode();
if(code.equals(attribute)){
if ("tom".equals(user.getUsername()) && "12345".equals(user.getPassword())) {
// 将用户信息存入session
session.setAttribute("user", user);
map.put("code", 200);
map.put("msg", "登录成功");
} else {
map.put("code", 500);
map.put("msg", "登录失败");
}
}else{
map.put("code", 500);
map.put("msg", "验证码错误");
}
return map;
}
@RequestMapping("add")
@ResponseBody
// @CookieValue
public Map<String, Object> add( User user) {
HashMap<String, Object> map = new HashMap<>();
map.put("code", 200);
map.put("msg", "添加成功 user= " + user);
return map;
}
@RequestMapping("delete")
@ResponseBody
public Map<String, Object> delete(Integer id) {
HashMap<String, Object> map = new HashMap<>();
map.put("code", 200);
map.put("msg", "删除成功 id = " + id);
return map;
}
@RequestMapping("logout")
public String logout(HttpSession session) {
session.invalidate();
//转发
return "login";
}
@RequestMapping("getcode")
@ResponseBody
public Map<String,Object> getCode(HttpSession session) {
HashMap<String, Object> map = new HashMap<>();
Random random = new Random();
int value = random.nextInt(10000);
session.setAttribute("code", value);
map.put("code", value);
return map;
}
}