目录
1.导入pom.xml配置
org.hibernate hibernate-validator 6.0.7.Final
- "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.0modelVersion>
-
- <groupId>org.examplegroupId>
- <artifactId>springmvcartifactId>
- <version>1.0-SNAPSHOTversion>
- <packaging>warpackaging>
-
- <name>springmvc Maven Webappname>
-
- <url>http://www.example.comurl>
-
- <properties>
- <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
- <maven.compiler.source>1.8maven.compiler.source>
- <maven.compiler.target>1.8maven.compiler.target>
- <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>
-
-
-
- <spring.version>5.0.2.RELEASEspring.version>
-
- <mybatis.version>3.4.5mybatis.version>
-
- <mysql.version>5.1.44mysql.version>
-
- <pagehelper.version>5.1.2pagehelper.version>
-
- <mybatis.spring.version>1.3.1mybatis.spring.version>
-
- <commons.dbcp2.version>2.1.1commons.dbcp2.version>
- <commons.pool2.version>2.4.3commons.pool2.version>
-
- <log4j2.version>2.9.1log4j2.version>
-
- <junit.version>4.12junit.version>
- <servlet.version>4.0.0servlet.version>
- <lombok.version>1.18.2lombok.version>
- properties>
-
- <dependencies>
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-contextartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-ormartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-txartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-aspectsartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-testartifactId>
- <version>${spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatisartifactId>
- <version>${mybatis.version}version>
- dependency>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>${mysql.version}version>
- dependency>
-
- <dependency>
- <groupId>com.github.pagehelpergroupId>
- <artifactId>pagehelperartifactId>
- <version>${pagehelper.version}version>
- dependency>
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatis-springartifactId>
- <version>${mybatis.spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-dbcp2artifactId>
- <version>${commons.dbcp2.version}version>
- dependency>
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-pool2artifactId>
- <version>${commons.pool2.version}version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-coreartifactId>
- <version>${log4j2.version}version>
- dependency>
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-apiartifactId>
- <version>${log4j2.version}version>
- dependency>
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-webartifactId>
- <version>${log4j2.version}version>
- dependency>
-
-
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>${junit.version}version>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>javax.servletgroupId>
- <artifactId>javax.servlet-apiartifactId>
- <version>${servlet.version}version>
- <scope>providedscope>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <version>${lombok.version}version>
- <scope>providedscope>
- dependency>
-
-
-
-
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-coreartifactId>
- <version>2.9.1version>
- dependency>
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-apiartifactId>
- <version>2.9.1version>
- dependency>
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-webartifactId>
- <version>2.9.1version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webmvcartifactId>
- <version>${spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>javax.servlet.jspgroupId>
- <artifactId>javax.servlet.jsp-apiartifactId>
- <version>2.3.3version>
- dependency>
- <dependency>
- <groupId>jstlgroupId>
- <artifactId>jstlartifactId>
- <version>1.2version>
- dependency>
- <dependency>
- <groupId>taglibsgroupId>
- <artifactId>standardartifactId>
- <version>1.1.2version>
- dependency>
- <dependency>
- <groupId>commons-fileuploadgroupId>
- <artifactId>commons-fileuploadartifactId>
- <version>1.3.3version>
- dependency>
-
-
- <dependency>
- <groupId>org.hibernategroupId>
- <artifactId>hibernate-validatorartifactId>
- <version>6.0.7.Finalversion>
- dependency>
-
- dependencies>
-
- <build>
- <finalName>springmvcfinalName>
- <resources>
-
- <resource>
- <directory>src/main/javadirectory>
- <includes>
- <include>**/*.xmlinclude>
- includes>
- resource>
-
- <resource>
- <directory>src/main/resourcesdirectory>
- <includes>
- <include>jdbc.propertiesinclude>
- <include>*.xmlinclude>
- includes>
- resource>
- resources>
-
- <pluginManagement>
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.pluginsgroupId>
- <artifactId>maven-compiler-pluginartifactId>
- <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.generatorgroupId>
- <artifactId>mybatis-generator-maven-pluginartifactId>
- <version>1.3.2version>
- <dependencies>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>${mysql.version}version>
- dependency>
- dependencies>
- <configuration>
- <overwrite>trueoverwrite>
- configuration>
- plugin>
-
- <plugin>
- <artifactId>maven-clean-pluginartifactId>
- <version>3.1.0version>
- plugin>
-
- <plugin>
- <artifactId>maven-resources-pluginartifactId>
- <version>3.0.2version>
- plugin>
- <plugin>
- <artifactId>maven-compiler-pluginartifactId>
- <version>3.8.0version>
- plugin>
- <plugin>
- <artifactId>maven-surefire-pluginartifactId>
- <version>2.22.1version>
- plugin>
- <plugin>
- <artifactId>maven-war-pluginartifactId>
- <version>3.2.2version>
- plugin>
- <plugin>
- <artifactId>maven-install-pluginartifactId>
- <version>2.5.2version>
- plugin>
- <plugin>
- <artifactId>maven-deploy-pluginartifactId>
- <version>2.8.2version>
- plugin>
- plugins>
- pluginManagement>
- build>
- project>
再进行其他的配置
applicationContext-mybatis.xml
- "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"
- xmlns:aop="http://www.springframework.org/schema/aop"
- 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">
-
-
- <context:annotation-config/>
-
- <context:component-scan base-package="com.ruojuan.ssm"/>
-
- <context:property-placeholder location="classpath:jdbc.properties"/>
-
- <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
- destroy-method="close">
- <property name="driverClassName" value="${jdbc.driver}"/>
- <property name="url" value="${jdbc.url}"/>
- <property name="username" value="${jdbc.username}"/>
- <property name="password" value="${jdbc.password}"/>
-
- <property name="initialSize" value="10"/>
-
- <property name="maxTotal" value="100"/>
-
- <property name="maxIdle" value="50"/>
-
- <property name="minIdle" value="10"/>
-
-
- <property name="maxWaitMillis" value="-1"/>
- bean>
-
-
-
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
-
- <property name="dataSource" ref="dataSource"/>
-
- <property name="mapperLocations" value="classpath*:com/ruojuan/ssm/**/mapper/*.xml"/>
-
- <property name="typeAliasesPackage" value="com/ruojuan/ssm/**/model"/>
-
- <property name="plugins">
- <array>
- <bean class="com.github.pagehelper.PageInterceptor">
- <property name="properties">
- <value>
- helperDialect=mysql
- value>
- property>
- bean>
- array>
- property>
- bean>
-
-
-
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
-
-
-
- <property name="basePackage" value="com/ruojuan/ssm/**/mapper"/>
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
- bean>
-
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- bean>
- <tx:annotation-driven transaction-manager="transactionManager" />
- <aop:aspectj-autoproxy/>
- beans>
generatorConfig.xml
- "1.0" encoding="UTF-8" ?>
- generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
- "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
- <generatorConfiguration>
-
- <properties resource="jdbc.properties"/>
-
-
- <classPathEntry location="D:\\maven mulu\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
-
-
- <context id="infoGuardian">
-
- <commentGenerator>
- <property name="suppressAllComments" value="true"/>
- <property name="suppressDate" value="true"/>
- commentGenerator>
-
-
- <jdbcConnection driverClass="${jdbc.driver}"
- connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
-
-
- <javaTypeResolver>
-
- <property name="forceBigDecimals" value="false"/>
- javaTypeResolver>
-
-
-
-
- <javaModelGenerator targetPackage="com.ruojuan.ssm.model"
- targetProject="src/main/java">
-
- <property name="enableSubPackages" value="false"/>
-
- <property name="constructorBased" value="true"/>
-
- <property name="trimStrings" value="false"/>
-
- <property name="immutable" value="false"/>
- javaModelGenerator>
-
-
- <sqlMapGenerator targetPackage="com.ruojuan.ssm.mapper"
- targetProject="src/main/java">
-
- <property name="enableSubPackages" value="false"/>
- sqlMapGenerator>
-
-
-
-
-
- <javaClientGenerator targetPackage="com.ruojuan.ssm.mapper"
- targetProject="src/main/java" type="XMLMAPPER">
-
- <property name="enableSubPackages" value="false"/>
- javaClientGenerator>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- <table schema="" tableName="t_struts_class" domainObjectName="Clazz"
- enableCountByExample="false" enableDeleteByExample="false"
- enableSelectByExample="false" enableUpdateByExample="false">
- table>
-
- context>
- generatorConfiguration>
jdbc.properties
- jdbc.driver=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/t280?useUnicode=true&characterEncoding=UTF-8
- jdbc.username=root
- jdbc.password=123456
log4j2.xml
- "1.0" encoding="UTF-8"?>
-
- <Configuration status="WARN" monitorInterval="30">
- <Properties>
-
- <Property name="LOG_HOME">/root/workspace/lucenedemo/logsProperty>
- <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/errorproperty>
- <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warnproperty>
- <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%nproperty>
- Properties>
-
- <Appenders>
-
- <Console name="Console" target="SYSTEM_OUT">
-
- <ThresholdFilter level="trace" onMatch="ACCEPT"
- onMismatch="DENY" />
-
-
- <PatternLayout pattern="${PATTERN}" />
- Console>
-
-
-
- <File name="log" fileName="logs/test.log" append="false">
- <PatternLayout
- pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
- File>
-
- <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
- filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
-
- <ThresholdFilter level="info" onMatch="ACCEPT"
- onMismatch="DENY" />
- <PatternLayout
- pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
- <Policies>
-
-
-
- <TimeBasedTriggeringPolicy interval="1"
- modulate="true" />
-
-
- Policies>
- RollingFile>
-
- <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
- filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
- <ThresholdFilter level="warn" onMatch="ACCEPT"
- onMismatch="DENY" />
- <PatternLayout
- pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
- <Policies>
- <TimeBasedTriggeringPolicy />
- <SizeBasedTriggeringPolicy size="2 kB" />
- Policies>
-
- <DefaultRolloverStrategy max="20" />
- RollingFile>
-
- <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
- filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
- <ThresholdFilter level="error" onMatch="ACCEPT"
- onMismatch="DENY" />
- <PatternLayout
- pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
- <Policies>
-
- <TimeBasedTriggeringPolicy interval="1"
- modulate="true" />
-
- Policies>
- RollingFile>
-
- Appenders>
-
-
- <Loggers>
-
- <logger name="org.springframework" level="INFO">logger>
- <logger name="org.mybatis" level="INFO">logger>
-
-
- <logger name="org.springframework" level="ERROR" />
- <logger name="org.hibernate" level="ERROR" />
- <logger name="org.apache.struts2" level="ERROR" />
- <logger name="com.opensymphony.xwork2" level="ERROR" />
- <logger name="org.jboss" level="ERROR" />
-
-
-
- <root level="all">
- <appender-ref ref="Console" />
- <appender-ref ref="RollingFileInfo" />
- <appender-ref ref="RollingFileWarn" />
- <appender-ref ref="RollingFileError" />
- root>
-
- Loggers>
-
- Configuration>
mybits.cfg.xml
- "1.0" encoding="UTF-8"?>
- configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
-
- <properties resource="jdbc.properties"/>
-
- <settings>
- <setting name="logImpl" value="LOG4J2"/>
- settings>
-
-
- <typeAliases>
-
- typeAliases>
-
- <plugins>
-
- <plugin interceptor="com.github.pagehelper.PageInterceptor">
- plugin>
- plugins>
-
-
- <environments default="development">
- <environment id="development">
-
- <transactionManager type="jdbc"/>
-
-
-
-
-
- <dataSource type="POOLED">
- <property name="driver"
- value="${jdbc.driver}"/>
- <property name="url"
- value="${jdbc.url}"/>
- <property name="username" value="${jdbc.username}"/>
- <property name="password" value="${jdbc.password}"/>
- dataSource>
- environment>
- environments>
-
-
-
- <mappers>
- <mapper resource="com/ruojuan/ssm/mapper/ClazzMapper.xml"/>
- mappers>
- configuration>
mvc.tld
- "1.0" encoding="UTF-8" ?>
-
- <taglib xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
- version="2.0">
-
- <description>mvc 1.1 core librarydescription>
- <display-name>mvc coredisplay-name>
- <tlib-version>1.1tlib-version>
- <short-name>mvcshort-name>
- <uri>http://jsp.veryedu.cnuri>
-
-
- <tag>
- <name>pagename>
- <tag-class>com.ruojuan.ssm.tag.PageTagtag-class>
- <body-content>JSPbody-content>
- <attribute>
- <name>pageBeanname>
- <required>truerequired>
- <rtexprvalue>truertexprvalue>
- attribute>
- tag>
-
- taglib>
springmvc-servlet.xml
- "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" xmlns:aop="http://www.springframework.org/schema/aop"
- 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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
-
-
- <aop:aspectj-autoproxy/>
- <context:component-scan base-package="com.ruojuan.ssm"/>
-
-
-
-
- <mvc:annotation-driven>mvc:annotation-driven>
-
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
-
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView">property>
- <property name="prefix" value="/"/>
- <property name="suffix" value=".jsp"/>
- bean>
-
-
-
-
-
- <mvc:resources location="/images/" mapping="/images/**"/>
-
-
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
-
- <property name="defaultEncoding" value="UTF-8">property>
-
- <property name="maxUploadSize" value="52428800">property>
-
- <property name="resolveLazily" value="true"/>
- bean>
-
-
-
-
-
- <mvc:interceptors>
- <mvc:interceptor>
-
- <mvc:mapping path="/**"/>
- <bean class="com.ruojuan.ssm.intercept.OneHandlerInterceptor">bean>
- mvc:interceptor>
- <mvc:interceptor>
-
- <mvc:mapping path="/clz/**"/>
- <bean class="com.ruojuan.ssm.intercept.TwoHandlerInterceptor">bean>
- mvc:interceptor>
- mvc:interceptors>
-
-
- beans>
web.xml
- web-app PUBLIC
- "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
- "http://java.sun.com/dtd/web-app_2_3.dtd" >
-
- <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_3_1.xsd"
- version="3.1">
- <display-name>Archetype Created Web Applicationdisplay-name>
- <context-param>
- <param-name>contextConfigLocationparam-name>
- <param-value>classpath:applicationContext.xmlparam-value>
- context-param>
-
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
- listener>
-
-
- <servlet>
- <servlet-name>SpringMVCservlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
-
- <init-param>
- <param-name>contextConfigLocationparam-name>
- <param-value>/WEB-INF/springmvc-servlet.xmlparam-value>
- init-param>
- <load-on-startup>1load-on-startup>
-
- <async-supported>trueasync-supported>
- servlet>
- <servlet-mapping>
- <servlet-name>SpringMVCservlet-name>
- <url-pattern>/url-pattern>
- servlet-mapping>
-
-
- <filter>
- <filter-name>encodingFilterfilter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
-
- <async-supported>trueasync-supported>
- <init-param>
- <param-name>encodingparam-name>
- <param-value>UTF-8param-value>
- init-param>
- filter>
- <filter-mapping>
- <filter-name>encodingFilterfilter-name>
- <url-pattern>/*url-pattern>
- filter-mapping>
- web-app>
实体类:
用注解的方式来提示是否输入
Clzz.java实体类
- package com.ruojuan.ssm.model;
-
- import javax.validation.constraints.NotBlank;
- import javax.validation.constraints.NotEmpty;
- import javax.validation.constraints.NotNull;
-
- /**
- * @NotNull :作用于基本数据类型
- * @NotEmpty 作用于集合
- * @NotBlank 作用于字符串
- */
- public class Clazz {
-
- @NotNull(message = "cid不能为空")
- private Integer cid;
-
- @NotBlank(message = "班级名不能为空")
- private String cname;
-
- @NotBlank(message = "教员老师不能为空")
- private String cteacher;
-
- private String pic;
-
- public Clazz(Integer cid, String cname, String cteacher, String pic) {
- this.cid = cid;
- this.cname = cname;
- this.cteacher = cteacher;
- this.pic = pic;
- }
-
- public Clazz() {
- super();
- }
-
- public Integer getCid() {
- return cid;
- }
-
- public void setCid(Integer cid) {
- this.cid = cid;
- }
-
- public String getCname() {
- return cname;
- }
-
- public void setCname(String cname) {
- this.cname = cname;
- }
-
- public String getCteacher() {
- return cteacher;
- }
-
- public void setCteacher(String cteacher) {
- this.cteacher = cteacher;
- }
-
- public String getPic() {
- return pic;
- }
-
- public void setPic(String pic) {
- this.pic = pic;
- }
- }
控制层ClazzController.java
- // 给数据添加服务端校验
- @RequestMapping("/valiAdd")
- public String valiAdd(@Validated Clazz clazz, BindingResult result,HttpServletRequest req){
- // 如果服务端验证不通过,有错误
- if(result.hasErrors()){
- // 服务端验证了实体类的多个属性,多个属性都没有验证通过
- List
fieldErrors = result.getFieldErrors(); - Map
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.clazzBiz.insertSelective(clazz);
- return "redirect:/clz/list";
- }
- return "clzEdit";
- }
前端代码:
- <body>
- <%--<form action="${pageContext.request.contextPath }/clz/${empty b ? 'add' : 'edit'}" method="post">--%>
- <form action="${pageContext.request.contextPath }/clz/${empty b ? 'valiAdd' : 'edit'}" method="post">
- id:<input type="text" name="cid" value="${b.cid }"><span style="color: red;">${errorMap.cid}span><br>
- cname:<input type="text" name="cname" value="${b.cname }"><span style="color: red;">${errorMap.cname}span><br>
- cteacher:<input type="text" name="cteacher" value="${b.cteacher }"><span style="color: red;">${errorMap.cteacher}span><br>
- <input type="submit">
- form>
- body>
效果:
当你不输入时就提示不能输入空值
SpringMVC的处理器拦截器,类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。
依赖于web框架,在实现上基于Java的反射机制,属于面向切面编程(AOP)的一种运用。由于拦截器是基于web框架的调用,因此可以使用Spring的依赖注入(DI)进行一些业务操作,同时一个拦截器实例在一个
controller生命周期之内可以多次调用。
依赖于servlet容器。在实现上基于函数回调,可以对几乎所有请求进行过滤,但是缺点是一个过滤器实例
只能在容器初始化时调用一次。使用过滤器的目的是用来做一些过滤操作,比如:在过滤器中修改字符编码;
在过滤器中修改HttpServletRequest的一些参数,包括:过滤低俗文字、危险字符等。
过滤器(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中的处理方法都需要的,我们就可以使用拦截器实现。
1. 拦截器入门:
①创建一个类名为HellController
- package com.ruojuan.ssm.web;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- /**
- * @author ruojuan
- * @site 123456999
- * @company 玉渊工作室
- * @create 2022-08-19 16:44
- */
- @Controller
- public class HellController {
-
- @RequestMapping("/hello")
- public String hello(){
- System.out.println("进入业务方法。。。。");
- return "List";
- }
-
- }
②再创建一个类为拦截器OneHandlerInterceptor
-
- package com.ruojuan.ssm.intercept;
-
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- /**
- * @author ruojuan
- * @site 123456999
- * @company 玉渊工作室
- * @create 2022-08-19 16:37
- */
-
- 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...");
- }
- }
-
③在springmvc-servlet.xml配置拦截器文件
-
- <mvc:interceptors>
- <bean class="com.ruojuan.ssm.intercept.OneHandlerInterceptor">bean>
- mvc:interceptors>
④结果
2.拦截器链
①创建另一个拦截器
-
- package com.ruojuan.ssm.intercept;
-
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- /**
- * @author ruojuan
- * @site 123456999
- * @company 玉渊工作室
- * @create 2022-08-19 16:37
- */
-
- 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...");
- }
- }
-
- package com.ruojuan.ssm.intercept;
-
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- /**
- * @author ruojuan
- * @site 123456999
- * @company 玉渊工作室
- * @create 2022-08-19 16:47
- */
- public class TwoHandlerInterceptor implements HandlerInterceptor {
-
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- //预处理
- System.out.println("[OneHandlerInterceptor].preHandle");
- return true;
- }
-
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
- //后处理
- System.out.println("[OneHandlerInterceptor].postHandle");
- }
-
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
- //完成后处理
- System.out.println("[OneHandlerInterceptor].afterCompletion");
- }
- }
②springmvc-servlet.xml配置文件
- <mvc:interceptors>
- <mvc:interceptor>
- <mvc:mapping path="/**"/>
- <bean class="com.zking.ssm.interceptor.OneInterceptor">bean>
- mvc:interceptor>
- <mvc:interceptor>
- <mvc:mapping path="/clz/**"/>
- <bean class="com.zking.ssm.interceptor.TwoInterceptor">bean>
- mvc:interceptor>
- mvc:interceptors>
③
④
- public class OneInterceptor implements HandlerInterceptor {
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- System.out.println("【OneInterceptor】: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)){
- return false;
- }
- 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...");
- }
- }
⑤
- @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:/clz/list";
- }
-
- @RequestMapping("/logout")
- public String logout(HttpServletRequest req){
- req.getSession().invalidate();
- return "redirect:/clz/list";
- }
- }
⑥