• Spring-MVC的crud增删改查--详细讲解


    目录

    一.前言

    二.crud---配置文件

     2.1 pom.xml文件

    2.2 web.xml文件 

    2.3 spring-context.xml

    2.4 spring-mvc.xml

    2.5 spring-MyBatis.xml

     2.6 jdbc.properties数据库配置文件

    2.7 generatorConfig.xml

     2.8 日志文件log4j

    三.后台

             3.1 pageBean.java 

    3.2 pageTag

    3.3 切面类

    3.4 biz层

    3.5 web层

    四.前端

     4.1 list.jsp

    4.2 edit.jsp

    今天的分享就到这啦!!!


    一.前言

            今天给大家分享,每个框架都需要学习的增删改查,在我们后端上班敲代码期间似乎60%的时间都是在写增删改查,所以这是我们作为程序员或却不可的技能,接下来,我们一起来学习吧!!!

    二.crud---配置文件

           用到的工具是Idea,我们创建好项目之后,就需要来配置相应的文件。

            2.1 pom.xml文件

            可以看到注释知道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>com.zkinggroupId>
    6. <artifactId>yzssmartifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. <packaging>warpackaging>
    9. <name>yzssm 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. dependency>
    205. <dependency>
    206. <groupId>javax.servletgroupId>
    207. <artifactId>javax.servlet-apiartifactId>
    208. <version>${servlet.version}version>
    209. <scope>providedscope>
    210. dependency>
    211. <dependency>
    212. <groupId>org.projectlombokgroupId>
    213. <artifactId>lombokartifactId>
    214. <version>${lombok.version}version>
    215. <scope>providedscope>
    216. dependency>
    217. <dependency>
    218. <groupId>jstlgroupId>
    219. <artifactId>jstlartifactId>
    220. <version>${jstl.version}version>
    221. dependency>
    222. <dependency>
    223. <groupId>taglibsgroupId>
    224. <artifactId>standardartifactId>
    225. <version>${standard.version}version>
    226. dependency>
    227. <dependency>
    228. <groupId>org.apache.tomcatgroupId>
    229. <artifactId>tomcat-jsp-apiartifactId>
    230. <version>${tomcat-jsp-api.version}version>
    231. dependency>
    232. <dependency>
    233. <groupId>commons-fileuploadgroupId>
    234. <artifactId>commons-fileuploadartifactId>
    235. <version>${commons-fileupload.version}version>
    236. dependency>
    237. <dependency>
    238. <groupId>org.hibernategroupId>
    239. <artifactId>hibernate-validatorartifactId>
    240. <version>${hibernate-validator.version}version>
    241. dependency>
    242. <dependency>
    243. <groupId>org.apache.shirogroupId>
    244. <artifactId>shiro-coreartifactId>
    245. <version>${shiro.version}version>
    246. dependency>
    247. <dependency>
    248. <groupId>org.apache.shirogroupId>
    249. <artifactId>shiro-webartifactId>
    250. <version>${shiro.version}version>
    251. dependency>
    252. <dependency>
    253. <groupId>org.apache.shirogroupId>
    254. <artifactId>shiro-springartifactId>
    255. <version>${shiro.version}version>
    256. dependency>
    257. dependencies>
    258. <build>
    259. <finalName>yzssmfinalName>
    260. <resources>
    261. <resource>
    262. <directory>src/main/javadirectory>
    263. <includes>
    264. <include>**/*.xmlinclude>
    265. includes>
    266. resource>
    267. <resource>
    268. <directory>src/main/resourcesdirectory>
    269. <includes>
    270. <include>jdbc.propertiesinclude>
    271. <include>*.xmlinclude>
    272. includes>
    273. resource>
    274. resources>
    275. <plugins>
    276. <plugin>
    277. <groupId>org.apache.maven.pluginsgroupId>
    278. <artifactId>maven-compiler-pluginartifactId>
    279. <version>${maven.compiler.plugin.version}version>
    280. <configuration>
    281. <source>${maven.compiler.source}source>
    282. <target>${maven.compiler.target}target>
    283. <encoding>${project.build.sourceEncoding}encoding>
    284. configuration>
    285. plugin>
    286. <plugin>
    287. <groupId>org.mybatis.generatorgroupId>
    288. <artifactId>mybatis-generator-maven-pluginartifactId>
    289. <version>1.3.2version>
    290. <dependencies>
    291. <dependency>
    292. <groupId>mysqlgroupId>
    293. <artifactId>mysql-connector-javaartifactId>
    294. <version>${mysql.version}version>
    295. dependency>
    296. dependencies>
    297. <configuration>
    298. <overwrite>trueoverwrite>
    299. configuration>
    300. plugin>
    301. <plugin>
    302. <artifactId>maven-clean-pluginartifactId>
    303. <version>3.1.0version>
    304. plugin>
    305. <plugin>
    306. <artifactId>maven-resources-pluginartifactId>
    307. <version>3.0.2version>
    308. plugin>
    309. <plugin>
    310. <artifactId>maven-compiler-pluginartifactId>
    311. <version>3.8.0version>
    312. plugin>
    313. <plugin>
    314. <artifactId>maven-surefire-pluginartifactId>
    315. <version>2.22.1version>
    316. plugin>
    317. <plugin>
    318. <artifactId>maven-war-pluginartifactId>
    319. <version>3.2.2version>
    320. plugin>
    321. <plugin>
    322. <artifactId>maven-install-pluginartifactId>
    323. <version>2.5.2version>
    324. plugin>
    325. <plugin>
    326. <artifactId>maven-deploy-pluginartifactId>
    327. <version>2.8.2version>
    328. plugin>
    329. plugins>
    330. build>
    331. project>

    2.2 web.xml文件 

            在这里我们需要建立两个资源包,一个是spring-context.xml,一个是spring-mvc.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>

    2.3 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>

    2.4 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:mvc="http://www.springframework.org/schema/mvc"
    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">
    8. <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    9. <context:component-scan base-package="com.yinzi"/>
    10. <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    11. <mvc:annotation-driven />
    12. <!--3) 创建ViewResolver视图解析器 -->
    13. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    14. <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
    15. <property name="viewClass"
    16. value="org.springframework.web.servlet.view.JstlView"></property>
    17. <property name="prefix" value="/WEB-INF/"/>
    18. <property name="suffix" value=".jsp"/>
    19. </bean>
    20. </beans>

    2.5 spring-MyBatis.xml

            spring与MyBatis的整合

    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.yinzi"/>
    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/yinzi/**/mapper/*.xml"/>
    25. <property name="typeAliasesPackage" value="com/yinzi/**/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/yinzi/**/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>

     2.6 jdbc.properties数据库配置文件

            连接数据库

    2.7 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="F:\\temp\\maven_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}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
    13. <javaTypeResolver>
    14. <property name="forceBigDecimals" value="false"/>
    15. javaTypeResolver>
    16. <javaModelGenerator targetPackage="com.yinzi.model" targetProject="src/main/java">
    17. <property name="enableSubPackages" value="false"/>
    18. <property name="constructorBased" value="true"/>
    19. <property name="trimStrings" value="false"/>
    20. <property name="immutable" value="false"/>
    21. javaModelGenerator>
    22. <sqlMapGenerator targetPackage="com.yinzi.mapper" targetProject="src/main/java">
    23. <property name="enableSubPackages" value="false"/>
    24. sqlMapGenerator>
    25. <javaClientGenerator targetPackage="com.yinzi.mapper" targetProject="src/main/java" type="XMLMAPPER">
    26. <property name="enableSubPackages" value="false"/>
    27. javaClientGenerator>
    28. <table schema="" tableName="t_mvc_book" domainObjectName="Book"
    29. enableCountByExample="false" enableDeleteByExample="false"
    30. enableSelectByExample="false" enableUpdateByExample="false">
    31. table>
    32. context>
    33. generatorConfiguration>

     2.8 日志文件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>

            到这项目之前的所有准备工作已经写完了,配置以及全部配完了,接下来就可以写后台!!

    三.后台

            我们先写好需要的工具类

            等下需要分页,所有单独写了两个类,来写分页的属性及方法

            3.1 pageBean.java 

            上一页,下一页,最大页,最小页,及判空

    1. package com.yinzi.util;
    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. }

    3.2 pageTag

            首页,尾页

    1. package com.yinzi.tag;
    2. import com.yinzi.util.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();
  • }
  • }
  • 3.3 切面类

    运用了环绕通知,日志管理,进行筛选及判断分页是否为空

    1. package com.yinzi.aspect;
    2. import com.github.pagehelper.PageHelper;
    3. import com.github.pagehelper.PageInfo;
    4. import com.yinzi.util.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 yinzi
    12. * @create 2023-08-25 17:05
    13. */
    14. @Aspect //代表为切面类
    15. @Component //代表该类交给spring管理
    16. public class PageAspect {
    17. @Around("execution(* *..*Biz.*List(..))") //环绕通知
    18. //* *..*Service.*Pager(..))
    19. //第一个* 代表了任意返回值
    20. //*.. 代表了任意包,不限层级
    21. //*Service 代表了以Service结尾的类/接口
    22. //*Pager 代表了以pager结尾的方法
    23. //.. 括号的点点 代表了任意参数
    24. //符合以上则为目标类或者目标方法
    25. public Object invoke(ProceedingJoinPoint args) throws Throwable {
    26. PageBean pageBean=null;
    27. //获取目标方法的所有参数
    28. Object[] args1 = args.getArgs();
    29. for (Object parm:args1){
    30. //如果有参数是pageBean 那么就强转
    31. if(parm instanceof PageBean){
    32. pageBean = (PageBean) parm;
    33. break;
    34. }
    35. }
    36. //判空分页
    37. if(pageBean!=null && pageBean.isPagination())
    38. PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
    39. //执行目标方法
    40. Object proceed = args.proceed();
    41. if(pageBean!=null && pageBean.isPagination()){
    42. PageInfo info = new PageInfo((List) proceed);
    43. pageBean.setTotal((int) info.getTotal());
    44. }
    45. return proceed;
    46. }
    47. }

    3.4 biz层

    上面的分页工具类写完之后,就可以正式的开始写后台代码了,增删改查应该还有模糊查询,所以我们要自己写一个模糊查询的方法

    定义一个接口

    然后写一个类实现接口

    1. package com.yinzi.Biz;
    2. import com.yinzi.mapper.BookMapper;
    3. import com.yinzi.model.Book;
    4. import com.yinzi.util.PageBean;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.List;
    8. /**
    9. * @author yinzi
    10. * @create 2023-09-07 14:32
    11. */
    12. @Service
    13. //将类交给spring处理
    14. public class BookBizImpl implements BookBiz {
    15. @Autowired //相当于set,get方法
    16. private BookMapper bm;
    17. @Override
    18. public int deleteByPrimaryKey(Integer bid) {
    19. return bm.deleteByPrimaryKey(bid);
    20. }
    21. @Override
    22. public int insert(Book record) {
    23. return bm.insert(record);
    24. }
    25. @Override
    26. public int insertSelective(Book record) {
    27. return bm.insertSelective(record);
    28. }
    29. @Override
    30. public Book selectByPrimaryKey(Integer bid) {
    31. return bm.selectByPrimaryKey(bid);
    32. }
    33. @Override
    34. public int updateByPrimaryKeySelective(Book record) {
    35. return bm.updateByPrimaryKeySelective(record);
    36. }
    37. @Override
    38. public int updateByPrimaryKey(Book record) {
    39. return bm.updateByPrimaryKey(record);
    40. }
    41. @Override
    42. public List selectList(Book book, PageBean pageBean) {
    43. return bm.selectList(book,pageBean);
    44. }
    45. }

    3.5 web层

    调用增删改查的方法,跳转页面

    1. package com.yinzi.web;
    2. import com.yinzi.Biz.BookBiz;
    3. import com.yinzi.model.Book;
    4. import com.yinzi.util.PageBean;
    5. import lombok.extern.slf4j.Slf4j;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Controller;
    8. import org.springframework.ui.Model;
    9. import org.springframework.web.bind.annotation.PathVariable;
    10. import org.springframework.web.bind.annotation.RequestMapping;
    11. import javax.servlet.http.HttpServletRequest;
    12. import java.util.List;
    13. /**
    14. * @author yinzi
    15. * @create 2023-09-07 14:38
    16. */
    17. @Slf4j
    18. @Controller //代替之前的自定义mvc的ActionSupport
    19. @RequestMapping("/book")
    20. public class BookController {
    21. @Autowired //代表setget的方法
    22. private BookBiz bookBiz;
    23. @RequestMapping("/list")
    24. public String list(Book book, HttpServletRequest request){
    25. //分页
    26. PageBean pageBean=new PageBean();
    27. pageBean.setRequest(request);
    28. //调用查询方法
    29. List<Book> books = bookBiz.selectList(book, pageBean);
    30. request.setAttribute("list",books);
    31. request.setAttribute("pageBean",pageBean);
    32. return "list";
    33. }
    34. //增加
    35. @RequestMapping("/add")
    36. public String add(Book book){
    37. //调用新增的方法
    38. int i = bookBiz.insertSelective(book);
    39. return "redirect:list";
    40. }
    41. //
    42. @RequestMapping("/del")
    43. public String del(Book book){
    44. //调用删除的方法
    45. int i = bookBiz.deleteByPrimaryKey(book.getBid());
    46. return "redirect:list";
    47. }
    48. //改Book
    49. @RequestMapping("/update")
    50. public String update(Book book){
    51. //调用修改的方法
    52. int i = bookBiz.updateByPrimaryKeySelective(book);
    53. return "redirect:list";
    54. }
    55. //修改回显数据
    56. @RequestMapping("/edit")
    57. public String edit(Book book, Model model) {
    58. //判断ID是否为空
    59. if (book != null && book.getBid() != null && book.getBid() != 0) {
    60. //不为空时,调用查询单个的方法
    61. Book book1 = bookBiz.selectByPrimaryKey(book.getBid());
    62. model.addAttribute("c",book1);
    63. }
    64. return "edit";
    65. }
    66. }

    后台的代码就完成了!!!


    四.前端

     4.1 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>
    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 }/book/list" method="post">
    36. <div class="form-group mb-2">
    37. <input type="text" class="form-control-plaintext" name="bname"
    38. placeholder="请输入书籍名称">
    39. </div>
    40. <button type="submit" class="btn btn-primary mb-2">查询</button>
    41. <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book/edit">新增</a>
    42. </form>
    43. <table class="table table-striped ">
    44. <thead>
    45. <tr>
    46. <th scope="col">书籍ID</th>
    47. <th scope="col">书籍名称</th>
    48. <th scope="col">书籍价格</th>
    49. <th scope="col">操作</th>
    50. </tr>
    51. </thead>
    52. <tbody>
    53. <c:forEach var="b" items="${list}">
    54. <tr>
    55. <td>${b.bid }</td>
    56. <td>${b.bname }</td>
    57. <td>${b.price }</td>
    58. <td>
    59. <a href="${pageContext.request.contextPath }/book/edit?bid=${b.bid}">修改</a>
    60. <a href="${pageContext.request.contextPath }/book/del?bid=${b.bid}">删除</a>
    61. </td>
    62. </tr>
    63. </c:forEach>
    64. </tbody>
    65. </table>
    66. <!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
    67. <z:page pageBean="${pageBean }"></z:page>
    68. ${pageBean }
    69. </body>
    70. </html>

    4.2 edit.jsp

    新增和修改都是用这个界面

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: 86131
    4. Date: 2023/9/7
    5. Time: 16:29
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. <html>
    10. <head>
    11. <title>Title</title>
    12. </head>
    13. <body>
    14. <form action="${pageContext.request.contextPath }/book/${empty c ? 'add' : 'update'}" method="post">
    15. 编号:<input type="text" name="bid" value="${c.bid }"><br>
    16. 名称:<input type="text" name="bname" value="${c.bname }"><br>
    17. 价格:<input type="text" name="price" value="${c.price }"><br>
    18. <input type="submit">
    19. </form>
    20. </body>
    21. </html>

    前台就比较简洁的搭建了一下

    最终效果:

    今天的分享就到这啦!!!

  • 相关阅读:
    ssm+vue的图书馆书库管理系统(有报告)。Javaee项目,ssm vue前后端分离项目。
    PowerCLi 一键批量部署OVA 到esxi 7
    YOLOv5-PTQ量化部署
    【数据结构】链表LinkedList
    【分享】集简云小程序识别身份证同步到表单流程搭建示例
    吴恩达机器学习课后作业
    Java实现排序算法
    AtCoder Beginner Contest 258 A~H 题解
    [go 反射] 函数
    HTTP与SOCKS5的区别对比
  • 原文地址:https://blog.csdn.net/YZZdear/article/details/132733969