一.什么是JSR303
Spring MVC JSR 303是结合了Spring MVC和JSR 303规范的一种验证机制。Spring MVC是Spring框架的一部分,用于构建基于Java的Web应用程序。而JSR 303是Java中的一个规范,用于定义对象验证的注解和API。
Spring MVC JSR 303提供了一种方便的方式来在Spring MVC应用程序中进行数据验证。通过在Controller的方法参数上添加验证注解,如
@Valid
,可以触发对请求参数的验证。该机制能够自动校验请求数据与JSR 303注解中定义的约束条件是否一致,例如非空、长度、范围等。如果验证失败,Spring MVC将生成相应的错误信息,并将其与视图进行绑定,以便显示给用户。这种验证机制可以帮助开发人员快速、便捷地进行输入数据的验证,提高应用程序的数据质量和安全性。
二.JSR303
常用注解
JSR 303定义了多个注解来支持对象验证。以下是一些常用的JSR 303注解:
@NotNull
:验证字段不能为null。@NotEmpty
:验证字段不能为空,对于String、Collection、Map和数组类型的字段有效。@NotBlank
:验证字段不能为空且长度必须大于0,用于字符串类型的字段。@Size(min, max)
:验证字段的大小必须在指定的范围内。@Min(value)
:验证字段的值必须大于或等于指定的最小值。@Max(value)
:验证字段的值必须小于或等于指定的最大值。@Pattern(regex)
:验证字段的值必须符合指定的正则表达式模式。@Valid
:用于嵌套验证,表示需要对嵌套对象进行验证。以上只是一些常见的JSR 303注解,实际上还有其他很多注解可供使用。开发人员可以根据具体的需求选择适合的注解来对对象进行验证。
作用
Spring MVC JSR 303的作用是在Spring MVC应用程序中提供一种方便的数据验证机制。它的主要目的是确保输入数据的合法性和一致性,从而提高应用程序的数据质量和安全性。
通过使用JSR 303规范定义的验证注解,开发人员可以对请求参数、表单数据或任何Java对象进行验证。Spring MVC框架会自动触发验证,并根据验证结果生成相应的错误信息。
具体来说,Spring MVC JSR 303的作用包括:
- 验证请求参数:可以在Controller的方法参数上添加
@Valid
注解,触发对请求参数的验证。- 验证表单数据:可以在表单对象的字段上使用JSR 303注解,通过校验注解定义的约束条件来验证表单数据的合法性。
- 验证任意Java对象:可以对任意Java对象进行验证,通过在对象的字段上添加相应的验证注解来指定验证规则。
- 生成错误消息:当验证失败时,Spring MVC会自动将错误信息与视图进行绑定,以方便在页面上显示给用户。
- 简化验证逻辑:Spring MVC JSR 303简化了开发人员对输入数据进行验证的逻辑,提供了一种便捷的方式进行数据验证。
总的来说,Spring MVC JSR 303使数据验证变得简单而便捷,提高了应用程序的健壮性和安全性。
使用 导入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>xyzy</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>xyzy Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version> <!--添加jar包依赖--> <!--1.spring 5.0.2.RELEASE相关--> <spring.version>5.0.2.RELEASE</spring.version> <!--2.mybatis相关--> <mybatis.version>3.4.5</mybatis.version> <!--mysql--> <mysql.version>5.1.44</mysql.version> <!--pagehelper分页jar依赖--> <pagehelper.version>5.1.2</pagehelper.version> <!--mybatis与spring集成jar依赖--> <mybatis.spring.version>1.3.1</mybatis.spring.version> <!--3.dbcp2连接池相关 druid--> <commons.dbcp2.version>2.1.1</commons.dbcp2.version> <commons.pool2.version>2.4.3</commons.pool2.version> <!--4.log日志相关--> <log4j2.version>2.9.1</log4j2.version> <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version> <slf4j.version>1.7.13</slf4j.version> <!--5.其他--> <junit.version>4.12</junit.version> <servlet.version>4.0.0</servlet.version> <lombok.version>1.18.2</lombok.version> <mybatis.ehcache.version>1.1.0</mybatis.ehcache.version> <ehcache.version>2.10.0</ehcache.version> <redis.version>2.9.0</redis.version> <redis.spring.version>1.7.1.RELEASE</redis.spring.version> <jackson.version>2.9.3</jackson.version> <jstl.version>1.2</jstl.version> <standard.version>1.1.2</standard.version> <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version> <commons-fileupload.version>1.3.3</commons-fileupload.version> <hibernate-validator.version>5.0.2.Final</hibernate-validator.version> <shiro.version>1.3.2</shiro.version> </properties> <dependencies> <!--1.spring相关--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!--2.mybatis相关--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--pagehelper分页插件jar包依赖--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>${pagehelper.version}</version> </dependency> <!--mybatis与spring集成jar包依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <!--mybatis与ehcache整合--> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>${mybatis.ehcache.version}</version> </dependency> <!--ehcache依赖--> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>${ehcache.version}</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${redis.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${redis.spring.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <!--3.dbcp2连接池相关--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>${commons.dbcp2.version}</version> <exclusions> <exclusion> <artifactId>commons-pool2</artifactId> <groupId>org.apache.commons</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>${commons.pool2.version}</version> </dependency> <!--springmvc依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!--4.log日志相关依赖--> <!-- log4j2日志相关依赖 --> <!-- log配置:Log4j2 + Slf4j --> <!-- slf4j核心包--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <!--核心log4j2jar包--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j2.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j2.version}</version> </dependency> <!--用于与slf4j保持桥接--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j2.version}</version> </dependency> <!--web工程需要包含log4j-web,非web工程不需要--> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>${log4j2.version}</version> <scope>runtime</scope> </dependency> <!--需要使用log4j2的AsyncLogger需要包含disruptor--> <dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>${log4j2.disruptor.version}</version> </dependency> <!--5.其他--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <!-- <scope>test</scope>--> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${standard.version}</version> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jsp-api</artifactId> <version>${tomcat-jsp-api.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate-validator.version}</version> </dependency> <!--shiro依赖--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> </dependencies> <build> <finalName>xyzy</finalName> <resources> <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题--> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题--> <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>${maven.compiler.plugin.version}</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <dependencies> <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> <configuration> <overwrite>true</overwrite> </configuration> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </build> </project>
在实体类相对应的属性中增加注解用来指定校验
package com.xy.model; import lombok.ToString; import org.hibernate.validator.constraints.NotBlank; import org.junit.Test; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @ToString public class hpjy { @NotNull(message = "班级编号不能为空") // @Size(max = 100,min = 10,message = "大小必须在10至100之间") protected Integer id; @NotBlank(message = "班级名不能为空") protected String name; @NotBlank(message = "班级教员老师不能为空") protected String type; private String image="暂无图片"; public hpjy(Integer id, String name, String type, String image) { this.id = id; this.name = name; this.type = type; this.image = image; } public hpjy() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } }
在hpjyController里面新加以下代码
// 给数据添加服务端校验 @RequestMapping("/valiAdd") public String valiAdd(@Validated hpjy hpjy, BindingResult result, HttpServletRequest req){ // 如果服务端验证不通过,有错误 if(result.hasErrors()){ // 服务端验证了实体类的多个属性,多个属性都没有验证通过 List<FieldError> fieldErrors = result.getFieldErrors(); Map<String,Object> map = new HashMap<>(); for (FieldError fieldError : fieldErrors) { // 将多个属性的验证失败信息输送到控制台 System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage()); map.put(fieldError.getField(),fieldError.getDefaultMessage()); } req.setAttribute("errorMap",map); }else { this.hpjyBiz.insertSelective(hpjy); return "redirect:list"; } return "hpjy/edit"; }
修改eidt.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>编辑信息</h1> <form action="${pageContext.request.contextPath }/${empty h ? 'hpjy/valiAdd' : 'hpjy/edit'}" method="post"> 枪械编号:<input type="text" name="id" value="${h.id }"><span style="color:red;">${errorMap.id}</span><br> 枪械名称:<input type="text" name="name" value="${h.name }"><span style="color:red;">${errorMap.name}</span><br> 枪械类型:<input type="text" name="type" value="${h.type }"><span style="color:red;">${errorMap.type}</span><br> <input type="submit"> </form> </body> </html>
测试结果
二.拦截器
什么是拦截器
SpringMVC的处理器拦截器,类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。依赖于web框架,在实现上基于Java的反射机制,属于面向切面编程(AOP)的一种运用。由于拦截器是基于web框架的调用,因此可以使用Spring的依赖注入(DI)进行一些业务操作,同时一个拦截器实例在一个 controller生命周期之内可以多次调用。
拦截器与过滤器的区别
- 过滤器(filter)
1.filter属于Servlet技术,只要是web工程都可以使用
2.filter主要由于对所有请求过滤
3.filter的执行时机早于Interceptor- 拦截器(interceptor)
1.interceptor属于SpringMVC技术,必须要有SpringMVC环境才可以使用
2.interceptor通常由于对处理器Controller进行拦截
3.interceptor只能拦截dispatcherServlet处理的请求
拦截器工作原理
应用场景
日志记录:拦截器可以用于记录请求的相关信息,如请求的URL、请求参数、请求的处理时间等。通过拦截器记录日志,可以方便后续的系统日志记录和分析,以及对请求的追踪和排查问题。
权限验证:拦截器可以用于对用户进行权限验证,判断用户是否具有访问特定资源的权限。例如,在用户访问某个需要登录的页面之前,拦截器可以检查用户是否已登录,并根据用户的角色判断是否有权限访问该页面。
请求预处理:拦截器可以用于对请求进行预处理,如字符编码转换、请求参数解析、请求数据的封装等。通过拦截器进行预处理,可以减轻目标处理器的负担,提高请求的处理效率和系统的稳定性。
性能监控:拦截器可以用于监控请求的处理时间,用于系统的性能分析和优化。例如,拦截器可以记录请求的处理时间,并根据时间阈值进行性能告警或者对慢请求进行分析和优化。
使用编写一个OneInterceptor
package com.xy.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class OneInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("【OneInterceptor】:preHandle..."); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("【OneInterceptor】:postHandle..."); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("【OneInterceptor】:afterCompletion..."); } }
在spring-mvc中配置拦截器
<?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:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)--> <context:component-scan base-package="com.xy"/> <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter --> <mvc:annotation-driven /> <!--3) 创建ViewResolver视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4) 单独处理图片、样式、js等资源 --> <!-- <mvc:resources location="/css/" mapping="/css/**"/>--> <!-- <mvc:resources location="/js/" mapping="/js/**"/>--> <!-- <mvc:resources location="WEB-INF/images/" mapping="/images/**"/>--> <mvc:resources location="/static/" mapping="/static/**"/> <!--处理文件的上传下载--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 文件最大大小(字节) 1024*1024*50=50M--> <property name="maxUploadSize" value="52428800"></property> <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常--> <property name="resolveLazily" value="true"/> </bean> <!--配置拦截器--> <mvc:interceptors> <bean class="com.xy.interceptor.OneInterceptor"></bean> </mvc:interceptors> <!--处理controller层发送请求到biz,会经过切面的拦截处理--> <aop:aspectj-autoproxy/> </beans>
测试结果
编写拦截器链
<?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:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)--> <context:component-scan base-package="com.xy"/> <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter --> <mvc:annotation-driven /> <!--3) 创建ViewResolver视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4) 单独处理图片、样式、js等资源 --> <!-- <mvc:resources location="/css/" mapping="/css/**"/>--> <!-- <mvc:resources location="/js/" mapping="/js/**"/>--> <!-- <mvc:resources location="WEB-INF/images/" mapping="/images/**"/>--> <mvc:resources location="/static/" mapping="/static/**"/> <!--处理文件的上传下载--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 文件最大大小(字节) 1024*1024*50=50M--> <property name="maxUploadSize" value="52428800"></property> <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常--> <property name="resolveLazily" value="true"/> </bean> <!--配置拦截器--> <!-- <mvc:interceptors> <!– <bean class="com.xy.interceptor.OneInterceptor"></bean>–> </mvc:interceptors>--> <mvc:interceptors> <!--2) 多拦截器(拦截器链)--> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.xy.interceptor.OneInterceptor"/> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/hpjy/**"/> <bean class="com.xy.interceptor.TwoInterceptor"/> </mvc:interceptor> </mvc:interceptors> <!--处理controller层发送请求到biz,会经过切面的拦截处理--> <aop:aspectj-autoproxy/> </beans>
编写TwoInterceptor类
package com.xy.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TwoInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("【TwoInterceptor】:preHandle..."); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("【TwoInterceptor】:postHandle..."); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("【TwoInterceptor】:afterCompletion..."); } }
测试结果
三.用户登录权限控制
编写LoginInterceptor
package com.xy.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; 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 { System.out.println("【implements】:preHandle..."); StringBuffer url = request.getRequestURL(); if (url.indexOf("/login") > 0 || url.indexOf("/logout") > 0){ // 如果是 登录、退出 中的一种 return true; } // 代表不是登录,也不是退出 // 除了登录、退出,其他操作都需要判断是否 session 登录成功过 String uname = (String) request.getSession().getAttribute("uname"); if (uname == null || "".equals(uname)){ response.sendRedirect("/page/login"); return false; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
编写LoginController
package com.xy.web; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * @author bing人 * @site * @company xy集团 * @create 2023-09-12 14:28 */ @Controller public class LoginController { @RequestMapping("/login") public String login(HttpServletRequest req){ String uname = req.getParameter("uname"); HttpSession session = req.getSession(); if ("zs".equals(uname)){ session.setAttribute("uname",uname); } return "redirect:/hpjy/list"; } @RequestMapping("/logout") public String logout(HttpServletRequest req){ req.getSession().invalidate(); return "redirect:/hpjy/list"; } }
编写login.jsp
<%-- Created by IntelliJ IDEA. User: 30340 Date: 2023/9/12 Time: 14:28 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> <form action="/login" method="post"> 用户:<input name="uname"> <input type="submit"> </form> </body> </html>
编写Spring-Mvc
<?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:aop="http://www.springframework.org/schema/aop" 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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)--> <context:component-scan base-package="com.xy"/> <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter --> <mvc:annotation-driven /> <!--3) 创建ViewResolver视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4) 单独处理图片、样式、js等资源 --> <!-- <mvc:resources location="/css/" mapping="/css/**"/>--> <!-- <mvc:resources location="/js/" mapping="/js/**"/>--> <!-- <mvc:resources location="WEB-INF/images/" mapping="/images/**"/>--> <mvc:resources location="/static/" mapping="/static/**"/> <!--处理文件的上传下载--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 文件最大大小(字节) 1024*1024*50=50M--> <property name="maxUploadSize" value="52428800"></property> <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常--> <property name="resolveLazily" value="true"/> </bean> <!--配置拦截器--> <mvc:interceptors> <bean class="com.xy.interceptor.LoginInterceptor"></bean> </mvc:interceptors> <!--2) 多拦截器(拦截器链)--> <!--<mvc:interceptors>--> <!--<mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.xy.interceptor.OneInterceptor"/> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/hpjy/**"/> <bean class="com.xy.interceptor.TwoInterceptor"/> </mvc:interceptor> </mvc:interceptors>--> <!--处理controller层发送请求到biz,会经过切面的拦截处理--> <aop:aspectj-autoproxy/> </beans>
测试结果