• SpringMVC之CRUD------增删改查


    目录

    前言

    配置文件

    pom.xml文件

    web.xml文件 

    spring-context.xml 

    spring-mvc.xml 

    spring-MyBatis.xml 

    jdbc.properties数据库配置文件

    generatorConfig.xml 

     log4j2日志文件

    后台

    PageBaen.java

    PageTag.java

    切面类 

     biz层

    定义一个接口

    再写一个实现类 

    web层 

    前台

    list.jsp

    edit.jsp 

    测试结果


    前言

    今天给大家带来的是SpringMVC的增删改查操作,也是SpringMVC中重要的部分

    配置文件

    pom.xml文件

    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>xiaoxuzyssmartifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. <packaging>warpackaging>
    9. <name>xiaoxuzyssm 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. <log4j2.disruptor.version>3.2.0log4j2.disruptor.version>
    25. <slf4j.version>1.7.13slf4j.version>
    26. <junit.version>4.12junit.version>
    27. <servlet.version>4.0.0servlet.version>
    28. <lombok.version>1.18.2lombok.version>
    29. <mybatis.ehcache.version>1.1.0mybatis.ehcache.version>
    30. <ehcache.version>2.10.0ehcache.version>
    31. <redis.version>2.9.0redis.version>
    32. <redis.spring.version>1.7.1.RELEASEredis.spring.version>
    33. <jackson.version>2.9.3jackson.version>
    34. <jstl.version>1.2jstl.version>
    35. <standard.version>1.1.2standard.version>
    36. <tomcat-jsp-api.version>8.0.47tomcat-jsp-api.version>
    37. <commons-fileupload.version>1.3.3commons-fileupload.version>
    38. <hibernate-validator.version>5.0.2.Finalhibernate-validator.version>
    39. <shiro.version>1.3.2shiro.version>
    40. properties>
    41. <dependencies>
    42. <dependency>
    43. <groupId>org.springframeworkgroupId>
    44. <artifactId>spring-coreartifactId>
    45. <version>${spring.version}version>
    46. dependency>
    47. <dependency>
    48. <groupId>org.springframeworkgroupId>
    49. <artifactId>spring-beansartifactId>
    50. <version>${spring.version}version>
    51. dependency>
    52. <dependency>
    53. <groupId>org.springframeworkgroupId>
    54. <artifactId>spring-contextartifactId>
    55. <version>${spring.version}version>
    56. dependency>
    57. <dependency>
    58. <groupId>org.springframeworkgroupId>
    59. <artifactId>spring-ormartifactId>
    60. <version>${spring.version}version>
    61. dependency>
    62. <dependency>
    63. <groupId>org.springframeworkgroupId>
    64. <artifactId>spring-txartifactId>
    65. <version>${spring.version}version>
    66. dependency>
    67. <dependency>
    68. <groupId>org.springframeworkgroupId>
    69. <artifactId>spring-aspectsartifactId>
    70. <version>${spring.version}version>
    71. dependency>
    72. <dependency>
    73. <groupId>org.springframeworkgroupId>
    74. <artifactId>spring-webartifactId>
    75. <version>${spring.version}version>
    76. dependency>
    77. <dependency>
    78. <groupId>org.springframeworkgroupId>
    79. <artifactId>spring-testartifactId>
    80. <version>${spring.version}version>
    81. dependency>
    82. <dependency>
    83. <groupId>org.mybatisgroupId>
    84. <artifactId>mybatisartifactId>
    85. <version>${mybatis.version}version>
    86. dependency>
    87. <dependency>
    88. <groupId>mysqlgroupId>
    89. <artifactId>mysql-connector-javaartifactId>
    90. <version>${mysql.version}version>
    91. dependency>
    92. <dependency>
    93. <groupId>com.github.pagehelpergroupId>
    94. <artifactId>pagehelperartifactId>
    95. <version>${pagehelper.version}version>
    96. dependency>
    97. <dependency>
    98. <groupId>org.mybatisgroupId>
    99. <artifactId>mybatis-springartifactId>
    100. <version>${mybatis.spring.version}version>
    101. dependency>
    102. <dependency>
    103. <groupId>org.springframeworkgroupId>
    104. <artifactId>spring-context-supportartifactId>
    105. <version>${spring.version}version>
    106. dependency>
    107. <dependency>
    108. <groupId>org.mybatis.cachesgroupId>
    109. <artifactId>mybatis-ehcacheartifactId>
    110. <version>${mybatis.ehcache.version}version>
    111. dependency>
    112. <dependency>
    113. <groupId>net.sf.ehcachegroupId>
    114. <artifactId>ehcacheartifactId>
    115. <version>${ehcache.version}version>
    116. dependency>
    117. <dependency>
    118. <groupId>redis.clientsgroupId>
    119. <artifactId>jedisartifactId>
    120. <version>${redis.version}version>
    121. dependency>
    122. <dependency>
    123. <groupId>org.springframework.datagroupId>
    124. <artifactId>spring-data-redisartifactId>
    125. <version>${redis.spring.version}version>
    126. dependency>
    127. <dependency>
    128. <groupId>com.fasterxml.jackson.coregroupId>
    129. <artifactId>jackson-databindartifactId>
    130. <version>${jackson.version}version>
    131. dependency>
    132. <dependency>
    133. <groupId>com.fasterxml.jackson.coregroupId>
    134. <artifactId>jackson-coreartifactId>
    135. <version>${jackson.version}version>
    136. dependency>
    137. <dependency>
    138. <groupId>com.fasterxml.jackson.coregroupId>
    139. <artifactId>jackson-annotationsartifactId>
    140. <version>${jackson.version}version>
    141. dependency>
    142. <dependency>
    143. <groupId>org.apache.commonsgroupId>
    144. <artifactId>commons-dbcp2artifactId>
    145. <version>${commons.dbcp2.version}version>
    146. <exclusions>
    147. <exclusion>
    148. <artifactId>commons-pool2artifactId>
    149. <groupId>org.apache.commonsgroupId>
    150. exclusion>
    151. exclusions>
    152. dependency>
    153. <dependency>
    154. <groupId>org.apache.commonsgroupId>
    155. <artifactId>commons-pool2artifactId>
    156. <version>${commons.pool2.version}version>
    157. dependency>
    158. <dependency>
    159. <groupId>org.springframeworkgroupId>
    160. <artifactId>spring-webmvcartifactId>
    161. <version>${spring.version}version>
    162. dependency>
    163. <dependency>
    164. <groupId>org.slf4jgroupId>
    165. <artifactId>slf4j-apiartifactId>
    166. <version>${slf4j.version}version>
    167. dependency>
    168. <dependency>
    169. <groupId>org.slf4jgroupId>
    170. <artifactId>jcl-over-slf4jartifactId>
    171. <version>${slf4j.version}version>
    172. <scope>runtimescope>
    173. dependency>
    174. <dependency>
    175. <groupId>org.apache.logging.log4jgroupId>
    176. <artifactId>log4j-apiartifactId>
    177. <version>${log4j2.version}version>
    178. dependency>
    179. <dependency>
    180. <groupId>org.apache.logging.log4jgroupId>
    181. <artifactId>log4j-coreartifactId>
    182. <version>${log4j2.version}version>
    183. dependency>
    184. <dependency>
    185. <groupId>org.apache.logging.log4jgroupId>
    186. <artifactId>log4j-slf4j-implartifactId>
    187. <version>${log4j2.version}version>
    188. dependency>
    189. <dependency>
    190. <groupId>org.apache.logging.log4jgroupId>
    191. <artifactId>log4j-webartifactId>
    192. <version>${log4j2.version}version>
    193. <scope>runtimescope>
    194. dependency>
    195. <dependency>
    196. <groupId>com.lmaxgroupId>
    197. <artifactId>disruptorartifactId>
    198. <version>${log4j2.disruptor.version}version>
    199. dependency>
    200. <dependency>
    201. <groupId>junitgroupId>
    202. <artifactId>junitartifactId>
    203. <version>${junit.version}version>
    204. <scope>testscope>
    205. dependency>
    206. <dependency>
    207. <groupId>javax.servletgroupId>
    208. <artifactId>javax.servlet-apiartifactId>
    209. <version>${servlet.version}version>
    210. <scope>providedscope>
    211. dependency>
    212. <dependency>
    213. <groupId>org.projectlombokgroupId>
    214. <artifactId>lombokartifactId>
    215. <version>${lombok.version}version>
    216. <scope>providedscope>
    217. dependency>
    218. <dependency>
    219. <groupId>jstlgroupId>
    220. <artifactId>jstlartifactId>
    221. <version>${jstl.version}version>
    222. dependency>
    223. <dependency>
    224. <groupId>taglibsgroupId>
    225. <artifactId>standardartifactId>
    226. <version>${standard.version}version>
    227. dependency>
    228. <dependency>
    229. <groupId>org.apache.tomcatgroupId>
    230. <artifactId>tomcat-jsp-apiartifactId>
    231. <version>${tomcat-jsp-api.version}version>
    232. dependency>
    233. <dependency>
    234. <groupId>commons-fileuploadgroupId>
    235. <artifactId>commons-fileuploadartifactId>
    236. <version>${commons-fileupload.version}version>
    237. dependency>
    238. <dependency>
    239. <groupId>org.hibernategroupId>
    240. <artifactId>hibernate-validatorartifactId>
    241. <version>${hibernate-validator.version}version>
    242. dependency>
    243. <dependency>
    244. <groupId>org.apache.shirogroupId>
    245. <artifactId>shiro-coreartifactId>
    246. <version>${shiro.version}version>
    247. dependency>
    248. <dependency>
    249. <groupId>org.apache.shirogroupId>
    250. <artifactId>shiro-webartifactId>
    251. <version>${shiro.version}version>
    252. dependency>
    253. <dependency>
    254. <groupId>org.apache.shirogroupId>
    255. <artifactId>shiro-springartifactId>
    256. <version>${shiro.version}version>
    257. dependency>
    258. dependencies>
    259. <build>
    260. <finalName>xiaoxuzyssmfinalName>
    261. <resources>
    262. <resource>
    263. <directory>src/main/javadirectory>
    264. <includes>
    265. <include>**/*.xmlinclude>
    266. includes>
    267. resource>
    268. <resource>
    269. <directory>src/main/resourcesdirectory>
    270. <includes>
    271. <include>*.propertiesinclude>
    272. <include>*.xmlinclude>
    273. includes>
    274. resource>
    275. resources>
    276. <plugins>
    277. <plugin>
    278. <groupId>org.apache.maven.pluginsgroupId>
    279. <artifactId>maven-compiler-pluginartifactId>
    280. <version>${maven.compiler.plugin.version}version>
    281. <configuration>
    282. <source>${maven.compiler.source}source>
    283. <target>${maven.compiler.target}target>
    284. <encoding>${project.build.sourceEncoding}encoding>
    285. configuration>
    286. plugin>
    287. <plugin>
    288. <groupId>org.mybatis.generatorgroupId>
    289. <artifactId>mybatis-generator-maven-pluginartifactId>
    290. <version>1.3.2version>
    291. <dependencies>
    292. <dependency>
    293. <groupId>mysqlgroupId>
    294. <artifactId>mysql-connector-javaartifactId>
    295. <version>${mysql.version}version>
    296. dependency>
    297. dependencies>
    298. <configuration>
    299. <overwrite>trueoverwrite>
    300. configuration>
    301. plugin>
    302. <plugin>
    303. <artifactId>maven-clean-pluginartifactId>
    304. <version>3.1.0version>
    305. plugin>
    306. <plugin>
    307. <artifactId>maven-resources-pluginartifactId>
    308. <version>3.0.2version>
    309. plugin>
    310. <plugin>
    311. <artifactId>maven-compiler-pluginartifactId>
    312. <version>3.8.0version>
    313. plugin>
    314. <plugin>
    315. <artifactId>maven-surefire-pluginartifactId>
    316. <version>2.22.1version>
    317. plugin>
    318. <plugin>
    319. <artifactId>maven-war-pluginartifactId>
    320. <version>3.2.2version>
    321. plugin>
    322. <plugin>
    323. <artifactId>maven-install-pluginartifactId>
    324. <version>2.5.2version>
    325. plugin>
    326. <plugin>
    327. <artifactId>maven-deploy-pluginartifactId>
    328. <version>2.8.2version>
    329. plugin>
    330. plugins>
    331. build>
    332. project>

    web.xml文件 

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    5. version="3.1">
    6. <display-name>Archetype Created Web Application</display-name>
    7. <!-- Spring和web项目集成start -->
    8. <!-- spring上下文配置文件 -->
    9. <context-param>
    10. <param-name>contextConfigLocation</param-name>
    11. <param-value>classpath:spring-context.xml</param-value>
    12. </context-param>
    13. <!-- 读取Spring上下文的监听器 -->
    14. <listener>
    15. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    16. </listener>
    17. <!-- Spring和web项目集成end -->
    18. <!-- 中文乱码处理 -->
    19. <filter>
    20. <filter-name>encodingFilter</filter-name>
    21. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    22. <async-supported>true</async-supported>
    23. <init-param>
    24. <param-name>encoding</param-name>
    25. <param-value>UTF-8</param-value>
    26. </init-param>
    27. </filter>
    28. <filter-mapping>
    29. <filter-name>encodingFilter</filter-name>
    30. <url-pattern>/*</url-pattern>
    31. </filter-mapping>
    32. <!-- Spring MVC servlet -->
    33. <servlet>
    34. <servlet-name>SpringMVC</servlet-name>
    35. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    36. <!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
    37. <init-param>
    38. <param-name>contextConfigLocation</param-name>
    39. <param-value>classpath:spring-mvc.xml</param-value>
    40. </init-param>
    41. <load-on-startup>1</load-on-startup>
    42. <!--web.xml 3.0的新特性,是否支持异步-->
    43. <async-supported>true</async-supported>
    44. </servlet>
    45. <servlet-mapping>
    46. <servlet-name>SpringMVC</servlet-name>
    47. <url-pattern>/</url-pattern>
    48. </servlet-mapping>
    49. </web-app>

    spring-context.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. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <import resource="classpath:spring-mybatis.xml">import>
    6. beans>

    spring-mvc.xml 

    1. <?xml version="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:aop="http://www.springframework.org/schema/aop"
    6. xmlns:mvc="http://www.springframework.org/schema/mvc"
    7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    9. http://www.springframework.org/schema/aop
    10. http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    11. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    12. <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    13. <context:component-scan base-package="com.xiaoxu"/>
    14. <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    15. <mvc:annotation-driven />
    16. <!--3) 创建ViewResolver视图解析器 -->
    17. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    18. <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
    19. <property name="viewClass"
    20. value="org.springframework.web.servlet.view.JstlView"></property>
    21. <property name="prefix" value="/WEB-INF/jsp/"/>
    22. <property name="suffix" value=".jsp"/>
    23. </bean>
    24. <!--4) 单独处理图片、样式、js等资源 -->
    25. <!-- <mvc:resources location="/css/" mapping="/css/**"/>
    26. <mvc:resources location="/js/" mapping="/js/**"/>
    27. <mvc:resources location="WEB-INF/images/" mapping="/images/**"/>-->
    28. <!-- <mvc:resources location="/static/" mapping="/static/**"/>-->
    29. <aop:aspectj-autoproxy/>
    30. </beans>

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

    jdbc.properties数据库配置文件

    这里咱们链接自己的数据库

    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:\\temp2\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44"/>
    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.xiaoxu.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.xiaoxu.mapper"
    25. targetProject="src/main/java">
    26. <property name="enableSubPackages" value="false"/>
    27. sqlMapGenerator>
    28. <javaClientGenerator targetPackage="com.xiaoxu.mapper"
    29. targetProject="src/main/java" type="XMLMAPPER">
    30. <property name="enableSubPackages" value="false"/>
    31. javaClientGenerator>
    32. <table schema="" tableName="t_hibernate_book" domainObjectName="Bookxx"
    33. enableCountByExample="false" enableDeleteByExample="false"
    34. enableSelectByExample="false" enableUpdateByExample="false">
    35. table>
    36. context>
    37. generatorConfiguration>

     log4j2日志文件

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!-- status : 指定log4j本身的打印日志的级别.ALL< Trace < DEBUG < INFO < WARN < ERROR
    3. < FATAL < OFF。 monitorInterval : 用于指定log4j自动重新配置的监测间隔时间,单位是s,最小是5s. -->
    4. <Configuration status="WARN" monitorInterval="30">
    5. <Properties>
    6. <!-- 配置日志文件输出目录 ${sys:user.home} -->
    7. <Property name="LOG_HOME">/root/workspace/lucenedemo/logs</Property>
    8. <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/error</property>
    9. <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warn</property>
    10. <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n</property>
    11. </Properties>
    12. <Appenders>
    13. <!--这个输出控制台的配置 -->
    14. <Console name="Console" target="SYSTEM_OUT">
    15. <!-- 控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
    16. <ThresholdFilter level="trace" onMatch="ACCEPT"
    17. onMismatch="DENY" />
    18. <!-- 输出日志的格式 -->
    19. <!-- %d{yyyy-MM-dd HH:mm:ss, SSS} : 日志生产时间 %p : 日志输出格式 %c : logger的名称
    20. %m : 日志内容,即 logger.info("message") %n : 换行符 %C : Java类名 %L : 日志输出所在行数 %M
    21. : 日志输出所在方法名 hostName : 本地机器名 hostAddress : 本地ip地址 -->
    22. <PatternLayout pattern="${PATTERN}" />
    23. </Console>
    24. <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用 -->
    25. <!--append为TRUE表示消息增加到指定文件中,false表示消息覆盖指定的文件内容,默认值是true -->
    26. <File name="log" fileName="logs/test.log" append="false">
    27. <PatternLayout
    28. pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    29. </File>
    30. <!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size, 则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档 -->
    31. <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
    32. filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
    33. <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch) -->
    34. <ThresholdFilter level="info" onMatch="ACCEPT"
    35. onMismatch="DENY" />
    36. <PatternLayout
    37. pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    38. <Policies>
    39. <!-- 基于时间的滚动策略,interval属性用来指定多久滚动一次,默认是1 hour。 modulate=true用来调整时间:比如现在是早上3am,interval是4,那么第一次滚动是在4am,接着是8am,12am...而不是7am. -->
    40. <!-- 关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval, 日期格式精确到哪一位,interval也精确到哪一个单位 -->
    41. <!-- log4j2的按天分日志文件 : info-%d{yyyy-MM-dd}-%i.log -->
    42. <TimeBasedTriggeringPolicy interval="1"
    43. modulate="true" />
    44. <!-- SizeBasedTriggeringPolicy:Policies子节点, 基于指定文件大小的滚动策略,size属性用来定义每个日志文件的大小. -->
    45. <!-- <SizeBasedTriggeringPolicy size="2 kB" /> -->
    46. </Policies>
    47. </RollingFile>
    48. <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
    49. filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
    50. <ThresholdFilter level="warn" onMatch="ACCEPT"
    51. onMismatch="DENY" />
    52. <PatternLayout
    53. pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    54. <Policies>
    55. <TimeBasedTriggeringPolicy />
    56. <SizeBasedTriggeringPolicy size="2 kB" />
    57. </Policies>
    58. <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了20 -->
    59. <DefaultRolloverStrategy max="20" />
    60. </RollingFile>
    61. <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
    62. filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
    63. <ThresholdFilter level="error" onMatch="ACCEPT"
    64. onMismatch="DENY" />
    65. <PatternLayout
    66. pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    67. <Policies>
    68. <!-- log4j2的按分钟 分日志文件 : warn-%d{yyyy-MM-dd-HH-mm}-%i.log -->
    69. <TimeBasedTriggeringPolicy interval="1"
    70. modulate="true" />
    71. <!-- <SizeBasedTriggeringPolicy size="10 MB" /> -->
    72. </Policies>
    73. </RollingFile>
    74. </Appenders>
    75. <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效 -->
    76. <Loggers>
    77. <!--过滤掉spring和mybatis的一些无用的DEBUG信息 -->
    78. <logger name="org.springframework" level="INFO"></logger>
    79. <logger name="org.mybatis" level="INFO"></logger>
    80. <!-- 第三方日志系统 -->
    81. <logger name="org.springframework" level="ERROR" />
    82. <logger name="org.hibernate" level="ERROR" />
    83. <logger name="org.apache.struts2" level="ERROR" />
    84. <logger name="com.opensymphony.xwork2" level="ERROR" />
    85. <logger name="org.jboss" level="ERROR" />
    86. <!-- 配置日志的根节点 -->
    87. <root level="all">
    88. <appender-ref ref="Console" />
    89. <appender-ref ref="RollingFileInfo" />
    90. <appender-ref ref="RollingFileWarn" />
    91. <appender-ref ref="RollingFileError" />
    92. </root>
    93. </Loggers>
    94. </Configuration>

     

     代码生成完之后,就代表我们已经配置好了!!!

    后台

    接下来写我们需要用到的工具类

    PageBaen.java

    1. package com.xiaoxu.utis;
    2. import javax.servlet.http.HttpServletRequest;
    3. import java.io.Serializable;
    4. import java.util.Map;
    5. public class PageBean implements Serializable {
    6. private static final long serialVersionUID = 2422581023658455731L;
    7. //页码
    8. private int page=1;
    9. //每页显示记录数
    10. private int rows=10;
    11. //总记录数
    12. private int total=0;
    13. //是否分页
    14. private boolean isPagination=true;
    15. //上一次的请求路径
    16. private String url;
    17. //获取所有的请求参数
    18. private Map<String,String[]> map;
    19. public PageBean() {
    20. super();
    21. }
    22. //设置请求参数
    23. public void setRequest(HttpServletRequest req) {
    24. String page=req.getParameter("page");
    25. String rows=req.getParameter("rows");
    26. String pagination=req.getParameter("pagination");
    27. this.setPage(page);
    28. this.setRows(rows);
    29. this.setPagination(pagination);
    30. this.url=req.getContextPath()+req.getServletPath();
    31. this.map=req.getParameterMap();
    32. }
    33. public String getUrl() {
    34. return url;
    35. }
    36. public void setUrl(String url) {
    37. this.url = url;
    38. }
    39. public Map<String, String[]> getMap() {
    40. return map;
    41. }
    42. public void setMap(Map<String, String[]> map) {
    43. this.map = map;
    44. }
    45. public int getPage() {
    46. return page;
    47. }
    48. public void setPage(int page) {
    49. this.page = page;
    50. }
    51. public void setPage(String page) {
    52. if(null!=page&&!"".equals(page.trim()))
    53. this.page = Integer.parseInt(page);
    54. }
    55. public int getRows() {
    56. return rows;
    57. }
    58. public void setRows(int rows) {
    59. this.rows = rows;
    60. }
    61. public void setRows(String rows) {
    62. if(null!=rows&&!"".equals(rows.trim()))
    63. this.rows = Integer.parseInt(rows);
    64. }
    65. public int getTotal() {
    66. return total;
    67. }
    68. public void setTotal(int total) {
    69. this.total = total;
    70. }
    71. public void setTotal(String total) {
    72. this.total = Integer.parseInt(total);
    73. }
    74. public boolean isPagination() {
    75. return isPagination;
    76. }
    77. public void setPagination(boolean isPagination) {
    78. this.isPagination = isPagination;
    79. }
    80. public void setPagination(String isPagination) {
    81. if(null!=isPagination&&!"".equals(isPagination.trim()))
    82. this.isPagination = Boolean.parseBoolean(isPagination);
    83. }
    84. /**
    85. * 获取分页起始标记位置
    86. * @return
    87. */
    88. public int getStartIndex() {
    89. //(当前页码-1)*显示记录数
    90. return (this.getPage()-1)*this.rows;
    91. }
    92. /**
    93. * 末页
    94. * @return
    95. */
    96. public int getMaxPage() {
    97. int totalpage=this.total/this.rows;
    98. if(this.total%this.rows!=0)
    99. totalpage++;
    100. return totalpage;
    101. }
    102. /**
    103. * 下一页
    104. * @return
    105. */
    106. public int getNextPage() {
    107. int nextPage=this.page+1;
    108. if(this.page>=this.getMaxPage())
    109. nextPage=this.getMaxPage();
    110. return nextPage;
    111. }
    112. /**
    113. * 上一页
    114. * @return
    115. */
    116. public int getPreivousPage() {
    117. int previousPage=this.page-1;
    118. if(previousPage<1)
    119. previousPage=1;
    120. return previousPage;
    121. }
    122. @Override
    123. public String toString() {
    124. return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
    125. + "]";
    126. }
    127. }

    PageTag.java

    1. package com.xiaoxu.tag;
    2. import com.xiaoxu.utis.PageBean;
    3. import java.io.IOException;
    4. import java.util.Map;
    5. import java.util.Map.Entry;
    6. import java.util.Set;
    7. import javax.servlet.jsp.JspException;
    8. import javax.servlet.jsp.JspWriter;
    9. import javax.servlet.jsp.tagext.BodyTagSupport;
    10. public class PageTag extends BodyTagSupport{
    11. private PageBean pageBean;// 包含了所有分页相关的元素
    12. public PageBean getPageBean() {
    13. return pageBean;
    14. }
    15. public void setPageBean(PageBean pageBean) {
    16. this.pageBean = pageBean;
    17. }
    18. @Override
    19. public int doStartTag() throws JspException {
    20. // 没有标签体,要输出内容
    21. JspWriter out = pageContext.getOut();
    22. try {
    23. out.print(toHTML());
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. }
    27. return super.doStartTag();
    28. }
    29. private String toHTML() {
    30. StringBuffer sb = new StringBuffer();
    31. // 隐藏的form表单---这个就是上一次请求下次重新发的奥义所在
    32. // 上一次请求的URL
    33. sb.append("
      ");
    34. sb.append(" ");
    35. // 上一次请求的参数
    36. Map<String, String[]> paramMap = pageBean.getMap();
    37. if(paramMap != null && paramMap.size() > 0) {
    38. Set<Entry<String, String[]>> entrySet = paramMap.entrySet();
    39. for (Entry<String, String[]> entry : entrySet) {
    40. // 参数名
    41. String key = entry.getKey();
    42. // 参数值
    43. for (String value : entry.getValue()) {
    44. // 上一次请求的参数,再一次组装成了新的Form表单
    45. // 注意:page参数每次都会提交,我们需要避免
    46. if(!"page".equals(key)) {
    47. sb.append(" ");
    48. }
    49. }
    50. }
    51. }
    52. sb.append("");
    53. // 分页条
    54. sb.append("
        ");
    55. sb.append("
    56. );
  • ");
  • sb.append("
  • );
  • ");// less than 小于号
  • // sb.append("
  • 1
  • ");
  • // sb.append("
  • 2
  • ");
  • sb.append("
  • "+pageBean.getPage()+"
  • ");
  • sb.append("
  • >
  • ");
  • sb.append("
  • 尾页
  • ");
  • sb.append("
  • 到第);
  • sb.append(" type='text' id='skipPage' name='' />
  • ");
  • sb.append("
  • );
  • ");
  • sb.append("
  • 共"+pageBean.getTotal()+"条
  • ");
  • sb.append("");
  • // 分页执行的JS代码
  • sb.append("");
  • return sb.toString();
  • }
  • }
  • 切面类 

    1. package com.xiaoxu.aspect;
    2. import com.github.pagehelper.PageHelper;
    3. import com.github.pagehelper.PageInfo;
    4. import com.xiaoxu.utis.PageBean;
    5. import org.aspectj.lang.ProceedingJoinPoint;
    6. import org.aspectj.lang.annotation.Around;
    7. import org.aspectj.lang.annotation.Aspect;
    8. import org.springframework.stereotype.Component;
    9. import java.util.List;
    10. /**
    11. * @author小徐
    12. * @site www.veryedu.cn
    13. * @company xu集团
    14. * @create 2023-08-25 17:24
    15. *
    16. * * *..*Service.*Pager(..)
    17. * *:任意返回值类型
    18. * *..:任意包,不限层级
    19. * *service:以serveice结尾的类/接口
    20. * *page:以page结尾的方法
    21. * ..:任意参数
    22. * 符合上述条件,即为目标类或者目标方法
    23. */
    24. @Aspect//代表当前类为切面类
    25. @Component//代表当前类交给spring进行管理
    26. public class PagerAspect {
    27. @Around("execution(* *..*Biz.*Page(..))")
    28. public Object invoke(ProceedingJoinPoint args) throws Throwable {
    29. PageBean pageBean = null;
    30. Object[] params = args.getArgs();
    31. for (Object param : params) {
    32. if(param instanceof PageBean){
    33. pageBean = (PageBean)param;
    34. break;
    35. }
    36. }
    37. if(pageBean != null && pageBean.isPagination())
    38. PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
    39. Object list = args.proceed(params);
    40. if(null != pageBean && pageBean.isPagination()){
    41. PageInfo pageInfo = new PageInfo((List) list);
    42. pageBean.setTotal(pageInfo.getTotal()+"");
    43. }
    44. return list;
    45. }
    46. }

     biz层

    定义一个接口

    再写一个实现类 

    1. package com.xiaoxu.impl;
    2. import com.xiaoxu.biz.BookxxBiz;
    3. import com.xiaoxu.mapper.BookxxMapper;
    4. import com.xiaoxu.model.Bookxx;
    5. import com.xiaoxu.utis.PageBean;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Service;
    8. import java.util.List;
    9. /**
    10. * @author小徐
    11. * @site www.veryedu.cn
    12. * @company xu集团
    13. * @create 2023-09-07 18:05
    14. */
    15. @Service
    16. public class BookxxBizImpl implements BookxxBiz {
    17. @Autowired
    18. private BookxxMapper bookxxMapper;
    19. @Override
    20. public int deleteByPrimaryKey(Integer book_id) {
    21. return bookxxMapper.deleteByPrimaryKey(book_id);
    22. }
    23. @Override
    24. public int insert(Bookxx record) {
    25. return bookxxMapper.insert(record);
    26. }
    27. @Override
    28. public int insertSelective(Bookxx record) {
    29. return bookxxMapper.insertSelective(record);
    30. }
    31. @Override
    32. public Bookxx selectByPrimaryKey(Integer book_id) {
    33. return bookxxMapper.selectByPrimaryKey(book_id);
    34. }
    35. @Override
    36. public int updateByPrimaryKeySelective(Bookxx record) {
    37. return bookxxMapper.updateByPrimaryKeySelective(record);
    38. }
    39. @Override
    40. public int updateByPrimaryKey(Bookxx record) {
    41. return bookxxMapper.updateByPrimaryKey(record);
    42. }
    43. @Override
    44. public List selectPage(Bookxx bookxx, PageBean pageBean) {
    45. return bookxxMapper.selectPage(bookxx);
    46. }
    47. }

    web层 

    1. package com.xiaoxu.web;
    2. import com.xiaoxu.biz.BookxxBiz;
    3. import com.xiaoxu.model.Bookxx;
    4. import com.xiaoxu.utis.PageBean;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Controller;
    7. import org.springframework.ui.Model;
    8. import org.springframework.web.bind.annotation.PathVariable;
    9. import org.springframework.web.bind.annotation.RequestMapping;
    10. import javax.servlet.http.HttpServletRequest;
    11. import java.util.List;
    12. /**
    13. * @author小徐
    14. * @site www.veryedu.cn
    15. * @company xu集团
    16. * @create 2023-09-08 2:44
    17. */
    18. @Controller
    19. @RequestMapping("/clz")
    20. public class BookxxController {
    21. @Autowired
    22. private BookxxBiz bookxxBiz;
    23. //增
    24. @RequestMapping("/add")
    25. public String add(Bookxx bookxx){
    26. int i = bookxxBiz.insertSelective(bookxx);
    27. return "redirect:list";
    28. }
    29. //删
    30. @RequestMapping("/del/{book_id}")
    31. public String del(@PathVariable("book_id") Integer book_id){
    32. bookxxBiz.deleteByPrimaryKey(book_id);
    33. return "redirect:/clz/list";
    34. }
    35. //改
    36. @RequestMapping("/edit")
    37. public String edit(Bookxx bookxx){
    38. bookxxBiz.updateByPrimaryKeySelective(bookxx);
    39. return "redirect:list";
    40. }
    41. //查
    42. @RequestMapping("/list")
    43. public String list(Bookxx bookxx,
    44. HttpServletRequest request) {
    45. PageBean pageBean = new PageBean();
    46. pageBean.setRequest(request);
    47. List<Bookxx> bookxxes = bookxxBiz.selectPage(bookxx, pageBean);
    48. request.setAttribute("list", bookxxes);
    49. request.setAttribute("pageBean", pageBean);
    50. return "clz/list";
    51. }
    52. //数据回显
    53. @RequestMapping("/preSave")
    54. public String preSave(Bookxx bookxx, Model model){
    55. if (bookxx != null && bookxx.getBook_id() != null && bookxx.getBook_id() != 0){
    56. Bookxx book = bookxxBiz.selectByPrimaryKey(bookxx.getBook_id());
    57. model.addAttribute("book",book);
    58. }
    59. return "clz/edit";
    60. }
    61. }

    前台

    list.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
    4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    6. <html>
    7. <head>
    8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    9. <link
    10. href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
    11. rel="stylesheet">
    12. <script
    13. src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
    14. <title>博客列表</title>
    15. <style type="text/css">
    16. .page-item input {
    17. padding: 0;
    18. width: 40px;
    19. height: 100%;
    20. text-align: center;
    21. margin: 0 6px;
    22. }
    23. .page-item input, .page-item b {
    24. line-height: 38px;
    25. float: left;
    26. font-weight: 400;
    27. }
    28. .page-item.go-input {
    29. margin: 0 10px;
    30. }
    31. </style>
    32. </head>
    33. <body>
    34. <form class="form-inline"
    35. action="${pageContext.request.contextPath }/clz/list" method="post">
    36. <div class="form-group mb-2">
    37. <input type="text" class="form-control-plaintext" name="book_name"
    38. placeholder="请输入书籍名称">
    39. <!-- <input name="rows" value="20" type="hidden"> -->
    40. <!-- 不想分页 -->
    41. </div>
    42. <button type="submit" class="btn btn-primary mb-2">查询</button>
    43. <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/clz/preSave">新增</a>
    44. </form>
    45. <table class="table table-striped ">
    46. <thead>
    47. <tr>
    48. <th scope="col">书籍编号</th>
    49. <th scope="col">书籍名字</th>
    50. <th scope="col">价格</th>
    51. <th scope="col">操作</th>
    52. </tr>
    53. </thead>
    54. <tbody>
    55. <c:forEach var="b" items="${list }">
    56. <tr>
    57. <td>${b.book_id }</td>
    58. <td>${b.book_name }</td>
    59. <td>${b.price }</td>
    60. <td>
    61. <a href="${pageContext.request.contextPath }/clz/preSave?book_id=${b.book_id}">修改</a>
    62. <a href="${pageContext.request.contextPath }/clz/del/${b.book_id}">删除</a>
    63. </td>
    64. </tr>
    65. </c:forEach>
    66. </tbody>
    67. </table>
    68. <!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
    69. <z:page pageBean="${pageBean }"></z:page>
    70. ${pageBean }
    71. </body>
    72. </html>

    edit.jsp 

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>Title</title>
    5. </head>
    6. <body>
    7. <h1>编辑界面</h1>
    8. <form action="${pageContext.request.contextPath }/clz/${empty book?'add' : 'edit'}" method="post">
    9. 书籍编号:<input type="text" name="book_id" value="${book.book_id }"><br>
    10. 书籍名字:<input type="text" name="book_name" value="${book.book_name }"><br>
    11. 价格:<input type="text" name="price" value="${book.price }"><br>
    12. <input type="submit">
    13. </form>
    14. </body>
    15. </html>

    测试结果

  • 相关阅读:
    【Go事】一眼看穿 Go 的集合和切片
    boom lab分析
    Spring IoC容器简介说明(BeanFactory和ApplicationContext)
    用go封装一下封禁功能
    附录4-JS关键字
    【前端知识】Three 学习日志(十)—— 常见几何体(长方体、球体、圆柱、矩形平面、圆形平面)
    AI大发展:人机交互、智能生活全解析
    顺序表与单链表
    Vue介绍&如何安装vue&Vue生命周期钩子&MVVM
    “微软爱写作”连词摘录
  • 原文地址:https://blog.csdn.net/m0_74934282/article/details/132767020