• SpringMVC:从入门到精通,7篇系列篇带你全面掌握--三.使用SpringMVC完成增删改查


    🥳🥳Welcome Huihui's Code World ! !🥳🥳

    接下来看看由辉辉所写的关于SpringMVC的相关操作吧

    目录

    🥳🥳Welcome Huihui's Code World ! !🥳🥳

    效果演示

    一.导入项目的相关依赖

    二.添加框架的配置文件

    generatorConfig.xml

    jdbc.properties

    log4j2.xml

    Spring-context.xml

    Spring-mvc.xml

    SpringMVCzy.xml

    三.工具类

    PagBean

    PageTag

    StringUtils

    四.逆向生成代码

    1.发布项目

    2.生成代码

    五.编写后台代码

    biz

    web

    六.前台代码编写

    index.jsp

    edit.jsp


    效果演示

    一.导入项目的相关依赖

    将项目需要用到的插件以及依赖导入到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>WHzyssmartifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. <packaging>warpackaging>
    9. <name>Spring-Mybatis 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. <resources>
    260. <resource>
    261. <directory>src/main/javadirectory>
    262. <includes>
    263. <include>**/*.xmlinclude>
    264. includes>
    265. resource>
    266. <resource>
    267. <directory>src/main/resourcesdirectory>
    268. <includes>
    269. <include>*.propertiesinclude>
    270. <include>*.xmlinclude>
    271. includes>
    272. resource>
    273. resources>
    274. <plugins>
    275. <plugin>
    276. <groupId>org.apache.maven.pluginsgroupId>
    277. <artifactId>maven-compiler-pluginartifactId>
    278. <version>${maven.compiler.plugin.version}version>
    279. <configuration>
    280. <source>${maven.compiler.source}source>
    281. <target>${maven.compiler.target}target>
    282. <encoding>${project.build.sourceEncoding}encoding>
    283. configuration>
    284. plugin>
    285. <plugin>
    286. <groupId>org.mybatis.generatorgroupId>
    287. <artifactId>mybatis-generator-maven-pluginartifactId>
    288. <version>1.3.2version>
    289. <dependencies>
    290. <dependency>
    291. <groupId>mysqlgroupId>
    292. <artifactId>mysql-connector-javaartifactId>
    293. <version>${mysql.version}version>
    294. dependency>
    295. dependencies>
    296. <configuration>
    297. <overwrite>trueoverwrite>
    298. configuration>
    299. plugin>
    300. <plugin>
    301. <artifactId>maven-clean-pluginartifactId>
    302. <version>3.1.0version>
    303. plugin>
    304. <plugin>
    305. <artifactId>maven-resources-pluginartifactId>
    306. <version>3.0.2version>
    307. plugin>
    308. <plugin>
    309. <artifactId>maven-compiler-pluginartifactId>
    310. <version>3.8.0version>
    311. plugin>
    312. <plugin>
    313. <artifactId>maven-surefire-pluginartifactId>
    314. <version>2.22.1version>
    315. plugin>
    316. <plugin>
    317. <artifactId>maven-war-pluginartifactId>
    318. <version>3.2.2version>
    319. plugin>
    320. <plugin>
    321. <artifactId>maven-install-pluginartifactId>
    322. <version>2.5.2version>
    323. plugin>
    324. <plugin>
    325. <artifactId>maven-deploy-pluginartifactId>
    326. <version>2.8.2version>
    327. plugin>
    328. plugins>
    329. build>
    330. project>

    二.添加框架的配置文件

    generatorConfig.xml

    这个文件用于生成Java代码。它包含了数据库连接信息、Java类型转换设置、JavaBean生成设置、SQL映射文件生成设置以及生成的表的结构等信息。通过这个配置文件,MyBatis Generator可以根据这些配置信息自动生成相应的Java实体类、Mapper接口以及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:\tools\apache-maven-3.5.0-bin\mvn_localRepositor\mysql\mysql-connector-java\5.1.44\\mysql-connector-java-5.1.44.jar"/>
    7. <context id="infoGuardian">
    8. <commentGenerator>
    9. <property name="suppressAllComments" value="true"/>
    10. <property name="suppressDate" value="true"/>
    11. commentGenerator>
    12. <jdbcConnection driverClass="${jdbc.driver}"
    13. connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
    14. <javaTypeResolver>
    15. <property name="forceBigDecimals" value="false"/>
    16. javaTypeResolver>
    17. <javaModelGenerator targetPackage="com.wh.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.wh.mapper"
    25. targetProject="src/main/java">
    26. <property name="enableSubPackages" value="false"/>
    27. sqlMapGenerator>
    28. <javaClientGenerator targetPackage="com.wh.mapper"
    29. targetProject="src/main/java" type="XMLMAPPER">
    30. <property name="enableSubPackages" value="false"/>
    31. javaClientGenerator>
    32. <table schema="" tableName="t_mvc_cat" domainObjectName="Cat"
    33. enableCountByExample="false" enableDeleteByExample="false"
    34. enableSelectByExample="false" enableUpdateByExample="false">
    35. table>
    36. context>
    37. generatorConfiguration>

    jdbc.properties

    这个配置文件是用来配置Java应用程序与MySQL数据库的连接信息的

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
    3. jdbc.username=root
    4. jdbc.password=123456

    log4j2.xml

    这个配置文件是用于配置Log4j2的日志输出规则。Log4j2是一个用于Java应用程序的日志框架,它提供了灵活的日志记录功能

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

    Spring-context.xml

    这是一个Spring框架的配置文件,用于定义和管理Spring容器中的Bean。它使用XML格式来描述Bean的配置信息和依赖关系。通过这个配置文件,Spring框架可以自动扫描并加载应用程序中的Bean定义,并根据这些配置信息创建和管理Bean的实例。这样可以实现依赖注入、面向切面编程等特性

    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:SpringMVCzy.xml">import>
    6. beans>

    Spring-mvc.xml

    这个配置文件是Spring MVC框架的XML配置文件,用于配置Spring MVC的各种组件和属性,其中做了这些操作:

    1. 扫描com.wh包及其子包下的控制器类,将它们注册为Spring MVC的控制器
    2. 开启注解驱动的Spring MVC功能,这意味着可以使用基于注解的方式进行请求映射、数据绑定等操作
    3. 配置了一个视图解析器(ViewResolver),用于将控制器返回的逻辑视图名解析为实际的视图对象。这里使用了JSP视图技术,并指定了JSP文件存放在/WEB-INF/jsp/目录下
    4. 注释掉了一些资源处理器的配置,这些配置可以用于处理静态资源(如图片、样式表、JavaScript文件等)的请求
    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc"
    6. xmlns:aop="http://www.springframework.org/schema/aop"
    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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    9. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    10. <context:component-scan base-package="com.wh"/>
    11. <mvc:annotation-driven />
    12. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    13. <property name="viewClass"
    14. value="org.springframework.web.servlet.view.JstlView">property>
    15. <property name="prefix" value="/WEB-INF/jsp/"/>
    16. <property name="suffix" value=".jsp"/>
    17. bean>
    18. <mvc:resources location="/common/" mapping="/jsp/**"/>
    19. <aop:aspectj-autoproxy/>
    20. beans>

    SpringMVCzy.xml

    这是一个Spring框架的XML配置文件,用于配置Spring应用程序的各种组件和属性。其中做了这些操作:

    1. 注解式开发:通过启用注解驱动的配置,允许使用注解来定义和管理Bean
    2. 组件扫描:通过标签指定要扫描的包路径,以自动发现并注册Bean
    3. 属性占位符:通过标签指定属性文件的位置,用于从外部属性文件中加载配置信息
    4. 数据源配置:通过标签配置数据库连接池,包括驱动程序类名、URL、用户名、密码等属性
    5. MyBatis整合:通过配置MyBatis的SqlSessionFactory和Mapper接口扫描器,实现自动扫描和注册Mapper接口
    6. 事务管理:通过配置事务管理器,将DataSource与事务管理器关联起来
    7. AOP支持:通过启用AspectJ自动代理,支持面向切面编程
    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.wh"/>
    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/wh/**/mapper/*.xml"/>
    25. <property name="typeAliasesPackage" value="com/wh/**/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/wh/**/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>

    web.xml

    1. "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 Applicationdisplay-name>
    7. <context-param>
    8. <param-name>contextConfigLocationparam-name>
    9. <param-value>classpath:Spring-context.xmlparam-value>
    10. context-param>
    11. <listener>
    12. <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    13. listener>
    14. <filter>
    15. <filter-name>encodingFilterfilter-name>
    16. <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    17. <async-supported>trueasync-supported>
    18. <init-param>
    19. <param-name>encodingparam-name>
    20. <param-value>UTF-8param-value>
    21. init-param>
    22. filter>
    23. <filter-mapping>
    24. <filter-name>encodingFilterfilter-name>
    25. <url-pattern>/*url-pattern>
    26. filter-mapping>
    27. <servlet>
    28. <servlet-name>SpringMVCservlet-name>
    29. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    30. <init-param>
    31. <param-name>contextConfigLocationparam-name>
    32. <param-value>classpath:Spring-mvc.xmlparam-value>
    33. init-param>
    34. <load-on-startup>1load-on-startup>
    35. <async-supported>trueasync-supported>
    36. servlet>
    37. <servlet-mapping>
    38. <servlet-name>SpringMVCservlet-name>
    39. <url-pattern>/url-pattern>
    40. servlet-mapping>
    41. web-app>

    三.工具类

    PagBean

    1. package com.wh.util;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. import javax.servlet.http.HttpServletRequest;
    5. /**
    6. * 分页工具类
    7. *
    8. */
    9. public class PageBean {
    10. private int page = 1;// 页码
    11. private int rows = 10;// 页大小
    12. private int total = 0;// 总记录数
    13. private boolean pagination = true;// 是否分页
    14. private String url; //保存上一次请求的URL
    15. private Map<String,String[]> paramMap = new HashMap<>();// 保存上一次请求的参数
    16. /**
    17. * 初始化pagebean的,保存上一次请求的重要参数
    18. * @param req
    19. */
    20. public void setRequest(HttpServletRequest req) {
    21. // 1.1 需要保存上一次请求的URL
    22. this.setUrl(req.getRequestURL().toString());
    23. // 1.2 需要保存上一次请求的参数 bname、price
    24. this.setParamMap(req.getParameterMap());
    25. // 1.3 需要保存上一次请求的分页设置 pagination
    26. this.setPagination(req.getParameter("pagination"));
    27. // 1.4 需要保存上一次请求的展示条目数
    28. this.setRows(req.getParameter("rows"));
    29. // 1.5 初始化请求的页码 page
    30. this.setPage(req.getParameter("page"));
    31. }
    32. public void setPage(String page) {
    33. if(StringUtils.isNotBlank(page))
    34. this.setPage(Integer.valueOf(page));
    35. }
    36. public void setRows(String rows) {
    37. if(StringUtils.isNotBlank(rows))
    38. this.setRows(Integer.valueOf(rows));
    39. }
    40. public void setPagination(String pagination) {
    41. // 只有在前台jsp填写了pagination=false,才代表不分页
    42. if(StringUtils.isNotBlank(pagination))
    43. this.setPagination(!"false".equals(pagination));
    44. }
    45. public String getUrl() {
    46. return url;
    47. }
    48. public void setUrl(String url) {
    49. this.url = url;
    50. }
    51. public Map<String, String[]> getParamMap() {
    52. return paramMap;
    53. }
    54. public void setParamMap(Map<String, String[]> paramMap) {
    55. this.paramMap = paramMap;
    56. }
    57. public PageBean() {
    58. super();
    59. }
    60. public int getPage() {
    61. return page;
    62. }
    63. public void setPage(int page) {
    64. this.page = page;
    65. }
    66. public int getRows() {
    67. return rows;
    68. }
    69. public void setRows(int rows) {
    70. this.rows = rows;
    71. }
    72. public int getTotal() {
    73. return total;
    74. }
    75. public void setTotal(int total) {
    76. this.total = total;
    77. }
    78. public void setTotal(String total) {
    79. this.total = Integer.parseInt(total);
    80. }
    81. public boolean isPagination() {
    82. return pagination;
    83. }
    84. public void setPagination(boolean pagination) {
    85. this.pagination = pagination;
    86. }
    87. /**
    88. * 获得起始记录的下标
    89. *
    90. * @return
    91. */
    92. public int getStartIndex() {
    93. return (this.page - 1) * this.rows;
    94. }
    95. /**
    96. * 最大页
    97. * @return
    98. */
    99. public int maxPage() {
    100. // total % rows == 0 ? total / rows : total / rows +1
    101. return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
    102. }
    103. /**
    104. * 下一页
    105. * @return
    106. */
    107. public int nextPage() {
    108. // 如果当前页小于最大页,那就下一页为当前页+1;如果不小于,说明当前页就是最大页,那就无需+1
    109. return this.page < this.maxPage() ? this.page + 1 : this.page;
    110. }
    111. /**
    112. * 上一页
    113. * @return
    114. */
    115. public int previousPage() {
    116. return this.page > 1 ? this.page - 1 : this.page;
    117. }
    118. @Override
    119. public String toString() {
    120. return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
    121. }
    122. }

    PageTag

    1. package com.wh.tag;
    2. import com.wh.util.PageBean;
    3. import javax.servlet.jsp.JspException;
    4. import javax.servlet.jsp.JspWriter;
    5. import javax.servlet.jsp.tagext.BodyTagSupport;
    6. import java.io.IOException;
    7. import java.util.Map;
    8. import java.util.Map.Entry;
    9. import java.util.Set;
    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.getParamMap();
    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();
  • }
  • }
  • StringUtils

    1. package com.wh.util;
    2. public class StringUtils {
    3. // 私有的构造方法,保护此类不能在外部实例化
    4. private StringUtils() {
    5. }
    6. /**
    7. * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
    8. *
    9. * @param s
    10. * @return
    11. */
    12. public static boolean isBlank(String s) {
    13. boolean b = false;
    14. if (null == s || s.trim().equals("")) {
    15. b = true;
    16. }
    17. return b;
    18. }
    19. /**
    20. * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
    21. *
    22. * @param s
    23. * @return
    24. */
    25. public static boolean isNotBlank(String s) {
    26. return !isBlank(s);
    27. }
    28. }

    切面类Aspect

    1. package com.wh.aop;
    2. import com.github.pagehelper.PageHelper;
    3. import com.github.pagehelper.PageInfo;
    4. import com.wh.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 王辉
    12. * @site www.shihuihuila.com
    13. * @create 2023-08-25 21:27
    14. */
    15. @Aspect
    16. //代表当前类是切面类
    17. @Component
    18. //代表这个是交给Spring管理
    19. public class AspectPager {
    20. @Around("execution(* *..*Biz.*Pager(..))")
    21. public Object invoke(ProceedingJoinPoint args) throws Throwable {
    22. Object[] params = args.getArgs();
    23. PageBean pageBean = null;
    24. for (Object param : params) {
    25. if (param instanceof PageBean) {
    26. pageBean = (PageBean) param;
    27. break;
    28. }
    29. }
    30. if (pageBean != null && pageBean.isPagination())
    31. PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
    32. Object list = args.proceed(params);
    33. if (null != pageBean && pageBean.isPagination()) {
    34. PageInfo pageInfo = new PageInfo((List) list);
    35. pageBean.setTotal(pageInfo.getTotal() + "");
    36. }
    37. return list;
    38. }
    39. }

    四.逆向生成代码

    1.发布项目

    2.生成代码

    五.编写后台代码

    biz

    1. package com.wh.biz;
    2. import com.wh.model.Cat;
    3. import com.wh.util.PageBean;
    4. import java.util.List;
    5. public interface CatBiz {
    6. int deleteByPrimaryKey(Integer cid);
    7. int insert(Cat record);
    8. int insertSelective(Cat record);
    9. List selectByPrimaryKey(Integer cid);
    10. List selectLikePager(Cat cat,PageBean pageBean);
    11. int updateByPrimaryKeySelective(Cat record);
    12. int updateByPrimaryKey(Cat record);
    13. }
    1. package com.wh.biz;
    2. import com.wh.mapper.CatMapper;
    3. import com.wh.model.Cat;
    4. import com.wh.util.PageBean;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.List;
    8. /**
    9. * @author 王辉
    10. * @site www.shihuihuila.com
    11. * @create 2023-09-08 18:05
    12. */
    13. @Service
    14. public class CatBizImpl implements CatBiz {
    15. @Autowired
    16. private CatMapper catBiz;
    17. @Override
    18. public int deleteByPrimaryKey(Integer cid) {
    19. return catBiz.deleteByPrimaryKey(cid);
    20. }
    21. @Override
    22. public int insert(Cat record) {
    23. return catBiz.insert(record);
    24. }
    25. @Override
    26. public int insertSelective(Cat record) {
    27. return catBiz.insertSelective(record);
    28. }
    29. @Override
    30. public List selectByPrimaryKey(Integer cid) {
    31. return catBiz.selectByPrimaryKey(cid);
    32. }
    33. @Override
    34. public List selectLikePager(Cat cat, PageBean pageBean) {
    35. return catBiz.selectLikePager(cat);
    36. }
    37. @Override
    38. public int updateByPrimaryKeySelective(Cat record) {
    39. return catBiz.updateByPrimaryKeySelective(record
    40. );
    41. }
    42. @Override
    43. public int updateByPrimaryKey(Cat record) {
    44. return catBiz.updateByPrimaryKey(record);
    45. }
    46. }

    web

    1. package com.wh.web;
    2. import com.wh.biz.CatBiz;
    3. import com.wh.model.Cat;
    4. import com.wh.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.RequestMapping;
    10. import javax.servlet.http.HttpServletRequest;
    11. import java.util.List;
    12. /**
    13. * @author 王辉
    14. * @site www.shihuihuila.com
    15. * @create 2023-09-08 18:08
    16. */
    17. @Controller
    18. @RequestMapping("/smvc3")
    19. @Slf4j
    20. public class CatController {
    21. @Autowired
    22. private CatBiz catBiz;
    23. //增
    24. @RequestMapping("/add")
    25. public String add(Cat cat){
    26. catBiz.insertSelective(cat);
    27. return "redirect:list";
    28. }
    29. // 删
    30. @RequestMapping("/del")
    31. public String del(Cat cat){
    32. catBiz.deleteByPrimaryKey(cat.getCid());
    33. return "redirect:list";
    34. }
    35. // 改
    36. @RequestMapping("/upd")
    37. public String upd(Cat cat){
    38. catBiz.updateByPrimaryKeySelective(cat);
    39. return "redirect:list";
    40. }
    41. // 查
    42. @RequestMapping("/list")
    43. public String list(Cat cat, HttpServletRequest request){
    44. PageBean pageBean=new PageBean();
    45. List cats = catBiz.selectLikePager(cat, pageBean);
    46. request.setAttribute("list",cats);
    47. request.setAttribute("pageBean",pageBean);
    48. return "index";
    49. }
    50. //数据回显
    51. @RequestMapping("/preSave")
    52. public String preSave(Cat cat, Model model){
    53. if(cat!=null && cat.getCid()!=null){
    54. List cats = catBiz.selectByPrimaryKey(cat.getCid());
    55. model.addAttribute("c",cats.get(0));
    56. }
    57. return "edit";
    58. }
    59. }

    六.前台代码编写

    index.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. 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 }/smvc3/list" method="post">
    36. <div class="form-group mb-2">
    37. <input type="text" class="form-control-plaintext" name="cname"
    38. placeholder="请输入书籍名称">
    39. <input name="pagination" value="false" type="hidden">
    40. div>
    41. <button type="submit" class="btn btn-primary mb-2">查询button>
    42. <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/smvc3/preSave">新增a>
    43. form>
    44. <table class="table table-striped ">
    45. <thead>
    46. <tr>
    47. <th scope="col">猫咪IDth>
    48. <th scope="col">猫咪名字th>
    49. <th scope="col">猫咪年龄th>
    50. <th scope="col">操作th>
    51. tr>
    52. thead>
    53. <tbody>
    54. <c:forEach var="b" items="${list }">
    55. <tr>
    56. <td>${b.cid }td>
    57. <td>${b.cname }td>
    58. <td>${b.age }td>
    59. <td>
    60. <a href="${pageContext.request.contextPath }/smvc3/preSave?cid=${b.cid}">修改a>
    61. <a href="${pageContext.request.contextPath }/smvc3/del?cid=${b.cid}">删除a>
    62. td>
    63. tr>
    64. c:forEach>
    65. tbody>
    66. table>
    67. <z:page pageBean="${pageBean }">z:page>
    68. body>
    69. html>

    edit.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>编辑界面title>
    8. head>
    9. <body>
    10. <form action="${pageContext.request.contextPath }/${empty c ? 'smvc3/add' : 'smvc3/upd'}" method="post">
    11. <c:forEach var="b" items="${c }">
    12. 猫咪id:<input type="text" name="cid" value="${b.cid }"><br>
    13. 猫咪姓名:<input type="text" name="cname" value="${b.cname }"><br>
    14. 猫咪年龄:<input type="text" name="age" value="${b.age }"><br>
    15. <input type="submit">
    16. c:forEach>
    17. form>
    18. body>
    19. html>

      好啦,今天的分享就到这了,希望能够帮到你呢!😊😊  

  • 相关阅读:
    TSINGSEE视频AI智能分析技术:水泥厂安全生产智能监管解决方案
    最新代码重构:面向单元测试
    MySql的索引与算法-B+树索引
    【Web】Java反序列化之CC6--HashMap版
    力扣100097. 合法分组的最少组数(哈希+贪心)
    GStreamer 进阶
    多人联机之研究
    Linux编程——多任务间通信和同步
    英语多语言翻译软件-调用多平台免费翻译额度
    刷题记录:牛客NC19115选择颜色
  • 原文地址:https://blog.csdn.net/m0_74315688/article/details/132763187