SpringMVC拦截器
2021/4/14 18:27:34
本文主要是介绍SpringMVC拦截器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
过滤器和拦截器区别
- 过滤器是servlet的
- 在url-pattern中配置了/*,可以对所有要访问的资源进行拦截
- 过滤器在SpringMVC框架中是特有的,只有SpringMVC框架的项目才能使用
- 过滤器只会拦截访问控制器(Controller)的方法,如果访问的jsp/html/css/js是不会进行拦截的
如何使用拦截器
使用SpringMVC的拦截器只需实现HandlerInterceptor
接口并在配置文件中配<mvc:interceptors>
即可
public class MyInterceptor implements HandlerInterceptor { // return true 执行下一个拦截器,放行 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("=========拦截前========="); return true; } // 在HandlerAdapter实际调用处理程序之后但在DispatcherServlet呈现视图之前调用。 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("=========拦截后========="); } // 完成请求处理后(即渲染视图后)的回调。将在处理程序执行的任何结果上被调用,从而允许*进行适当的资源清理。 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("=========清理========="); } }
resources\applicationContext.xml
<!--拦截器--> <mvc:interceptors> <mvc:interceptor> <!--拦截的请求路径 /admin/** 拦截路径下的所有请求及其子请求 /admin/user/add会被拦截 /admin/* 拦截路径下的所有请求不包含其子请求 /admin/user会被拦截 /admin/user/add就不会被拦截 --> <mvc:mapping path="/**"/> <!--使用哪个拦截器--> <bean class="com.starry.interceptor.MyInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
用户登录验证
创建maven-web项目
pom.xml
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.18.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
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"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encoding</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>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
applicationContext.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 https://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.starry.controller"/> <!--mvc注解支持--> <mvc:annotation-driven/> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!--前缀--> <property name="prefix" value="/WEB-INF/jsp/"></property> <!--后缀--> <property name="suffix" value=".jsp"></property> </bean> <!--拦截器--> <mvc:interceptors> <mvc:interceptor> <!--拦截的请求路径 /admin/** 拦截路径下的所有请求及其子请求 /admin/user/add会被拦截 /admin/* 拦截路径下的所有请求不包含其子请求 /admin/user会被拦截 /admin/user/add就不会被拦截 --> <mvc:mapping path="/**"/> <!--使用哪个拦截器--> <bean class="com.starry.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> </beans>
拦截器
public class LoginInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 如果请求包含login就放行 if (request.getRequestURI().contains("login")){ return true; } // 如果session有值,就表明已经登录了,放行 if (request.getSession().getAttribute("userInfo")!=null){ return true; } // 没登录就转发到登录页 request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response); return false; } }
Controller
@Controller public class LoginController { /** * 跳转到登录页面 * @return */ @RequestMapping("goLogin") public String goLogin(){ return "login"; } /** * 跳转到首页 * @return */ @RequestMapping("main") public String main(){ return "main"; } /** * 登录请求 * @param session * @param username * @param password * @return */ @RequestMapping("login") public String login(HttpSession session, @RequestParam("username")String username, @RequestParam("password")String password){ System.out.println("=====>login()"); session.setAttribute("userInfo",username); return "main"; } /** * 退出登录 * @param session * @return */ @RequestMapping("goOut") public String goOut(HttpSession session){ // 用户注销 从session中移出userInfo session.removeAttribute("userInfo"); // 页面跳转到登录页面 return "login"; } }
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <a href="${pageContext.request.contextPath}/goLogin">登录页面</a> <a href="${pageContext.request.contextPath}/main">首页</a> </body> </html>
main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>首页</h1> ${pageContext.session.getAttribute("userInfo")} <a href="/goOut">注销</a> </body> </html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>登录页面</h1> <form action="${pageContext.request.contextPath}/login" method="post"> 用户名:<input name="username"><br> 密码:<input name="password"><br> <input type="submit" value="提交"> </form> </body> </html>
实现功能
- 用户未登录不能查看首页
- 用户登录后点击首页即可跳转到首页,不用再次登录
- 用户注销后,不能查看首页,跳转到登录页面
项目结构
这篇关于SpringMVC拦截器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现
- 2024-05-30我们小公司,哪像华为一样,用得上IPD(集成产品开发)?