• SprimgMVC增删改查·


    1.项目创建

    在IDEA创建一个maven项目

    2.项目依赖

    pom.xml

    1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    3. <modelVersion>4.0.0</modelVersion>
    4. <groupId>org.example</groupId>
    5. <artifactId>lzxzyssm</artifactId>
    6. <packaging>war</packaging>
    7. <version>1.0-SNAPSHOT</version>
    8. <name>lzxzyssmMaven Webapp</name>
    9. <url>http://maven.apache.org</url>
    10. <properties>
    11. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    12. <maven.compiler.source>1.8</maven.compiler.source>
    13. <maven.compiler.target>1.8</maven.compiler.target>
    14. <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
    15. <!--添加jar包依赖-->
    16. <!--1.spring 5.0.2.RELEASE相关-->
    17. <spring.version>5.0.2.RELEASE</spring.version>
    18. <!--2.mybatis相关-->
    19. <mybatis.version>3.4.5</mybatis.version>
    20. <!--mysql-->
    21. <mysql.version>5.1.44</mysql.version>
    22. <!--pagehelper分页jar依赖-->
    23. <pagehelper.version>5.1.2</pagehelper.version>
    24. <!--mybatis与spring集成jar依赖-->
    25. <mybatis.spring.version>1.3.1</mybatis.spring.version>
    26. <!--3.dbcp2连接池相关 druid-->
    27. <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
    28. <commons.pool2.version>2.4.3</commons.pool2.version>
    29. <!--4.log日志相关-->
    30. <log4j2.version>2.9.1</log4j2.version>
    31. <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
    32. <slf4j.version>1.7.13</slf4j.version>
    33. <!--5.其他-->
    34. <junit.version>4.12</junit.version>
    35. <servlet.version>4.0.0</servlet.version>
    36. <lombok.version>1.18.2</lombok.version>
    37. <mybatis.ehcache.version>1.1.0</mybatis.ehcache.version>
    38. <ehcache.version>2.10.0</ehcache.version>
    39. <redis.version>2.9.0</redis.version>
    40. <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
    41. <jackson.version>2.9.3</jackson.version>
    42. <jstl.version>1.2</jstl.version>
    43. <standard.version>1.1.2</standard.version>
    44. <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
    45. <commons-fileupload.version>1.3.3</commons-fileupload.version>
    46. <hibernate-validator.version>5.0.2.Final</hibernate-validator.version>
    47. <shiro.version>1.3.2</shiro.version>
    48. </properties>
    49. <dependencies>
    50. <!--1.spring相关-->
    51. <dependency>
    52. <groupId>org.springframework</groupId>
    53. <artifactId>spring-core</artifactId>
    54. <version>${spring.version}</version>
    55. </dependency>
    56. <dependency>
    57. <groupId>org.springframework</groupId>
    58. <artifactId>spring-beans</artifactId>
    59. <version>${spring.version}</version>
    60. </dependency>
    61. <dependency>
    62. <groupId>org.springframework</groupId>
    63. <artifactId>spring-context</artifactId>
    64. <version>${spring.version}</version>
    65. </dependency>
    66. <dependency>
    67. <groupId>org.springframework</groupId>
    68. <artifactId>spring-orm</artifactId>
    69. <version>${spring.version}</version>
    70. </dependency>
    71. <dependency>
    72. <groupId>org.springframework</groupId>
    73. <artifactId>spring-tx</artifactId>
    74. <version>${spring.version}</version>
    75. </dependency>
    76. <dependency>
    77. <groupId>org.springframework</groupId>
    78. <artifactId>spring-aspects</artifactId>
    79. <version>${spring.version}</version>
    80. </dependency>
    81. <dependency>
    82. <groupId>org.springframework</groupId>
    83. <artifactId>spring-web</artifactId>
    84. <version>${spring.version}</version>
    85. </dependency>
    86. <dependency>
    87. <groupId>org.springframework</groupId>
    88. <artifactId>spring-test</artifactId>
    89. <version>${spring.version}</version>
    90. </dependency>
    91. <!--2.mybatis相关-->
    92. <dependency>
    93. <groupId>org.mybatis</groupId>
    94. <artifactId>mybatis</artifactId>
    95. <version>${mybatis.version}</version>
    96. </dependency>
    97. <!--mysql-->
    98. <dependency>
    99. <groupId>mysql</groupId>
    100. <artifactId>mysql-connector-java</artifactId>
    101. <version>${mysql.version}</version>
    102. </dependency>
    103. <!--pagehelper分页插件jar包依赖-->
    104. <dependency>
    105. <groupId>com.github.pagehelper</groupId>
    106. <artifactId>pagehelper</artifactId>
    107. <version>${pagehelper.version}</version>
    108. </dependency>
    109. <!--mybatis与spring集成jar包依赖-->
    110. <dependency>
    111. <groupId>org.mybatis</groupId>
    112. <artifactId>mybatis-spring</artifactId>
    113. <version>${mybatis.spring.version}</version>
    114. </dependency>
    115. <dependency>
    116. <groupId>org.springframework</groupId>
    117. <artifactId>spring-context-support</artifactId>
    118. <version>${spring.version}</version>
    119. </dependency>
    120. <!--mybatis与ehcache整合-->
    121. <dependency>
    122. <groupId>org.mybatis.caches</groupId>
    123. <artifactId>mybatis-ehcache</artifactId>
    124. <version>${mybatis.ehcache.version}</version>
    125. </dependency>
    126. <!--ehcache依赖-->
    127. <dependency>
    128. <groupId>net.sf.ehcache</groupId>
    129. <artifactId>ehcache</artifactId>
    130. <version>${ehcache.version}</version>
    131. </dependency>
    132. <dependency>
    133. <groupId>redis.clients</groupId>
    134. <artifactId>jedis</artifactId>
    135. <version>${redis.version}</version>
    136. </dependency>
    137. <dependency>
    138. <groupId>org.springframework.data</groupId>
    139. <artifactId>spring-data-redis</artifactId>
    140. <version>${redis.spring.version}</version>
    141. </dependency>
    142. <dependency>
    143. <groupId>com.fasterxml.jackson.core</groupId>
    144. <artifactId>jackson-databind</artifactId>
    145. <version>${jackson.version}</version>
    146. </dependency>
    147. <dependency>
    148. <groupId>com.fasterxml.jackson.core</groupId>
    149. <artifactId>jackson-core</artifactId>
    150. <version>${jackson.version}</version>
    151. </dependency>
    152. <dependency>
    153. <groupId>com.fasterxml.jackson.core</groupId>
    154. <artifactId>jackson-annotations</artifactId>
    155. <version>${jackson.version}</version>
    156. </dependency>
    157. <!--3.dbcp2连接池相关-->
    158. <dependency>
    159. <groupId>org.apache.commons</groupId>
    160. <artifactId>commons-dbcp2</artifactId>
    161. <version>${commons.dbcp2.version}</version>
    162. <exclusions>
    163. <exclusion>
    164. <artifactId>commons-pool2</artifactId>
    165. <groupId>org.apache.commons</groupId>
    166. </exclusion>
    167. </exclusions>
    168. </dependency>
    169. <dependency>
    170. <groupId>org.apache.commons</groupId>
    171. <artifactId>commons-pool2</artifactId>
    172. <version>${commons.pool2.version}</version>
    173. </dependency>
    174. <!--springmvc依赖-->
    175. <dependency>
    176. <groupId>org.springframework</groupId>
    177. <artifactId>spring-webmvc</artifactId>
    178. <version>${spring.version}</version>
    179. </dependency>
    180. <!--4.log日志相关依赖-->
    181. <!-- log4j2日志相关依赖 -->
    182. <!-- log配置:Log4j2 + Slf4j -->
    183. <!-- slf4j核心包-->
    184. <dependency>
    185. <groupId>org.slf4j</groupId>
    186. <artifactId>slf4j-api</artifactId>
    187. <version>${slf4j.version}</version>
    188. </dependency>
    189. <dependency>
    190. <groupId>org.slf4j</groupId>
    191. <artifactId>jcl-over-slf4j</artifactId>
    192. <version>${slf4j.version}</version>
    193. <scope>runtime</scope>
    194. </dependency>
    195. <!--核心log4j2jar包-->
    196. <dependency>
    197. <groupId>org.apache.logging.log4j</groupId>
    198. <artifactId>log4j-api</artifactId>
    199. <version>${log4j2.version}</version>
    200. </dependency>
    201. <dependency>
    202. <groupId>org.apache.logging.log4j</groupId>
    203. <artifactId>log4j-core</artifactId>
    204. <version>${log4j2.version}</version>
    205. </dependency>
    206. <!--用于与slf4j保持桥接-->
    207. <dependency>
    208. <groupId>org.apache.logging.log4j</groupId>
    209. <artifactId>log4j-slf4j-impl</artifactId>
    210. <version>${log4j2.version}</version>
    211. </dependency>
    212. <!--web工程需要包含log4j-web,非web工程不需要-->
    213. <dependency>
    214. <groupId>org.apache.logging.log4j</groupId>
    215. <artifactId>log4j-web</artifactId>
    216. <version>${log4j2.version}</version>
    217. <scope>runtime</scope>
    218. </dependency>
    219. <!--需要使用log4j2的AsyncLogger需要包含disruptor-->
    220. <dependency>
    221. <groupId>com.lmax</groupId>
    222. <artifactId>disruptor</artifactId>
    223. <version>${log4j2.disruptor.version}</version>
    224. </dependency>
    225. <!--5.其他-->
    226. <dependency>
    227. <groupId>junit</groupId>
    228. <artifactId>junit</artifactId>
    229. <version>${junit.version}</version>
    230. <!--<scope>test</scope>&lt;!&ndash;&ndash;&gt;-->
    231. </dependency>
    232. <dependency>
    233. <groupId>javax.servlet</groupId>
    234. <artifactId>javax.servlet-api</artifactId>
    235. <version>${servlet.version}</version>
    236. <scope>provided</scope>
    237. </dependency>
    238. <dependency>
    239. <groupId>org.projectlombok</groupId>
    240. <artifactId>lombok</artifactId>
    241. <version>${lombok.version}</version>
    242. <scope>provided</scope>
    243. </dependency>
    244. <dependency>
    245. <groupId>jstl</groupId>
    246. <artifactId>jstl</artifactId>
    247. <version>${jstl.version}</version>
    248. </dependency>
    249. <dependency>
    250. <groupId>taglibs</groupId>
    251. <artifactId>standard</artifactId>
    252. <version>${standard.version}</version>
    253. </dependency>
    254. <dependency>
    255. <groupId>org.apache.tomcat</groupId>
    256. <artifactId>tomcat-jsp-api</artifactId>
    257. <version>${tomcat-jsp-api.version}</version>
    258. </dependency>
    259. <dependency>
    260. <groupId>commons-fileupload</groupId>
    261. <artifactId>commons-fileupload</artifactId>
    262. <version>${commons-fileupload.version}</version>
    263. </dependency>
    264. <dependency>
    265. <groupId>org.hibernate</groupId>
    266. <artifactId>hibernate-validator</artifactId>
    267. <version>${hibernate-validator.version}</version>
    268. </dependency>
    269. <!--shiro依赖-->
    270. <dependency>
    271. <groupId>org.apache.shiro</groupId>
    272. <artifactId>shiro-core</artifactId>
    273. <version>${shiro.version}</version>
    274. </dependency>
    275. <dependency>
    276. <groupId>org.apache.shiro</groupId>
    277. <artifactId>shiro-web</artifactId>
    278. <version>${shiro.version}</version>
    279. </dependency>
    280. <dependency>
    281. <groupId>org.apache.shiro</groupId>
    282. <artifactId>shiro-spring</artifactId>
    283. <version>${shiro.version}</version>
    284. </dependency>
    285. </dependencies>
    286. <build>
    287. <finalName>lzxzyssm</finalName>
    288. <resources>
    289. <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
    290. <resource>
    291. <directory>src/main/java</directory>
    292. <includes>
    293. <include>**/*.xml</include>
    294. </includes>
    295. </resource>
    296. <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
    297. <resource>
    298. <directory>src/main/resources</directory>
    299. <includes>
    300. <include>*.properties</include>
    301. <include>*.xml</include>
    302. </includes>
    303. </resource>
    304. </resources>
    305. <plugins>
    306. <plugin>
    307. <groupId>org.apache.maven.plugins</groupId>
    308. <artifactId>maven-compiler-plugin</artifactId>
    309. <version>${maven.compiler.plugin.version}</version>
    310. <configuration>
    311. <source>${maven.compiler.source}</source>
    312. <target>${maven.compiler.target}</target>
    313. <encoding>${project.build.sourceEncoding}</encoding>
    314. </configuration>
    315. </plugin>
    316. <plugin>
    317. <groupId>org.mybatis.generator</groupId>
    318. <artifactId>mybatis-generator-maven-plugin</artifactId>
    319. <version>1.3.2</version>
    320. <dependencies>
    321. <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
    322. <dependency>
    323. <groupId>mysql</groupId>
    324. <artifactId>mysql-connector-java</artifactId>
    325. <version>${mysql.version}</version>
    326. </dependency>
    327. </dependencies>
    328. <configuration>
    329. <overwrite>true</overwrite>
    330. </configuration>
    331. </plugin>
    332. <plugin>
    333. <artifactId>maven-clean-plugin</artifactId>
    334. <version>3.1.0</version>
    335. </plugin>
    336. <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
    337. <plugin>
    338. <artifactId>maven-resources-plugin</artifactId>
    339. <version>3.0.2</version>
    340. </plugin>
    341. <plugin>
    342. <artifactId>maven-compiler-plugin</artifactId>
    343. <version>3.8.0</version>
    344. </plugin>
    345. <plugin>
    346. <artifactId>maven-surefire-plugin</artifactId>
    347. <version>2.22.1</version>
    348. </plugin>
    349. <plugin>
    350. <artifactId>maven-war-plugin</artifactId>
    351. <version>3.2.2</version>
    352. </plugin>
    353. <plugin>
    354. <artifactId>maven-install-plugin</artifactId>
    355. <version>2.5.2</version>
    356. </plugin>
    357. <plugin>
    358. <artifactId>maven-deploy-plugin</artifactId>
    359. <version>2.8.2</version>
    360. </plugin>
    361. </plugins>
    362. </build>
    363. </project>

    web.xml

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

    3.配置文件

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

    数据库配置文件:  jdbc.properties

    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

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

     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>

     spring-mvc-xml:

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:context="http://www.springframework.org/schema/context"
    4. xmlns:mvc="http://www.springframework.org/schema/mvc"
    5. xmlns:aop="http://www.springframework.org/schema/aop"
    6. xmlns="http://www.springframework.org/schema/beans"
    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.liao"/>
    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. <aop:aspectj-autoproxy/>
    19. beans>

    4.后端代码

    分页功能 

     PageBean

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

      PageTag

    1. package com.liao.tag;
    2. import com.liao.utils.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.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();
  • }
  • }
  •  tld

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <taglib xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns="http://java.sun.com/xml/ns/j2ee"
    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>liao 1.1 core library</description>
    7. <display-name>liao core</display-name>
    8. <tlib-version>1.1</tlib-version>
    9. <short-name>liao </short-name>
    10. <uri>http://jsp.veryedu.cn</uri>
    11. <tag>
    12. <name>page</name>
    13. <tag-class>com.liao .tag.PageTag</tag-class>
    14. <body-content>JSP</body-content>
    15. <attribute>
    16. <name>pageBean</name>
    17. <required>true</required>
    18. <rtexprvalue>true</rtexprvalue>
    19. </attribute>
    20. </tag>
    21. </taglib>

    编写业务逻辑层(增删改查方法)

    在UserMapper.xml中新建一条查询sql

    1. <select id="listPager" resultMap="BaseResultMap" parameterType="com.liao.model.User" >
    2. select
    3. <include refid="Base_Column_List" />
    4. from t_oa_user
    5. <where>
    6. <if test="name!=null">
    7. and name like concat('%',#{name},'%')
    8. </if>
    9. </where>
    10. </select>

     UserMapper接口方法

    List<User> listPager(User user);

    业务逻辑层接口

    1. package com.liao.biz;
    2. import com.liao.model.User;
    3. import com.liao.utils.PageBean;
    4. import java.util.List;
    5. public interface UserBiz {
    6. int deleteByPrimaryKey(Long id);
    7. int insert(User record);
    8. int insertSelective(User record);
    9. User selectByPrimaryKey(Long id);
    10. int updateByPrimaryKeySelective(User record);
    11. int updateByPrimaryKey(User record);
    12. List listPager(User user, PageBean page);
    13. }

    实现接口

    1. package com.liao.biz.impl;
    2. import com.liao.biz.UserBiz;
    3. import com.liao.mapper.UserMapper;
    4. import com.liao.model.User;
    5. import com.liao.utils.PageBean;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Service;
    8. import java.util.List;
    9. @Service
    10. public class UserBizImpl implements UserBiz {
    11. @Autowired
    12. private UserMapper userMapper;
    13. @Override
    14. public int deleteByPrimaryKey(Long id) {
    15. return userMapper.deleteByPrimaryKey(id);
    16. }
    17. @Override
    18. public int insert(User record) {
    19. return userMapper.insert(record);
    20. }
    21. @Override
    22. public int insertSelective(User record) {
    23. return userMapper.insertSelective(record);
    24. }
    25. @Override
    26. public User selectByPrimaryKey(Long id) {
    27. return userMapper.selectByPrimaryKey(id);
    28. }
    29. @Override
    30. public int updateByPrimaryKeySelective(User record) {
    31. return userMapper.updateByPrimaryKeySelective(record);
    32. }
    33. @Override
    34. public int updateByPrimaryKey(User record) {
    35. return userMapper.updateByPrimaryKey(record);
    36. }
    37. @Override
    38. public List listPager(User user, PageBean page) {
    39. return userMapper.listPager(user);
    40. }
    41. }

    .编写切面

    1. package com.liao.aspect;
    2. import com.github.pagehelper.PageHelper;
    3. import com.github.pagehelper.PageInfo;
    4. import com.liao.utils.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. @Aspect
    11. @Component
    12. public class PageAspect {
    13. @Around("execution(* *..*Biz.*Pager(..))")
    14. public Object invoke(ProceedingJoinPoint args) throws Throwable {
    15. PageBean pageBean = null;
    16. Object[] args1 = args.getArgs();
    17. for (Object param:args1) {
    18. if (param instanceof PageBean){
    19. pageBean = (PageBean) param;
    20. break;
    21. }
    22. }
    23. if(pageBean!=null && pageBean.isPagination())
    24. PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
    25. Object proceed = args.proceed();
    26. if(pageBean!=null && pageBean.isPagination()){
    27. PageInfo info = new PageInfo((List) proceed);
    28. pageBean.setTotal((int) info.getTotal());
    29. }
    30. return proceed;
    31. }
    32. }

    web层控制器

    1. package com.liao.web;
    2. import com.liao.biz.UserBiz;
    3. import com.liao.model.User;
    4. import com.liao.utils.PageBean;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Controller;
    7. import org.springframework.web.bind.annotation.GetMapping;
    8. import org.springframework.web.bind.annotation.PathVariable;
    9. import org.springframework.web.bind.annotation.RequestMapping;
    10. import org.springframework.web.servlet.ModelAndView;
    11. import javax.servlet.http.HttpServletRequest;
    12. import java.util.List;
    13. /**
    14. * @author 云村小威
    15. * @site blog.csdn.net/Justw320
    16. * @create 2023-09-08 11:56
    17. */
    18. @Controller
    19. @RequestMapping("/users")
    20. public class UserController {
    21. @Autowired
    22. private UserBiz userBiz;
    23. /*新增方法*/
    24. @RequestMapping("/add")
    25. public String save(User user, HttpServletRequest request) {
    26. userBiz.insertSelective(user);
    27. return "redirect:list";
    28. }
    29. /*删除方法*/
    30. @RequestMapping("/del/{id}")
    31. public String del(@PathVariable("id") Long id, HttpServletRequest request) {
    32. userBiz.deleteByPrimaryKey(id);
    33. return "redirect:/users/list";
    34. }
    35. /*修改方法*/
    36. @RequestMapping("/edit")
    37. public String edit(User user, HttpServletRequest request) {
    38. userBiz.updateByPrimaryKeySelective(user);
    39. return "redirect:list";
    40. }
    41. /*查询方法*/
    42. @GetMapping("/list")
    43. public ModelAndView list(User user, HttpServletRequest request) {
    44. PageBean pageBean = new PageBean();
    45. pageBean.setRequest(request);
    46. List users = userBiz.listPager(user, pageBean);
    47. ModelAndView modelAndView = new ModelAndView();
    48. modelAndView.addObject("users", users);
    49. modelAndView.addObject("pageBean", pageBean);
    50. modelAndView.setViewName("user/list");
    51. return modelAndView;
    52. }
    53. /*数据回显*/
    54. @RequestMapping("/preSave")
    55. public String preSave(User user, HttpServletRequest request) {
    56. if (user != null && user.getId() != null && user.getId() != 0) {
    57. User u = userBiz.selectByPrimaryKey(user.getId());
    58. request.setAttribute("u", u);
    59. }
    60. return "user/edit";
    61. }
    62. }

    5.前端代码

    list.jsp

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


    edit.jsp 

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4.     <title>用户编辑、新增公共页面</title>
    5. </head>
    6. <body>
    7. <form action="${pageContext.request.contextPath }/${empty u ? 'users/add' : 'users/edit'}" method="post">
    8.     用户id:<input type="text" name="id" value="${u.id }"><br>
    9.     用户名:<input type="text" name="name" value="${u.name }"><br>
    10.     账号:<input type="text" name="loginname" value="${u.loginname }"><br>
    11.     密码:<input type="text" name="pwd" value="${u.pwd }"><br>
    12.     权限:<input type="text" name="rid" value="${u.rid }"><br>
    13.     <input type="submit">
    14. </form>
    15. </body>
    16. </html>

  • 相关阅读:
    一文看懂推荐系统:召回07:双塔模型——正负样本的选择,召回的目的是区分感兴趣和不感兴趣的,精排是区分感兴趣和非常感兴趣的
    java异常处理
    RocketMQ的push消费方式实现的太聪明了
    Process assessment techniques-3
    写给 MMSegmentation 工具箱新手的避坑指南
    Linux 远程工具 基础命令
    分销商城小程序开发运营逻辑是什么?
    PIC单片机4——定时器方波
    前端监控系列2 |聊聊 JS 错误监控那些事儿
    3D体验平台品牌应用——ENOVIA
  • 原文地址:https://blog.csdn.net/liaozhixiangjava/article/details/132769366