• SpringMVC实现增删改查(CRUD)--从头到尾全面详细讲解


    一,实现CRUD前准备工作

    1.1 pom.xml依赖的配置

    创建Model项目并导入相关pom.xml依赖

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

    1.2 generatorConfig.xml

    此文件是实现模型代码层的配置,在下面table标签中定义数据库的表与生成的表名

    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_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
    7. <context id="infoGuardian">
    8. <commentGenerator>
    9. <property name="suppressAllComments" value="true"/>
    10. <property name="suppressDate" value="true"/>
    11. commentGenerator>
    12. <jdbcConnection driverClass="${jdbc.driver}"
    13. connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
    14. <javaTypeResolver>
    15. <property name="forceBigDecimals" value="false"/>
    16. javaTypeResolver>
    17. <javaModelGenerator targetPackage="com.Bingzy.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.Bingzy.mapper"
    25. targetProject="src/main/java">
    26. <property name="enableSubPackages" value="false"/>
    27. sqlMapGenerator>
    28. <javaClientGenerator targetPackage="com.Bingzy.mapper"
    29. targetProject="src/main/java" type="XMLMAPPER">
    30. <property name="enableSubPackages" value="false"/>
    31. javaClientGenerator>
    32. <table schema="" tableName="t_mvc_book" domainObjectName="Tbook"
    33. enableCountByExample="false" enableDeleteByExample="false"
    34. enableSelectByExample="false" enableUpdateByExample="false">
    35. table>
    36. context>
    37. generatorConfiguration>

    1.3 jdbc.properties

    建立数据库连接

    25256c994dbf420f83b6c82ca544f87e.png

    1.4 log4j2.xml:

    日志文件

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

    1.5 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="spring-mybatis.xml">import>
    6. beans>

    1.6 spring-mvc.xml

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc"
    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. <context:component-scan base-package="com.Bingzy"/>
    9. <mvc:annotation-driven />
    10. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    11. <property name="viewClass"
    12. value="org.springframework.web.servlet.view.JstlView">property>
    13. <property name="prefix" value="/WEB-INF/jsp/"/>
    14. <property name="suffix" value=".jsp"/>
    15. bean>
    16. <mvc:resources location="/static/" mapping="/static/**"/>
    17. beans>

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

    1.8 生成模型层代码

    d78fc1de0d4b422f8f1fb5c720c666d1.png

    生成类样式:

    622c33658a6043f294fc986b07b9b249.png

    1.9 导入相关的工具类

    1b11837d6251419f9d3d95695be2487d.png

    创建util包并添加Page Bean类

    PageBean类:

    专门处理分页

    1. package com.Bingzy.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 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 getMap() {
    40. return map;
    41. }
    42. public void setMap(Map 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. }

    创建一个aspect包并添加pageAspect类:

    该是切面类专门来做分页

    1. package com.Bingzy.aspect;
    2. import com.Bingzy.util.PageBean;
    3. import com.github.pagehelper.PageHelper;
    4. import com.github.pagehelper.PageInfo;
    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. * @Name BingBing
    12. * @company zking cy
    13. * @create 2023-08-25-18:37
    14. */
    15. @Aspect//代表当前类为切面类
    16. @Component//代表当前类交给Spring进行管理
    17. public class PageAspect {
    18. @Around("execution(* *..*Biz.*Page(..))")
    19. public Object invoke(ProceedingJoinPoint args) throws Throwable {
    20. PageBean pageBean =null;
    21. //获取目标方法中的所有参数
    22. Object[] arg = args.getArgs();
    23. for (Object param : arg){
    24. if(param instanceof PageBean){
    25. pageBean= (PageBean) param;
    26. break;
    27. }
    28. }
    29. if (pageBean != null && pageBean.isPagination())
    30. PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
    31. //执行目标方法
    32. Object lst= args.proceed();
    33. if (pageBean != null && pageBean.isPagination()) {
    34. PageInfo info = new PageInfo ((List) lst);
    35. pageBean.setTotal((int) info.getTotal());
    36. }
    37. return lst;
    38. }
    39. }

    二、controller层代码编写

    创建一个web包并定义controller类

    1. package com.Bingzy.web;
    2. import com.Bingzy.Biz.TbookBiz;
    3. import com.Bingzy.model.Tbook;
    4. import com.Bingzy.util.PageBean;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Controller;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import javax.servlet.http.HttpServletRequest;
    9. import java.util.List;
    10. /**
    11. * @Name BingBing
    12. * @company zking cy
    13. * @create 2023-09-08-19:51
    14. */
    15. @Controller
    16. @RequestMapping("/book")
    17. public class TbookController {
    18. @Autowired
    19. private TbookBiz tbookBiz;
    20. @RequestMapping("/list")
    21. //查询
    22. public String list(Tbook tbook, HttpServletRequest request){
    23. PageBean pageBean =new PageBean();
    24. pageBean.setRequest(request);
    25. List tbookList = tbookBiz.listPager(tbook, pageBean);
    26. request.setAttribute("lst",tbookList);
    27. request.setAttribute("pageBean",pageBean);
    28. return "book/list";
    29. }
    30. //增加
    31. // 增
    32. @RequestMapping("/add")
    33. public String add(Tbook tbook){
    34. tbookBiz.insertSelective(tbook);
    35. return "redirect:list";
    36. }
    37. // 删
    38. @RequestMapping("/del")
    39. public String del(Tbook tbook){
    40. tbookBiz.deleteByPrimaryKey(tbook.getBid());
    41. return "redirect:list";
    42. }
    43. // 改
    44. @RequestMapping("/edit")
    45. public String edit(Tbook tbook){
    46. tbookBiz.updateByPrimaryKeySelective(tbook);
    47. return "redirect:list";
    48. }
    49. // 模糊分页查询
    50. @RequestMapping("/PreSave")
    51. public String PreSave(Tbook tbook, HttpServletRequest request){
    52. if(tbook!=null && tbook.getBid()!=null){
    53. Tbook s = tbookBiz.selectByPrimaryKey(tbook.getBid());
    54. request.setAttribute("b",s);
    55. }
    56. return "book/edit";
    57. }
    58. }

    三,分页代码与前端代码

    3.1 分页代码

    3.1.1 PageTag

    1. package com.Bingzy.tag;
    2. import com.Bingzy.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 paramMap = pageBean.getMap();
    37. if(paramMap != null && paramMap.size() > 0) {
    38. Set> entrySet = paramMap.entrySet();
    39. for (Entry 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.1.2 zking.tld

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

    3.2 前端代码

    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. 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 }/book/list" method="post">
    36. <div class="form-group mb-2">
    37. <input type="text" class="form-control-plaintext" name="bname"
    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 }/book/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. tr>
    51. thead>
    52. <tbody>
    53. <c:forEach var="b" items="${lst }">
    54. <tr>
    55. <td>${b.bid }td>
    56. <td>${b.bname }td>
    57. <td>
    58. <a href="${pageContext.request.contextPath }/book/PreSave?bid=${b.bid}">修改a>
    59. <a href="${pageContext.request.contextPath }/book/del?bid=${b.bid}">删除a>
    60. td>
    61. tr>
    62. c:forEach>
    63. tbody>
    64. table>
    65. <z:page pageBean="${pageBean }">z:page>
    66. ${pageBean }
    67. ${slist}
    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. <center>
    11. 编辑界面
    12. <form action="${pageContext.request.contextPath }/${empty b ? 'book/add' : 'book/edit'}" method="post">
    13. 书籍id:<input type="text" name="bid" value="${b.bid }"><br>
    14. 书籍名称:<input type="text" name="bname" value="${b.bname }"><br>
    15. <input type="submit">
    16. form>
    17. center>
    18. body>
    19. html>

    四,案例测试(CRUD)

    25533d9f8a8b4ada96ae7e8020416253.gif

  • 相关阅读:
    参数查阅~~~9.18
    Mybatis (2)
    全栈开发笔记1:首个项目的收获
    HTML制作一个介绍自己家乡的网站——贵阳,排版整洁,内容丰富,主题鲜明
    【算法基础】栈和队列及常见变种与使用,双栈、动态栈、栈的迭代器,双端队列、优先队列、并发队列、延迟队列的使用
    界面组件DevExpress WinForms v23.1 - 增强的图表、甘特图功能
    Android WebRTC 入门教程(二) -- 模拟p2p本地视频传输
    【漏洞复现】Apache_Shiro_1.2.4_反序列化漏洞(CVE-2016-4437)
    binfmt_misc
    火山引擎 RTC 自研音频编码器 NICO 实践之路
  • 原文地址:https://blog.csdn.net/m0_73192864/article/details/132766018