🥳🥳Welcome Huihui's Code World ! !🥳🥳
接下来看看由辉辉所写的关于SpringMVC的相关操作吧
目录
🥳🥳Welcome Huihui's Code World ! !🥳🥳
将项目需要用到的插件以及依赖导入到pom.xml中
"1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0modelVersion> <groupId>org.examplegroupId> <artifactId>WHzyssmartifactId> <version>1.0-SNAPSHOTversion> <packaging>warpackaging> <name>Spring-Mybatis Maven Webappname> <url>http://www.example.comurl> <properties> <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> <maven.compiler.source>1.8maven.compiler.source> <maven.compiler.target>1.8maven.compiler.target> <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version> <spring.version>5.0.2.RELEASEspring.version> <mybatis.version>3.4.5mybatis.version> <mysql.version>5.1.44mysql.version> <pagehelper.version>5.1.2pagehelper.version> <mybatis.spring.version>1.3.1mybatis.spring.version> <commons.dbcp2.version>2.1.1commons.dbcp2.version> <commons.pool2.version>2.4.3commons.pool2.version> <log4j2.version>2.9.1log4j2.version> <log4j2.disruptor.version>3.2.0log4j2.disruptor.version> <slf4j.version>1.7.13slf4j.version> <junit.version>4.12junit.version> <servlet.version>4.0.0servlet.version> <lombok.version>1.18.2lombok.version> <mybatis.ehcache.version>1.1.0mybatis.ehcache.version> <ehcache.version>2.10.0ehcache.version> <redis.version>2.9.0redis.version> <redis.spring.version>1.7.1.RELEASEredis.spring.version> <jackson.version>2.9.3jackson.version> <jstl.version>1.2jstl.version> <standard.version>1.1.2standard.version> <tomcat-jsp-api.version>8.0.47tomcat-jsp-api.version> <commons-fileupload.version>1.3.3commons-fileupload.version> <hibernate-validator.version>5.0.2.Finalhibernate-validator.version> <shiro.version>1.3.2shiro.version> properties> <dependencies> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-coreartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-beansartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-ormartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-aspectsartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> <version>${mybatis.version}version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>${mysql.version}version> dependency> <dependency> <groupId>com.github.pagehelpergroupId> <artifactId>pagehelperartifactId> <version>${pagehelper.version}version> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatis-springartifactId> <version>${mybatis.spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-context-supportartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.mybatis.cachesgroupId> <artifactId>mybatis-ehcacheartifactId> <version>${mybatis.ehcache.version}version> dependency> <dependency> <groupId>net.sf.ehcachegroupId> <artifactId>ehcacheartifactId> <version>${ehcache.version}version> dependency> <dependency> <groupId>redis.clientsgroupId> <artifactId>jedisartifactId> <version>${redis.version}version> dependency> <dependency> <groupId>org.springframework.datagroupId> <artifactId>spring-data-redisartifactId> <version>${redis.spring.version}version> dependency> <dependency> <groupId>com.fasterxml.jackson.coregroupId> <artifactId>jackson-databindartifactId> <version>${jackson.version}version> dependency> <dependency> <groupId>com.fasterxml.jackson.coregroupId> <artifactId>jackson-coreartifactId> <version>${jackson.version}version> dependency> <dependency> <groupId>com.fasterxml.jackson.coregroupId> <artifactId>jackson-annotationsartifactId> <version>${jackson.version}version> dependency> <dependency> <groupId>org.apache.commonsgroupId> <artifactId>commons-dbcp2artifactId> <version>${commons.dbcp2.version}version> <exclusions> <exclusion> <artifactId>commons-pool2artifactId> <groupId>org.apache.commonsgroupId> exclusion> exclusions> dependency> <dependency> <groupId>org.apache.commonsgroupId> <artifactId>commons-pool2artifactId> <version>${commons.pool2.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-apiartifactId> <version>${slf4j.version}version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>jcl-over-slf4jartifactId> <version>${slf4j.version}version> <scope>runtimescope> dependency> <dependency> <groupId>org.apache.logging.log4jgroupId> <artifactId>log4j-apiartifactId> <version>${log4j2.version}version> dependency> <dependency> <groupId>org.apache.logging.log4jgroupId> <artifactId>log4j-coreartifactId> <version>${log4j2.version}version> dependency> <dependency> <groupId>org.apache.logging.log4jgroupId> <artifactId>log4j-slf4j-implartifactId> <version>${log4j2.version}version> dependency> <dependency> <groupId>org.apache.logging.log4jgroupId> <artifactId>log4j-webartifactId> <version>${log4j2.version}version> <scope>runtimescope> dependency> <dependency> <groupId>com.lmaxgroupId> <artifactId>disruptorartifactId> <version>${log4j2.disruptor.version}version> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>${junit.version}version> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>javax.servlet-apiartifactId> <version>${servlet.version}version> <scope>providedscope> dependency> <dependency> <groupId>org.projectlombokgroupId> <artifactId>lombokartifactId> <version>${lombok.version}version> <scope>providedscope> dependency> <dependency> <groupId>jstlgroupId> <artifactId>jstlartifactId> <version>${jstl.version}version> dependency> <dependency> <groupId>taglibsgroupId> <artifactId>standardartifactId> <version>${standard.version}version> dependency> <dependency> <groupId>org.apache.tomcatgroupId> <artifactId>tomcat-jsp-apiartifactId> <version>${tomcat-jsp-api.version}version> dependency> <dependency> <groupId>commons-fileuploadgroupId> <artifactId>commons-fileuploadartifactId> <version>${commons-fileupload.version}version> dependency> <dependency> <groupId>org.hibernategroupId> <artifactId>hibernate-validatorartifactId> <version>${hibernate-validator.version}version> dependency> <dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-coreartifactId> <version>${shiro.version}version> dependency> <dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-webartifactId> <version>${shiro.version}version> dependency> <dependency> <groupId>org.apache.shirogroupId> <artifactId>shiro-springartifactId> <version>${shiro.version}version> dependency> dependencies> <build> <resources> <resource> <directory>src/main/javadirectory> <includes> <include>**/*.xmlinclude> includes> resource> <resource> <directory>src/main/resourcesdirectory> <includes> <include>*.propertiesinclude> <include>*.xmlinclude> includes> resource> resources> <plugins> <plugin> <groupId>org.apache.maven.pluginsgroupId> <artifactId>maven-compiler-pluginartifactId> <version>${maven.compiler.plugin.version}version> <configuration> <source>${maven.compiler.source}source> <target>${maven.compiler.target}target> <encoding>${project.build.sourceEncoding}encoding> configuration> plugin> <plugin> <groupId>org.mybatis.generatorgroupId> <artifactId>mybatis-generator-maven-pluginartifactId> <version>1.3.2version> <dependencies> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>${mysql.version}version> dependency> dependencies> <configuration> <overwrite>trueoverwrite> configuration> plugin> <plugin> <artifactId>maven-clean-pluginartifactId> <version>3.1.0version> plugin> <plugin> <artifactId>maven-resources-pluginartifactId> <version>3.0.2version> plugin> <plugin> <artifactId>maven-compiler-pluginartifactId> <version>3.8.0version> plugin> <plugin> <artifactId>maven-surefire-pluginartifactId> <version>2.22.1version> plugin> <plugin> <artifactId>maven-war-pluginartifactId> <version>3.2.2version> plugin> <plugin> <artifactId>maven-install-pluginartifactId> <version>2.5.2version> plugin> <plugin> <artifactId>maven-deploy-pluginartifactId> <version>2.8.2version> plugin> plugins> build> project>二.添加框架的配置文件
generatorConfig.xml
这个文件用于生成Java代码。它包含了数据库连接信息、Java类型转换设置、JavaBean生成设置、SQL映射文件生成设置以及生成的表的结构等信息。通过这个配置文件,MyBatis Generator可以根据这些配置信息自动生成相应的Java实体类、Mapper接口以及XML映射文件
"1.0" encoding="UTF-8" ?> generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" > <generatorConfiguration> <properties resource="jdbc.properties"/> <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"/> <context id="infoGuardian"> <commentGenerator> <property name="suppressAllComments" value="true"/> <property name="suppressDate" value="true"/> commentGenerator> <jdbcConnection driverClass="${jdbc.driver}" connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> javaTypeResolver> <javaModelGenerator targetPackage="com.wh.model" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> <property name="constructorBased" value="true"/> <property name="trimStrings" value="false"/> <property name="immutable" value="false"/> javaModelGenerator> <sqlMapGenerator targetPackage="com.wh.mapper" targetProject="src/main/java"> <property name="enableSubPackages" value="false"/> sqlMapGenerator> <javaClientGenerator targetPackage="com.wh.mapper" targetProject="src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="false"/> javaClientGenerator> <table schema="" tableName="t_mvc_cat" domainObjectName="Cat" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false"> table> context> generatorConfiguration>jdbc.properties
这个配置文件是用来配置Java应用程序与MySQL数据库的连接信息的
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=123456log4j2.xml
这个配置文件是用于配置Log4j2的日志输出规则。Log4j2是一个用于Java应用程序的日志框架,它提供了灵活的日志记录功能
"1.0" encoding="UTF-8"?> <Configuration status="WARN" monitorInterval="30"> <Properties> <Property name="LOG_HOME">/root/workspace/lucenedemo/logsProperty> <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/errorproperty> <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warnproperty> <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%nproperty> Properties> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="${PATTERN}" /> Console> <File name="log" fileName="logs/test.log" append="false"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> File> <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log" filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <Policies> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> Policies> RollingFile> <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log" filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log"> <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <Policies> <TimeBasedTriggeringPolicy /> <SizeBasedTriggeringPolicy size="2 kB" /> Policies> <DefaultRolloverStrategy max="20" /> RollingFile> <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log" filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log"> <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> <Policies> <TimeBasedTriggeringPolicy interval="1" modulate="true" /> Policies> RollingFile> Appenders> <Loggers> <logger name="org.springframework" level="INFO">logger> <logger name="org.mybatis" level="INFO">logger> <logger name="org.springframework" level="ERROR" /> <logger name="org.hibernate" level="ERROR" /> <logger name="org.apache.struts2" level="ERROR" /> <logger name="com.opensymphony.xwork2" level="ERROR" /> <logger name="org.jboss" level="ERROR" /> <root level="all"> <appender-ref ref="Console" /> <appender-ref ref="RollingFileInfo" /> <appender-ref ref="RollingFileWarn" /> <appender-ref ref="RollingFileError" /> root> Loggers> Configuration>Spring-context.xml
这是一个Spring框架的配置文件,用于定义和管理Spring容器中的Bean。它使用XML格式来描述Bean的配置信息和依赖关系。通过这个配置文件,Spring框架可以自动扫描并加载应用程序中的Bean定义,并根据这些配置信息创建和管理Bean的实例。这样可以实现依赖注入、面向切面编程等特性
"1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="classpath:SpringMVCzy.xml">import> beans>Spring-mvc.xml
这个配置文件是Spring MVC框架的XML配置文件,用于配置Spring MVC的各种组件和属性,其中做了这些操作:
- 扫描
com.wh
包及其子包下的控制器类,将它们注册为Spring MVC的控制器- 开启注解驱动的Spring MVC功能,这意味着可以使用基于注解的方式进行请求映射、数据绑定等操作
- 配置了一个视图解析器(ViewResolver),用于将控制器返回的逻辑视图名解析为实际的视图对象。这里使用了JSP视图技术,并指定了JSP文件存放在
/WEB-INF/jsp/
目录下- 注释掉了一些资源处理器的配置,这些配置可以用于处理静态资源(如图片、样式表、JavaScript文件等)的请求
"1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" 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-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.wh"/> <mvc:annotation-driven /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView">property> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> bean> <mvc:resources location="/common/" mapping="/jsp/**"/> <aop:aspectj-autoproxy/> beans>SpringMVCzy.xml
这是一个Spring框架的XML配置文件,用于配置Spring应用程序的各种组件和属性。其中做了这些操作:
- 注解式开发:通过
启用注解驱动的配置,允许使用注解来定义和管理Bean
- 组件扫描:通过
标签指定要扫描的包路径,以自动发现并注册Bean
- 属性占位符:通过
标签指定属性文件的位置,用于从外部属性文件中加载配置信息
- 数据源配置:通过
标签配置数据库连接池,包括驱动程序类名、URL、用户名、密码等属性
- MyBatis整合:通过
和
配置MyBatis的SqlSessionFactory和Mapper接口扫描器,实现自动扫描和注册Mapper接口
- 事务管理:通过
和
配置事务管理器,将DataSource与事务管理器关联起来
- AOP支持:通过
启用AspectJ自动代理,支持面向切面编程
"1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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"> <context:annotation-config/> <context:component-scan base-package="com.wh"/> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="initialSize" value="10"/> <property name="maxTotal" value="100"/> <property name="maxIdle" value="50"/> <property name="minIdle" value="10"/> <property name="maxWaitMillis" value="-1"/> bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath*:com/wh/**/mapper/*.xml"/> <property name="typeAliasesPackage" value="com/wh/**/model"/> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <value> helperDialect=mysql value> property> bean> array> property> bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com/wh/**/mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> bean> <tx:annotation-driven transaction-manager="transactionManager" /> <aop:aspectj-autoproxy/> beans>web.xml
"1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Applicationdisplay-name> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:Spring-context.xmlparam-value> context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class> listener> <filter> <filter-name>encodingFilterfilter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> <async-supported>trueasync-supported> <init-param> <param-name>encodingparam-name> <param-value>UTF-8param-value> init-param> filter> <filter-mapping> <filter-name>encodingFilterfilter-name> <url-pattern>/*url-pattern> filter-mapping> <servlet> <servlet-name>SpringMVCservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:Spring-mvc.xmlparam-value> init-param> <load-on-startup>1load-on-startup> <async-supported>trueasync-supported> servlet> <servlet-mapping> <servlet-name>SpringMVCservlet-name> <url-pattern>/url-pattern> servlet-mapping> web-app>
PagBean
package com.wh.util; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; /** * 分页工具类 * */ public class PageBean { private int page = 1;// 页码 private int rows = 10;// 页大小 private int total = 0;// 总记录数 private boolean pagination = true;// 是否分页 private String url; //保存上一次请求的URL private Map<String,String[]> paramMap = new HashMap<>();// 保存上一次请求的参数 /** * 初始化pagebean的,保存上一次请求的重要参数 * @param req */ public void setRequest(HttpServletRequest req) { // 1.1 需要保存上一次请求的URL this.setUrl(req.getRequestURL().toString()); // 1.2 需要保存上一次请求的参数 bname、price this.setParamMap(req.getParameterMap()); // 1.3 需要保存上一次请求的分页设置 pagination this.setPagination(req.getParameter("pagination")); // 1.4 需要保存上一次请求的展示条目数 this.setRows(req.getParameter("rows")); // 1.5 初始化请求的页码 page this.setPage(req.getParameter("page")); } public void setPage(String page) { if(StringUtils.isNotBlank(page)) this.setPage(Integer.valueOf(page)); } public void setRows(String rows) { if(StringUtils.isNotBlank(rows)) this.setRows(Integer.valueOf(rows)); } public void setPagination(String pagination) { // 只有在前台jsp填写了pagination=false,才代表不分页 if(StringUtils.isNotBlank(pagination)) this.setPagination(!"false".equals(pagination)); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map<String, String[]> getParamMap() { return paramMap; } public void setParamMap(Map<String, String[]> paramMap) { this.paramMap = paramMap; } public PageBean() { super(); } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public void setTotal(String total) { this.total = Integer.parseInt(total); } public boolean isPagination() { return pagination; } public void setPagination(boolean pagination) { this.pagination = pagination; } /** * 获得起始记录的下标 * * @return */ public int getStartIndex() { return (this.page - 1) * this.rows; } /** * 最大页 * @return */ public int maxPage() { // total % rows == 0 ? total / rows : total / rows +1 return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1; } /** * 下一页 * @return */ public int nextPage() { // 如果当前页小于最大页,那就下一页为当前页+1;如果不小于,说明当前页就是最大页,那就无需+1 return this.page < this.maxPage() ? this.page + 1 : this.page; } /** * 上一页 * @return */ public int previousPage() { return this.page > 1 ? this.page - 1 : this.page; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]"; } }PageTag
package com.wh.tag; import com.wh.util.PageBean; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class PageTag extends BodyTagSupport{ private PageBean pageBean;// 包含了所有分页相关的元素 public PageBean getPageBean() { return pageBean; } public void setPageBean(PageBean pageBean) { this.pageBean = pageBean; } @Override public int doStartTag() throws JspException { // 没有标签体,要输出内容 JspWriter out = pageContext.getOut(); try { out.print(toHTML()); } catch (IOException e) { e.printStackTrace(); } return super.doStartTag(); } private String toHTML() { StringBuffer sb = new StringBuffer(); // 隐藏的form表单---这个就是上一次请求下次重新发的奥义所在 // 上一次请求的URL sb.append("); sb.append(" "); // 上一次请求的参数 Map<String, String[]> paramMap = pageBean.getParamMap(); if(paramMap != null && paramMap.size() > 0) { Set<Entry<String, String[]>> entrySet = paramMap.entrySet(); for (Entry<String, String[]> entry : entrySet) { // 参数名 String key = entry.getKey(); // 参数值 for (String value : entry.getValue()) { // 上一次请求的参数,再一次组装成了新的Form表单 // 注意:page参数每次都会提交,我们需要避免 if(!"page".equals(key)) { sb.append(" "); } } } } sb.append(""); // 分页条 sb.append(""
); sb.append("- );
sb.append(" href='javascript:gotoPage(1)'>首页"); sb.append("- );
sb.append(" href='javascript:gotoPage("+pageBean.previousPage()+")'><");// less than 小于号 // sb.append("- 1
"); // sb.append("- 2
"); sb.append("- >
"); sb.append("- 尾页
"); sb.append("- 到第);
sb.append(" type='text' id='skipPage' name='' />页"); sb.append("- );
sb.append(" href='javascript:skipPage()'>确定"); sb.append("- 共"
+pageBean.getTotal()+"条"); sb.append(""); // 分页执行的JS代码 sb.append(""); return sb.toString(); } }StringUtils
package com.wh.util; public class StringUtils { // 私有的构造方法,保护此类不能在外部实例化 private StringUtils() { } /** * 如果字符串等于null或去空格后等于"",则返回true,否则返回false * * @param s * @return */ public static boolean isBlank(String s) { boolean b = false; if (null == s || s.trim().equals("")) { b = true; } return b; } /** * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false * * @param s * @return */ public static boolean isNotBlank(String s) { return !isBlank(s); } }切面类Aspect
package com.wh.aop; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.wh.util.PageBean; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; import java.util.List; /** * @author 王辉 * @site www.shihuihuila.com * @create 2023-08-25 21:27 */ @Aspect //代表当前类是切面类 @Component //代表这个是交给Spring管理 public class AspectPager { @Around("execution(* *..*Biz.*Pager(..))") public Object invoke(ProceedingJoinPoint args) throws Throwable { Object[] params = args.getArgs(); PageBean pageBean = null; for (Object param : params) { if (param instanceof PageBean) { pageBean = (PageBean) param; break; } } if (pageBean != null && pageBean.isPagination()) PageHelper.startPage(pageBean.getPage(), pageBean.getRows()); Object list = args.proceed(params); if (null != pageBean && pageBean.isPagination()) { PageInfo pageInfo = new PageInfo((List) list); pageBean.setTotal(pageInfo.getTotal() + ""); } return list; } }
1.发布项目
2.生成代码
biz
package com.wh.biz; import com.wh.model.Cat; import com.wh.util.PageBean; import java.util.List; public interface CatBiz { int deleteByPrimaryKey(Integer cid); int insert(Cat record); int insertSelective(Cat record); ListselectByPrimaryKey(Integer cid); ListselectLikePager(Cat cat,PageBean pageBean); int updateByPrimaryKeySelective(Cat record); int updateByPrimaryKey(Cat record); }
package com.wh.biz; import com.wh.mapper.CatMapper; import com.wh.model.Cat; import com.wh.util.PageBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author 王辉 * @site www.shihuihuila.com * @create 2023-09-08 18:05 */ @Service public class CatBizImpl implements CatBiz { @Autowired private CatMapper catBiz; @Override public int deleteByPrimaryKey(Integer cid) { return catBiz.deleteByPrimaryKey(cid); } @Override public int insert(Cat record) { return catBiz.insert(record); } @Override public int insertSelective(Cat record) { return catBiz.insertSelective(record); } @Override public ListselectByPrimaryKey(Integer cid) { return catBiz.selectByPrimaryKey(cid); } @Override public ListselectLikePager(Cat cat, PageBean pageBean) { return catBiz.selectLikePager(cat); } @Override public int updateByPrimaryKeySelective(Cat record) { return catBiz.updateByPrimaryKeySelective(record ); } @Override public int updateByPrimaryKey(Cat record) { return catBiz.updateByPrimaryKey(record); } }web
package com.wh.web; import com.wh.biz.CatBiz; import com.wh.model.Cat; import com.wh.util.PageBean; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * @author 王辉 * @site www.shihuihuila.com * @create 2023-09-08 18:08 */ @Controller @RequestMapping("/smvc3") @Slf4j public class CatController { @Autowired private CatBiz catBiz; //增 @RequestMapping("/add") public String add(Cat cat){ catBiz.insertSelective(cat); return "redirect:list"; } // 删 @RequestMapping("/del") public String del(Cat cat){ catBiz.deleteByPrimaryKey(cat.getCid()); return "redirect:list"; } // 改 @RequestMapping("/upd") public String upd(Cat cat){ catBiz.updateByPrimaryKeySelective(cat); return "redirect:list"; } // 查 @RequestMapping("/list") public String list(Cat cat, HttpServletRequest request){ PageBean pageBean=new PageBean(); Listcats = catBiz.selectLikePager(cat, pageBean); request.setAttribute("list",cats); request.setAttribute("pageBean",pageBean); return "index"; } //数据回显 @RequestMapping("/preSave") public String preSave(Cat cat, Model model){ if(cat!=null && cat.getCid()!=null){ Listcats = catBiz.selectByPrimaryKey(cat.getCid()); model.addAttribute("c",cats.get(0)); } return "edit"; } }
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js">script> <title>博客列表title> <style type="text/css"> .page-item input { padding: 0; width: 40px; height: 100%; text-align: center; margin: 0 6px; } .page-item input, .page-item b { line-height: 38px; float: left; font-weight: 400; } .page-item.go-input { margin: 0 10px; } style> head> <body> <form class="form-inline" action="${pageContext.request.contextPath }/smvc3/list" method="post"> <div class="form-group mb-2"> <input type="text" class="form-control-plaintext" name="cname" placeholder="请输入书籍名称"> <input name="pagination" value="false" type="hidden"> div> <button type="submit" class="btn btn-primary mb-2">查询button> <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/smvc3/preSave">新增a> form> <table class="table table-striped "> <thead> <tr> <th scope="col">猫咪IDth> <th scope="col">猫咪名字th> <th scope="col">猫咪年龄th> <th scope="col">操作th> tr> thead> <tbody> <c:forEach var="b" items="${list }"> <tr> <td>${b.cid }td> <td>${b.cname }td> <td>${b.age }td> <td> <a href="${pageContext.request.contextPath }/smvc3/preSave?cid=${b.cid}">修改a> <a href="${pageContext.request.contextPath }/smvc3/del?cid=${b.cid}">删除a> td> tr> c:forEach> tbody> table> <z:page pageBean="${pageBean }">z:page> body> html>edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>编辑界面title> head> <body> <form action="${pageContext.request.contextPath }/${empty c ? 'smvc3/add' : 'smvc3/upd'}" method="post"> <c:forEach var="b" items="${c }"> 猫咪id:<input type="text" name="cid" value="${b.cid }"><br> 猫咪姓名:<input type="text" name="cname" value="${b.cname }"><br> 猫咪年龄:<input type="text" name="age" value="${b.age }"><br> <input type="submit"> c:forEach> form> body> html>
好啦,今天的分享就到这了,希望能够帮到你呢!😊😊