新手进行的一个简单拦截器开发
开发工具: IDEA
项目结构
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SSM-StudyDemo</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>SSM-SpringMVc</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!--servelt-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0-b07</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>SSM</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
实体类
package Com.Demo.pojo;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User() {
}
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
}
拦截器
package Com.Demo.Config;
import Com.Demo.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//拦截器,拦截用户的请求并作出相应的处理
public class LoginExterceptor implements HandlerInterceptor {
/*
* preHandle: 该方法会在控制器方法前执行,其返回值表示是否中断后续操作
* */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("正在进入preHandle方法");
HttpSession session = request.getSession(false);
// 获取session
User user = (User) session.getAttribute("user");
if (user ==null){
//跳转到登录界面
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
}
return true;
}
/*
* postHandle:该方法会在控制器方法调用之后,且解析视图之前执行
* */
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("正在进入postHandle方法");
}
/*
* afterCompletion: 该方法会在整个请求完成,即视图渲染结束之后执行
* */
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("正在进入afterCompletion方法");
}
}
控制器
package Com.Demo.Controller;
import Com.Demo.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
public class UserController {
@RequestMapping("/hello")
public String Test(Model model){
model.addAttribute ("msg","HelloWorld");
System.out.println("控制层");
return "Hello";
}
@RequestMapping("/login")
public String login(HttpServletRequest request,User user) {
// 创建Session
HttpSession session = request.getSession();
String username = user.getUsername();
String password = user.getPassword();
//把用户名和密码存到session域中
session.setAttribute("user", user);
return "login";
}
@RequestMapping("/welcome")
public String welcome(){
return "welcome";
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>filter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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:SpringMvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!--/ 表示所有请求都会被dispatcherServlet拦截-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<context:component-scan base-package="Com.Demo.Controller"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置拦截器-->
<mvc:interceptors>
<!--拦截器的指定路径-->
<mvc:interceptor>
<!--拦截器作用路径,path ="/**" 表示拦截所有路径-->
<mvc:mapping path="/**"/>
<!--mvc:exclude-mapping path="" :指定不需要拦截的对象-->
<mvc:exclude-mapping path="/login"/>
<mvc:exclude-mapping path="/welcome"/>
<!--表示匹配指定路径的请求-->
<bean class="Com.Demo.Config.LoginExterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
接下来是:
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="/hello">点我进入主页</a>
<a href="/login">登录</a>
</body>
</html>
Hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
welcome
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>欢迎</h2>
</body>
</html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/welcome" method="post">
用户名: <input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="提交"><br>
</form>
</body>
</html>
运行结果