原创转载请注明出处:http://agilestyle.iteye.com/blog/2382526
Project Directory
Maven Dependency
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool.spring</groupId> <artifactId>spring</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>session-share Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.8.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8.1</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>8080</port> <path>/spring</path> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterEncodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> <error-page> <error-code>500</error-code> <location>/WEB-INF/views/error/500.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/WEB-INF/views/error/404.jsp</location> </error-page> </web-app>
root-context.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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <context:component-scan base-package="org.fool.spring"/> </beans>
servlet-context.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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 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"> <mvc:annotation-driven/> <mvc:resources location="/resources/" mapping="/resources/**"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <context:component-scan base-package="org.fool.spring"/> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="org.fool.spring.interceptor.LoginInterceptor"> <property name="excludedUrls"> <list> <value>/login</value> </list> </property> </bean> </mvc:interceptor> </mvc:interceptors> </beans>
Controller
LoginController.java
package org.fool.spring.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import javax.servlet.http.HttpServletRequest; @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @PostMapping("/login") public String login(HttpServletRequest request) { request.getSession().setAttribute("user", "spring exception test"); return "success"; } @PostMapping("/logout") public String logout(HttpServletRequest request) { request.getSession().removeAttribute("user"); return "login"; } }
TestResponseStatusController.java
package org.fool.spring.controller; import org.fool.spring.exception.SpringInternalErrorException; import org.fool.spring.exception.SpringNotFoundException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @Controller public class TestResponseStatusController { @GetMapping("/testResponseStatusNotFoundException/{id}") public String testResponseStatusNotFoundException(@PathVariable int id) { if (id == 404) { throw new SpringNotFoundException(); } return "success"; } @GetMapping("/testResponseStatusInternalServerException/{id}") public String testResponseStatusInternalServerException(@PathVariable int id) { if (id == 500) { throw new SpringInternalErrorException(); } return "success"; } }
exception
AppGlobalException.java
package org.fool.spring.exception; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class AppGlobalException { @ExceptionHandler(SpringNotFoundException.class) public String pageNotFoundHandler() { return "error/404"; } @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public String methodNotAllowedHandler() { return "error/405"; } @ExceptionHandler(SpringInternalErrorException.class) public String serverInternalErrorHandler() { return "error/500"; } @ExceptionHandler(SpringNotAuthException.class) public String pageNotAuthHandler() { return "login"; } }
SpringInternalErrorException.java
package org.fool.spring.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Internal Server Error in Spring") public class SpringInternalErrorException extends RuntimeException { }
SpringNotAuthException.java
package org.fool.spring.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "Unauthorized in Spring") public class SpringNotAuthException extends RuntimeException { }
SpringNotFoundException.java
package org.fool.spring.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Not Found in Spring") public class SpringNotFoundException extends RuntimeException { }
Interceptor
LoginInterceptor.java
package org.fool.spring.interceptor; import org.fool.spring.exception.SpringNotAuthException; 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; import java.util.List; public class LoginInterceptor implements HandlerInterceptor { private List<String> excludedUrls; public void setExcludedUrls(List<String> excludedUrls) { this.excludedUrls = excludedUrls; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestUri = request.getRequestURI(); for (String url : excludedUrls) { if (requestUri.endsWith(url)) { return true; } } HttpSession session = request.getSession(); if (session.getAttribute("user") == null) { throw new SpringNotAuthException(); } return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
Page
404.jsp
404
405.jsp
405
500.jsp
500
login.jsp
<html> <head> <title>Login</title> </head> <body> <h1>login page</h1> <form action="/spring/login" method="post"> <input type="submit" value="login"> </form> </body> </html>
success.jsp
<html> <head> <title>Success</title> </head> <body> <h1>success page</h1> <form action="/spring/logout" method="post"> <input type="submit" value="logout"> </form> </body> </html>
Test
tomcat7:run
http://localhost:8080/spring/login
点击login按钮
登录成功后
http://localhost:8080/spring/testResponseStatusNotFoundException/404
http://localhost:8080/spring/testResponseStatusNotFoundException/0
http://localhost:8080/spring/testResponseStatusInternalServerException/500
http://localhost:8080/spring/testResponseStatusInternalServerException/0
点击logout
再次尝试请求http://localhost:8080/spring/logout
Note:
因为是浏览器是get请求,程序中logout只支持post,所以会报405
在未登录的情况下尝试请求
http://localhost:8080/spring/testResponseStatusInternalServerException/500
会直接跳掉login页面
相关推荐
整合Spring主要体现在Action类的创建上,我们通常会把Action类声明为Spring的Bean,这样可以利用Spring的依赖注入功能,使得Action类能够获取到其他服务或DAO对象。在struts.xml配置文件中,通过`<action>`标签指定...
在Spring Boot应用中,登录拦截器是一个至关重要的组件,它用于保护特定的Web资源,确保只有经过身份验证的用户才能访问。Spring Boot结合了Spring MVC框架,提供了方便的方式来实现这样的拦截器。本篇文章将深入...
本篇文章将详细探讨如何在Spring Boot中添加和使用拦截器来实现登录拦截。 首先,我们需要了解Spring Boot中的拦截器是如何工作的。在Spring MVC框架中,拦截器是基于AOP(面向切面编程)的概念实现的。我们可以...
基于Spring Boot的用户管理系统 项目概述 本项目是一个基于Spring Boot框架的用户管理系统,主要实现了用户登录校验功能。前端使用HTML、CSS和JavaScript技术构建了一个简洁的登录界面,后端采用Spring Boot框架...
java代码-登陆拦截器LoginInterceptor源代码 ——学习参考资料:仅用于个人学习使用
Spring MVC 是一款强大的Java web开发框架,用于构建可维护、高性能的Web应用程序。在这个名为"springmvc-login-interceptor"的项目中,我们关注的核心是Spring MVC的拦截器(Interceptor)功能,它允许开发者在请求...
SSM框架整合需要配置多个文件,包括`web.xml`、`applicationContext.xml`、`spring-mvc.xml`及MyBatis的相关配置文件。 ##### 1. web.xml 这是Web应用的核心配置文件,用于配置Spring容器和Spring MVC的前端控制器...
这样,每次访问匹配的URL时,Spring MVC都会先调用`LoginInterceptor`的`preHandle`方法进行登录验证。如果验证失败,用户会被重定向到登录页面;如果验证成功,请求会继续传递到控制器处理。 此外,Spring MVC还...
在Spring MVC框架中,拦截器(Interceptor)是一个强大的工具,用于在请求被控制器处理之前、之后以及视图渲染之后执行一些额外的操作。拦截器通过实现`HandlerInterceptor`接口或者继承`HandlerInterceptorAdapter`...
Spring Boot 中添加 Spring MVC 拦截器 在 Spring Boot 工程中添加 Spring MVC 拦截器是实现请求预处理和后处理的一种常见方式。 Spring MVC 的拦截器(Interceptor)不同于 Filter,可以实现请求的预处理和后处理...
### 使用Spring + SpringMVC + Interceptor + JWT + Redis 实现SSO单点登录 #### 一、背景介绍 在当前互联网技术飞速发展的背景下,越来越多的企业选择采用微服务架构来构建自己的应用系统。分布式环境下,如何...
1. `spring-core.jar`:包含Spring框架的基础工具类,是其他组件的基础。 2. `spring-beans.jar`:提供了IoC(控制反转)和DI(依赖注入)的核心功能。 3. `spring-aop.jar`:支持AOP(面向切面编程),如声明式事务...
Spring Boot 设置默认网页的方法 在 Spring Boot 中设置默认网页是非常必要的,因为它可以提供一个良好的用户体验。今天,我们将介绍如何在 Spring Boot 中设置默认网页的方法。 首先,让我们了解什么是默认网页。...
在Spring Boot应用中,添加拦截器是实现特定功能,如权限控制、日志记录或性能监控等的关键步骤。本文将详细介绍如何在Spring Boot项目中配置和使用拦截器。 首先,让我们从构建一个基础的Spring Boot项目开始。在...
创建自定义拦截器类,例如`LoginInterceptor`,该类需要继承Spring的`HandlerInterceptor`接口并实现其三个方法:`preHandle()`, `postHandle()` 和 `afterCompletion()`。在这里,我们将主要关注`preHandle()`方法...
在Spring MVC框架中,拦截器(Interceptor)是一个至关重要的组件,它允许我们在处理请求之前或之后执行自定义逻辑。在本篇文章中,我们将深入探讨Spring MVC中的拦截器机制,了解其工作原理、如何配置以及实际应用...
Spring Boot整合了Spring MVC,因此我们可以利用Spring MVC的拦截器来实现各种功能,如权限验证、日志记录、性能监控等。本文将详细介绍如何在Spring Boot中设置拦截器,并通过四个基本的HTTP请求方法(PUT、DELETE...
public LoginInterceptor LoginInterceptor() { return new LoginInterceptor(); } @Bean public AuthorityInterceptor AuthorityInterceptor() { return new AuthorityInterceptor(); } } ``` 在上面的代码...
在Spring MVC框架中,拦截器(Interceptor)是一个强大的工具,用于在请求被控制器处理之前或之后执行特定的逻辑。它可以用来实现诸如权限验证、日志记录、性能统计、缓存控制等多种功能。在这个主题中,我们将深入...