• springmvc 03(JSR303和拦截器)


    目录

    一,JSR303

            1.服务端验证

            2.步骤

    二,拦截器

            1.简介

            2.拦截器与过滤器

                    2.1 什么是过滤器

                    2.2 拦截器和过滤器的区别

            3.拦截器案例

                    3.1 使用原理


    一,JSR303

            1.服务端验证

            2.步骤

    1.导入pom.xml配置

    
    
        org.hibernate
        hibernate-validator
        6.0.7.Final
    
    
    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <groupId>org.examplegroupId>
    6. <artifactId>springmvcartifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. <packaging>warpackaging>
    9. <name>springmvc Maven Webappname>
    10. <url>http://www.example.comurl>
    11. <properties>
    12. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    13. <maven.compiler.source>1.8maven.compiler.source>
    14. <maven.compiler.target>1.8maven.compiler.target>
    15. <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>
    16. <spring.version>5.0.2.RELEASEspring.version>
    17. <mybatis.version>3.4.5mybatis.version>
    18. <mysql.version>5.1.44mysql.version>
    19. <pagehelper.version>5.1.2pagehelper.version>
    20. <mybatis.spring.version>1.3.1mybatis.spring.version>
    21. <commons.dbcp2.version>2.1.1commons.dbcp2.version>
    22. <commons.pool2.version>2.4.3commons.pool2.version>
    23. <log4j2.version>2.9.1log4j2.version>
    24. <junit.version>4.12junit.version>
    25. <servlet.version>4.0.0servlet.version>
    26. <lombok.version>1.18.2lombok.version>
    27. properties>
    28. <dependencies>
    29. <dependency>
    30. <groupId>org.springframeworkgroupId>
    31. <artifactId>spring-contextartifactId>
    32. <version>${spring.version}version>
    33. dependency>
    34. <dependency>
    35. <groupId>org.springframeworkgroupId>
    36. <artifactId>spring-ormartifactId>
    37. <version>${spring.version}version>
    38. dependency>
    39. <dependency>
    40. <groupId>org.springframeworkgroupId>
    41. <artifactId>spring-txartifactId>
    42. <version>${spring.version}version>
    43. dependency>
    44. <dependency>
    45. <groupId>org.springframeworkgroupId>
    46. <artifactId>spring-aspectsartifactId>
    47. <version>${spring.version}version>
    48. dependency>
    49. <dependency>
    50. <groupId>org.springframeworkgroupId>
    51. <artifactId>spring-webartifactId>
    52. <version>${spring.version}version>
    53. dependency>
    54. <dependency>
    55. <groupId>org.springframeworkgroupId>
    56. <artifactId>spring-testartifactId>
    57. <version>${spring.version}version>
    58. dependency>
    59. <dependency>
    60. <groupId>org.mybatisgroupId>
    61. <artifactId>mybatisartifactId>
    62. <version>${mybatis.version}version>
    63. dependency>
    64. <dependency>
    65. <groupId>mysqlgroupId>
    66. <artifactId>mysql-connector-javaartifactId>
    67. <version>${mysql.version}version>
    68. dependency>
    69. <dependency>
    70. <groupId>com.github.pagehelpergroupId>
    71. <artifactId>pagehelperartifactId>
    72. <version>${pagehelper.version}version>
    73. dependency>
    74. <dependency>
    75. <groupId>org.mybatisgroupId>
    76. <artifactId>mybatis-springartifactId>
    77. <version>${mybatis.spring.version}version>
    78. dependency>
    79. <dependency>
    80. <groupId>org.apache.commonsgroupId>
    81. <artifactId>commons-dbcp2artifactId>
    82. <version>${commons.dbcp2.version}version>
    83. dependency>
    84. <dependency>
    85. <groupId>org.apache.commonsgroupId>
    86. <artifactId>commons-pool2artifactId>
    87. <version>${commons.pool2.version}version>
    88. dependency>
    89. <dependency>
    90. <groupId>org.apache.logging.log4jgroupId>
    91. <artifactId>log4j-coreartifactId>
    92. <version>${log4j2.version}version>
    93. dependency>
    94. <dependency>
    95. <groupId>org.apache.logging.log4jgroupId>
    96. <artifactId>log4j-apiartifactId>
    97. <version>${log4j2.version}version>
    98. dependency>
    99. <dependency>
    100. <groupId>org.apache.logging.log4jgroupId>
    101. <artifactId>log4j-webartifactId>
    102. <version>${log4j2.version}version>
    103. dependency>
    104. <dependency>
    105. <groupId>junitgroupId>
    106. <artifactId>junitartifactId>
    107. <version>${junit.version}version>
    108. <scope>testscope>
    109. dependency>
    110. <dependency>
    111. <groupId>javax.servletgroupId>
    112. <artifactId>javax.servlet-apiartifactId>
    113. <version>${servlet.version}version>
    114. <scope>providedscope>
    115. dependency>
    116. <dependency>
    117. <groupId>org.projectlombokgroupId>
    118. <artifactId>lombokartifactId>
    119. <version>${lombok.version}version>
    120. <scope>providedscope>
    121. dependency>
    122. <dependency>
    123. <groupId>org.apache.logging.log4jgroupId>
    124. <artifactId>log4j-coreartifactId>
    125. <version>2.9.1version>
    126. dependency>
    127. <dependency>
    128. <groupId>org.apache.logging.log4jgroupId>
    129. <artifactId>log4j-apiartifactId>
    130. <version>2.9.1version>
    131. dependency>
    132. <dependency>
    133. <groupId>org.apache.logging.log4jgroupId>
    134. <artifactId>log4j-webartifactId>
    135. <version>2.9.1version>
    136. dependency>
    137. <dependency>
    138. <groupId>org.springframeworkgroupId>
    139. <artifactId>spring-webmvcartifactId>
    140. <version>${spring.version}version>
    141. dependency>
    142. <dependency>
    143. <groupId>javax.servlet.jspgroupId>
    144. <artifactId>javax.servlet.jsp-apiartifactId>
    145. <version>2.3.3version>
    146. dependency>
    147. <dependency>
    148. <groupId>jstlgroupId>
    149. <artifactId>jstlartifactId>
    150. <version>1.2version>
    151. dependency>
    152. <dependency>
    153. <groupId>taglibsgroupId>
    154. <artifactId>standardartifactId>
    155. <version>1.1.2version>
    156. dependency>
    157. <dependency>
    158. <groupId>commons-fileuploadgroupId>
    159. <artifactId>commons-fileuploadartifactId>
    160. <version>1.3.3version>
    161. dependency>
    162. <dependency>
    163. <groupId>org.hibernategroupId>
    164. <artifactId>hibernate-validatorartifactId>
    165. <version>6.0.7.Finalversion>
    166. dependency>
    167. dependencies>
    168. <build>
    169. <finalName>springmvcfinalName>
    170. <resources>
    171. <resource>
    172. <directory>src/main/javadirectory>
    173. <includes>
    174. <include>**/*.xmlinclude>
    175. includes>
    176. resource>
    177. <resource>
    178. <directory>src/main/resourcesdirectory>
    179. <includes>
    180. <include>jdbc.propertiesinclude>
    181. <include>*.xmlinclude>
    182. includes>
    183. resource>
    184. resources>
    185. <pluginManagement>
    186. <plugins>
    187. <plugin>
    188. <groupId>org.apache.maven.pluginsgroupId>
    189. <artifactId>maven-compiler-pluginartifactId>
    190. <version>${maven.compiler.plugin.version}version>
    191. <configuration>
    192. <source>${maven.compiler.source}source>
    193. <target>${maven.compiler.target}target>
    194. <encoding>${project.build.sourceEncoding}encoding>
    195. configuration>
    196. plugin>
    197. <plugin>
    198. <groupId>org.mybatis.generatorgroupId>
    199. <artifactId>mybatis-generator-maven-pluginartifactId>
    200. <version>1.3.2version>
    201. <dependencies>
    202. <dependency>
    203. <groupId>mysqlgroupId>
    204. <artifactId>mysql-connector-javaartifactId>
    205. <version>${mysql.version}version>
    206. dependency>
    207. dependencies>
    208. <configuration>
    209. <overwrite>trueoverwrite>
    210. configuration>
    211. plugin>
    212. <plugin>
    213. <artifactId>maven-clean-pluginartifactId>
    214. <version>3.1.0version>
    215. plugin>
    216. <plugin>
    217. <artifactId>maven-resources-pluginartifactId>
    218. <version>3.0.2version>
    219. plugin>
    220. <plugin>
    221. <artifactId>maven-compiler-pluginartifactId>
    222. <version>3.8.0version>
    223. plugin>
    224. <plugin>
    225. <artifactId>maven-surefire-pluginartifactId>
    226. <version>2.22.1version>
    227. plugin>
    228. <plugin>
    229. <artifactId>maven-war-pluginartifactId>
    230. <version>3.2.2version>
    231. plugin>
    232. <plugin>
    233. <artifactId>maven-install-pluginartifactId>
    234. <version>2.5.2version>
    235. plugin>
    236. <plugin>
    237. <artifactId>maven-deploy-pluginartifactId>
    238. <version>2.8.2version>
    239. plugin>
    240. plugins>
    241. pluginManagement>
    242. build>
    243. project>

    再进行其他的配置

     applicationContext-mybatis.xml

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    5. xmlns:aop="http://www.springframework.org/schema/aop"
    6. 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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    7. <context:annotation-config/>
    8. <context:component-scan base-package="com.ruojuan.ssm"/>
    9. <context:property-placeholder location="classpath:jdbc.properties"/>
    10. <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
    11. destroy-method="close">
    12. <property name="driverClassName" value="${jdbc.driver}"/>
    13. <property name="url" value="${jdbc.url}"/>
    14. <property name="username" value="${jdbc.username}"/>
    15. <property name="password" value="${jdbc.password}"/>
    16. <property name="initialSize" value="10"/>
    17. <property name="maxTotal" value="100"/>
    18. <property name="maxIdle" value="50"/>
    19. <property name="minIdle" value="10"/>
    20. <property name="maxWaitMillis" value="-1"/>
    21. bean>
    22. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    23. <property name="dataSource" ref="dataSource"/>
    24. <property name="mapperLocations" value="classpath*:com/ruojuan/ssm/**/mapper/*.xml"/>
    25. <property name="typeAliasesPackage" value="com/ruojuan/ssm/**/model"/>
    26. <property name="plugins">
    27. <array>
    28. <bean class="com.github.pagehelper.PageInterceptor">
    29. <property name="properties">
    30. <value>
    31. helperDialect=mysql
    32. value>
    33. property>
    34. bean>
    35. array>
    36. property>
    37. bean>
    38. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    39. <property name="basePackage" value="com/ruojuan/ssm/**/mapper"/>
    40. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    41. bean>
    42. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    43. <property name="dataSource" ref="dataSource" />
    44. bean>
    45. <tx:annotation-driven transaction-manager="transactionManager" />
    46. <aop:aspectj-autoproxy/>
    47. beans>

    generatorConfig.xml

    1. "1.0" encoding="UTF-8" ?>
    2. generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    3. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
    4. <generatorConfiguration>
    5. <properties resource="jdbc.properties"/>
    6. <classPathEntry location="D:\\maven mulu\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
    7. <context id="infoGuardian">
    8. <commentGenerator>
    9. <property name="suppressAllComments" value="true"/>
    10. <property name="suppressDate" value="true"/>
    11. commentGenerator>
    12. <jdbcConnection driverClass="${jdbc.driver}"
    13. connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
    14. <javaTypeResolver>
    15. <property name="forceBigDecimals" value="false"/>
    16. javaTypeResolver>
    17. <javaModelGenerator targetPackage="com.ruojuan.ssm.model"
    18. targetProject="src/main/java">
    19. <property name="enableSubPackages" value="false"/>
    20. <property name="constructorBased" value="true"/>
    21. <property name="trimStrings" value="false"/>
    22. <property name="immutable" value="false"/>
    23. javaModelGenerator>
    24. <sqlMapGenerator targetPackage="com.ruojuan.ssm.mapper"
    25. targetProject="src/main/java">
    26. <property name="enableSubPackages" value="false"/>
    27. sqlMapGenerator>
    28. <javaClientGenerator targetPackage="com.ruojuan.ssm.mapper"
    29. targetProject="src/main/java" type="XMLMAPPER">
    30. <property name="enableSubPackages" value="false"/>
    31. javaClientGenerator>
    32. <table schema="" tableName="t_struts_class" domainObjectName="Clazz"
    33. enableCountByExample="false" enableDeleteByExample="false"
    34. enableSelectByExample="false" enableUpdateByExample="false">
    35. table>
    36. context>
    37. generatorConfiguration>
    jdbc.properties
    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/t280?useUnicode=true&characterEncoding=UTF-8
    3. jdbc.username=root
    4. jdbc.password=123456

     log4j2.xml

    1. "1.0" encoding="UTF-8"?>
    2. <Configuration status="WARN" monitorInterval="30">
    3. <Properties>
    4. <Property name="LOG_HOME">/root/workspace/lucenedemo/logsProperty>
    5. <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/errorproperty>
    6. <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warnproperty>
    7. <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%nproperty>
    8. Properties>
    9. <Appenders>
    10. <Console name="Console" target="SYSTEM_OUT">
    11. <ThresholdFilter level="trace" onMatch="ACCEPT"
    12. onMismatch="DENY" />
    13. <PatternLayout pattern="${PATTERN}" />
    14. Console>
    15. <File name="log" fileName="logs/test.log" append="false">
    16. <PatternLayout
    17. pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    18. File>
    19. <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
    20. filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
    21. <ThresholdFilter level="info" onMatch="ACCEPT"
    22. onMismatch="DENY" />
    23. <PatternLayout
    24. pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    25. <Policies>
    26. <TimeBasedTriggeringPolicy interval="1"
    27. modulate="true" />
    28. Policies>
    29. RollingFile>
    30. <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
    31. filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
    32. <ThresholdFilter level="warn" onMatch="ACCEPT"
    33. onMismatch="DENY" />
    34. <PatternLayout
    35. pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    36. <Policies>
    37. <TimeBasedTriggeringPolicy />
    38. <SizeBasedTriggeringPolicy size="2 kB" />
    39. Policies>
    40. <DefaultRolloverStrategy max="20" />
    41. RollingFile>
    42. <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
    43. filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
    44. <ThresholdFilter level="error" onMatch="ACCEPT"
    45. onMismatch="DENY" />
    46. <PatternLayout
    47. pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    48. <Policies>
    49. <TimeBasedTriggeringPolicy interval="1"
    50. modulate="true" />
    51. Policies>
    52. RollingFile>
    53. Appenders>
    54. <Loggers>
    55. <logger name="org.springframework" level="INFO">logger>
    56. <logger name="org.mybatis" level="INFO">logger>
    57. <logger name="org.springframework" level="ERROR" />
    58. <logger name="org.hibernate" level="ERROR" />
    59. <logger name="org.apache.struts2" level="ERROR" />
    60. <logger name="com.opensymphony.xwork2" level="ERROR" />
    61. <logger name="org.jboss" level="ERROR" />
    62. <root level="all">
    63. <appender-ref ref="Console" />
    64. <appender-ref ref="RollingFileInfo" />
    65. <appender-ref ref="RollingFileWarn" />
    66. <appender-ref ref="RollingFileError" />
    67. root>
    68. Loggers>
    69. Configuration>

     mybits.cfg.xml

    1. "1.0" encoding="UTF-8"?>
    2. configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    3. <configuration>
    4. <properties resource="jdbc.properties"/>
    5. <settings>
    6. <setting name="logImpl" value="LOG4J2"/>
    7. settings>
    8. <typeAliases>
    9. typeAliases>
    10. <plugins>
    11. <plugin interceptor="com.github.pagehelper.PageInterceptor">
    12. plugin>
    13. plugins>
    14. <environments default="development">
    15. <environment id="development">
    16. <transactionManager type="jdbc"/>
    17. <dataSource type="POOLED">
    18. <property name="driver"
    19. value="${jdbc.driver}"/>
    20. <property name="url"
    21. value="${jdbc.url}"/>
    22. <property name="username" value="${jdbc.username}"/>
    23. <property name="password" value="${jdbc.password}"/>
    24. dataSource>
    25. environment>
    26. environments>
    27. <mappers>
    28. <mapper resource="com/ruojuan/ssm/mapper/ClazzMapper.xml"/>
    29. mappers>
    30. configuration>

    mvc.tld

    1. "1.0" encoding="UTF-8" ?>
    2. <taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    5. version="2.0">
    6. <description>mvc 1.1 core librarydescription>
    7. <display-name>mvc coredisplay-name>
    8. <tlib-version>1.1tlib-version>
    9. <short-name>mvcshort-name>
    10. <uri>http://jsp.veryedu.cnuri>
    11. <tag>
    12. <name>pagename>
    13. <tag-class>com.ruojuan.ssm.tag.PageTagtag-class>
    14. <body-content>JSPbody-content>
    15. <attribute>
    16. <name>pageBeanname>
    17. <required>truerequired>
    18. <rtexprvalue>truertexprvalue>
    19. attribute>
    20. tag>
    21. taglib>

     springmvc-servlet.xml

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    7. 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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    8. <aop:aspectj-autoproxy/>
    9. <context:component-scan base-package="com.ruojuan.ssm"/>
    10. <mvc:annotation-driven>mvc:annotation-driven>
    11. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    12. <property name="viewClass"
    13. value="org.springframework.web.servlet.view.JstlView">property>
    14. <property name="prefix" value="/"/>
    15. <property name="suffix" value=".jsp"/>
    16. bean>
    17. <mvc:resources location="/images/" mapping="/images/**"/>
    18. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    19. <property name="defaultEncoding" value="UTF-8">property>
    20. <property name="maxUploadSize" value="52428800">property>
    21. <property name="resolveLazily" value="true"/>
    22. bean>
    23. <mvc:interceptors>
    24. <mvc:interceptor>
    25. <mvc:mapping path="/**"/>
    26. <bean class="com.ruojuan.ssm.intercept.OneHandlerInterceptor">bean>
    27. mvc:interceptor>
    28. <mvc:interceptor>
    29. <mvc:mapping path="/clz/**"/>
    30. <bean class="com.ruojuan.ssm.intercept.TwoHandlerInterceptor">bean>
    31. mvc:interceptor>
    32. mvc:interceptors>
    33. beans>

     web.xml

    1. web-app PUBLIC
    2. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    3. "http://java.sun.com/dtd/web-app_2_3.dtd" >
    4. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    6. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    7. version="3.1">
    8. <display-name>Archetype Created Web Applicationdisplay-name>
    9. <context-param>
    10. <param-name>contextConfigLocationparam-name>
    11. <param-value>classpath:applicationContext.xmlparam-value>
    12. context-param>
    13. <listener>
    14. <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    15. listener>
    16. <servlet>
    17. <servlet-name>SpringMVCservlet-name>
    18. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    19. <init-param>
    20. <param-name>contextConfigLocationparam-name>
    21. <param-value>/WEB-INF/springmvc-servlet.xmlparam-value>
    22. init-param>
    23. <load-on-startup>1load-on-startup>
    24. <async-supported>trueasync-supported>
    25. servlet>
    26. <servlet-mapping>
    27. <servlet-name>SpringMVCservlet-name>
    28. <url-pattern>/url-pattern>
    29. servlet-mapping>
    30. <filter>
    31. <filter-name>encodingFilterfilter-name>
    32. <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    33. <async-supported>trueasync-supported>
    34. <init-param>
    35. <param-name>encodingparam-name>
    36. <param-value>UTF-8param-value>
    37. init-param>
    38. filter>
    39. <filter-mapping>
    40. <filter-name>encodingFilterfilter-name>
    41. <url-pattern>/*url-pattern>
    42. filter-mapping>
    43. web-app>

    实体类:

    用注解的方式来提示是否输入

     

    Clzz.java实体类

    1. package com.ruojuan.ssm.model;
    2. import javax.validation.constraints.NotBlank;
    3. import javax.validation.constraints.NotEmpty;
    4. import javax.validation.constraints.NotNull;
    5. /**
    6. * @NotNull :作用于基本数据类型
    7. * @NotEmpty 作用于集合
    8. * @NotBlank 作用于字符串
    9. */
    10. public class Clazz {
    11. @NotNull(message = "cid不能为空")
    12. private Integer cid;
    13. @NotBlank(message = "班级名不能为空")
    14. private String cname;
    15. @NotBlank(message = "教员老师不能为空")
    16. private String cteacher;
    17. private String pic;
    18. public Clazz(Integer cid, String cname, String cteacher, String pic) {
    19. this.cid = cid;
    20. this.cname = cname;
    21. this.cteacher = cteacher;
    22. this.pic = pic;
    23. }
    24. public Clazz() {
    25. super();
    26. }
    27. public Integer getCid() {
    28. return cid;
    29. }
    30. public void setCid(Integer cid) {
    31. this.cid = cid;
    32. }
    33. public String getCname() {
    34. return cname;
    35. }
    36. public void setCname(String cname) {
    37. this.cname = cname;
    38. }
    39. public String getCteacher() {
    40. return cteacher;
    41. }
    42. public void setCteacher(String cteacher) {
    43. this.cteacher = cteacher;
    44. }
    45. public String getPic() {
    46. return pic;
    47. }
    48. public void setPic(String pic) {
    49. this.pic = pic;
    50. }
    51. }

     控制层ClazzController.java

    1. // 给数据添加服务端校验
    2. @RequestMapping("/valiAdd")
    3. public String valiAdd(@Validated Clazz clazz, BindingResult result,HttpServletRequest req){
    4. // 如果服务端验证不通过,有错误
    5. if(result.hasErrors()){
    6. // 服务端验证了实体类的多个属性,多个属性都没有验证通过
    7. List fieldErrors = result.getFieldErrors();
    8. Map map = new HashMap<>();
    9. for (FieldError fieldError : fieldErrors) {
    10. // 将多个属性的验证失败信息输送到控制台
    11. System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
    12. map.put(fieldError.getField(),fieldError.getDefaultMessage());
    13. }
    14. req.setAttribute("errorMap",map);
    15. }else {
    16. this.clazzBiz.insertSelective(clazz);
    17. return "redirect:/clz/list";
    18. }
    19. return "clzEdit";
    20. }

     前端代码:

    1. <body>
    2. <%--<form action="${pageContext.request.contextPath }/clz/${empty b ? 'add' : 'edit'}" method="post">--%>
    3. <form action="${pageContext.request.contextPath }/clz/${empty b ? 'valiAdd' : 'edit'}" method="post">
    4. id:<input type="text" name="cid" value="${b.cid }"><span style="color: red;">${errorMap.cid}span><br>
    5. cname:<input type="text" name="cname" value="${b.cname }"><span style="color: red;">${errorMap.cname}span><br>
    6. cteacher:<input type="text" name="cteacher" value="${b.cteacher }"><span style="color: red;">${errorMap.cteacher}span><br>
    7. <input type="submit">
    8. form>
    9. body>

     效果:

    当你不输入时就提示不能输入空值

     

    二,拦截器

            1.简介

    SpringMVC的处理器拦截器,类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。

      依赖于web框架,在实现上基于Java的反射机制属于面向切面编程(AOP)的一种运用。由于拦截器是基于web框架的调用,因此可以使用Spring的依赖注入(DI)进行一些业务操作,同时一个拦截器实例在一个 
      controller生命周期之内可以多次调用。

            2.拦截器与过滤器

                    2.1 什么是过滤器

        依赖于servlet容器。在实现上基于函数回调,可以对几乎所有请求进行过滤,但是缺点是一个过滤器实例
        只能在容器初始化时调用一次。使用过滤器的目的是用来做一些过滤操作,比如:在过滤器中修改字符编码;
        在过滤器中修改HttpServletRequest的一些参数,包括:过滤低俗文字、危险字符等。

                    2.2 拦截器和过滤器的区别

        过滤器(filter):

        1) filter属于Servlet技术,只要是web工程都可以使用
        2) filter主要对所有请求过滤
        3) filter的执行时机早于Interceptor

        拦截器(interceptor)

        1) interceptor属于SpringMVC技术,必须要有SpringMVC环境才可以使用
        2) interceptor通常对处理器Controller进行拦截
        3) interceptor只能拦截dispatcherServlet处理的请求

    应用场景

        1)日志记录:记录请求信息的日志,以便进行信息监控、信息统计、计算PV(Page View)等。

        2)权限检查:如登录检测,进入处理器检测是否登录,如果没有直接返回到登录页面;

        3)性能监控:有时候系统在某段时间莫名其妙的慢,可以通过拦截器在进入处理器之前记录开始时间,在处理完后记录结束时间,从而得到该请求的处理时间(如果有反向代理,如apache可以自动记录);

        4)通用行为:读取cookie得到用户信息并将用户对象放入请求,从而方便后续流程使用,还有如提取Locale、Theme信息等,只要是多个Controller中的处理方法都需要的,我们就可以使用拦截器实现。

            3.拦截器案例

                    3.1 使用原理

    1.   拦截器入门:

    ①创建一个类名为HellController

     
    
    1. package com.ruojuan.ssm.web;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.RequestMapping;
    4. /**
    5. * @author ruojuan
    6. * @site 123456999
    7. * @company 玉渊工作室
    8. * @create 2022-08-19 16:44
    9. */
    10. @Controller
    11. public class HellController {
    12. @RequestMapping("/hello")
    13. public String hello(){
    14. System.out.println("进入业务方法。。。。");
    15. return "List";
    16. }
    17. }

     

    ②再创建一个类为拦截器OneHandlerInterceptor

    1. package com.ruojuan.ssm.intercept;
    2. import org.springframework.web.servlet.HandlerInterceptor;
    3. import org.springframework.web.servlet.ModelAndView;
    4. import javax.servlet.http.HttpServletRequest;
    5. import javax.servlet.http.HttpServletResponse;
    6. /**
    7. * @author ruojuan
    8. * @site 123456999
    9. * @company 玉渊工作室
    10. * @create 2022-08-19 16:37
    11. */
    12. public class OneInterceptor implements HandlerInterceptor {
    13. @Override
    14. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    15. System.out.println("【OneInterceptor】:preHandle...");
    16. return true;
    17. }
    18. @Override
    19. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    20. System.out.println("【OneInterceptor】:postHandle...");
    21. }
    22. @Override
    23. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    24. System.out.println("【OneInterceptor】:afterCompletion...");
    25. }
    26. }

    ③在springmvc-servlet.xml配置拦截器文件

    1. <mvc:interceptors>
    2. <bean class="com.ruojuan.ssm.intercept.OneHandlerInterceptor">bean>
    3. mvc:interceptors>

    ④结果

     

    2.拦截器链

    ①创建另一个拦截器

    1. package com.ruojuan.ssm.intercept;
    2. import org.springframework.web.servlet.HandlerInterceptor;
    3. import org.springframework.web.servlet.ModelAndView;
    4. import javax.servlet.http.HttpServletRequest;
    5. import javax.servlet.http.HttpServletResponse;
    6. /**
    7. * @author ruojuan
    8. * @site 123456999
    9. * @company 玉渊工作室
    10. * @create 2022-08-19 16:37
    11. */
    12. public class OneInterceptor implements HandlerInterceptor {
    13. @Override
    14. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    15. System.out.println("【OneInterceptor】:preHandle...");
    16. return true;
    17. }
    18. @Override
    19. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    20. System.out.println("【OneInterceptor】:postHandle...");
    21. }
    22. @Override
    23. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    24. System.out.println("【OneInterceptor】:afterCompletion...");
    25. }
    26. }

    1. package com.ruojuan.ssm.intercept;
    2. import org.springframework.web.servlet.HandlerInterceptor;
    3. import org.springframework.web.servlet.ModelAndView;
    4. import javax.servlet.http.HttpServletRequest;
    5. import javax.servlet.http.HttpServletResponse;
    6. /**
    7. * @author ruojuan
    8. * @site 123456999
    9. * @company 玉渊工作室
    10. * @create 2022-08-19 16:47
    11. */
    12. public class TwoHandlerInterceptor implements HandlerInterceptor {
    13. @Override
    14. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    15. //预处理
    16. System.out.println("[OneHandlerInterceptor].preHandle");
    17. return true;
    18. }
    19. @Override
    20. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    21. //后处理
    22. System.out.println("[OneHandlerInterceptor].postHandle");
    23. }
    24. @Override
    25. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    26. //完成后处理
    27. System.out.println("[OneHandlerInterceptor].afterCompletion");
    28. }
    29. }

    ②springmvc-servlet.xml配置文件

     

    1. <mvc:interceptors>
    2. <mvc:interceptor>
    3. <mvc:mapping path="/**"/>
    4. <bean class="com.zking.ssm.interceptor.OneInterceptor">bean>
    5. mvc:interceptor>
    6. <mvc:interceptor>
    7. <mvc:mapping path="/clz/**"/>
    8. <bean class="com.zking.ssm.interceptor.TwoInterceptor">bean>
    9. mvc:interceptor>
    10. mvc:interceptors>

     

     

    1. public class OneInterceptor implements HandlerInterceptor {
    2. @Override
    3. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    4. System.out.println("【OneInterceptor】:preHandle...");
    5. StringBuffer url = request.getRequestURL();
    6. if (url.indexOf("/login") > 0 || url.indexOf("/logout") > 0){
    7. // 如果是 登录、退出 中的一种
    8. return true;
    9. }
    10. // 代表不是登录,也不是退出
    11. // 除了登录、退出,其他操作都需要判断是否 session 登录成功过
    12. String uname = (String) request.getSession().getAttribute("uname");
    13. if (uname == null || "".equals(uname)){
    14. return false;
    15. }
    16. return true;
    17. }
    18. @Override
    19. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    20. System.out.println("【OneInterceptor】:postHandle...");
    21. }
    22. @Override
    23. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    24. System.out.println("【OneInterceptor】:afterCompletion...");
    25. }
    26. }

    1. @Controller
    2. public class LoginController {
    3. @RequestMapping("/login")
    4. public String login(HttpServletRequest req){
    5. String uname = req.getParameter("uname");
    6. HttpSession session = req.getSession();
    7. if ("zs".equals(uname)){
    8. session.setAttribute("uname",uname);
    9. }
    10. return "redirect:/clz/list";
    11. }
    12. @RequestMapping("/logout")
    13. public String logout(HttpServletRequest req){
    14. req.getSession().invalidate();
    15. return "redirect:/clz/list";
    16. }
    17. }

            

  • 相关阅读:
    手机取证基础知识(一)
    AI只需26秒,就可以设计一款会走路的机器人
    docker Compose 部署springboot+vue前端端分离项目
    10个常用的JS工具库,80%的项目都在用!
    uniapp项目初始化时报gyp ERR
    NTFS安全权限
    Elasticsearch 安装与配置
    Day06-filebeat,logstash多实例,pipline,ElasticStack项目架构梳理及实战案例
    RabbitMQ:发布订阅和路由模式
    Fabric.js 元素中心缩放
  • 原文地址:https://blog.csdn.net/weixin_67338832/article/details/126431043