“构建高效的SpringMVC增删改查应用“

目录

  • 引言
    • 1.配置SpringMVC
      • pom.xml
      • web.xml
      • zking.tld
      • generatorConfig.xml
      • jdbc.properties
      • log4j2.xml
      • spring-context.xml
      • spring-mvc.xml
      • spring-mybatis.xml
      • StudentBizImpl
      • PagerAspect
      • PageTag
    • 2.实现代码功能
      • StudentController
    • 3.JSP页面代码
      • List.jsp
      • edit.jsp
      • heard.jsp
    • 4. 运行截图
    • 总结

“构建高效的SpringMVC增删改查应用“_第1张图片

引言

在现代软件开发中,实现增删改查(CRUD)功能是非常常见且重要的任务。SpringMVC是一个强大的框架,可以帮助我们快速构建具有CRUD功能的应用程序。本文将介绍如何使用SpringMVC来实现高效的增删改查功能,并提供一些实用的技巧和最佳实践。

1.配置SpringMVC

pom.xml



<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>yhzyssmartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>yhzyssm 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>
    <finalName>yhzyssmfinalName>
    <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>

web.xml


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

zking.tld


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

generatorConfig.xml


DOCTYPE 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:\\Course\\Y1\\1.maven(1)\\temp2\\mvn_repository\\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.yuan.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.yuan.mapper"
                         targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false"/>
        sqlMapGenerator>

        
        
        
        
        <javaClientGenerator targetPackage="com.yuan.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            
            <property name="enableSubPackages" value="false"/>
        javaClientGenerator>

        
        
        
        
        
        
        
        
        
        
        
        
        

        <table schema="" tableName="t_mysql_student" domainObjectName="Student"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            
            
            
            
        table>

    context>
generatorConfiguration>


jdbc.properties

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

log4j2.xml




<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


<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:spring-mybatis.xml">import>
beans>

spring-mvc.xml


<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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <context:component-scan base-package="com.yuan"/>

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

    
    

    <aop:aspectj-autoproxy/>
beans>

spring-mybatis.xml


<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.yuan"/>

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

StudentBizImpl

package com.yuan.Biz.Impl;

import com.yuan.Biz.StudentBiz;
import com.yuan.mapper.StudentMapper;
import com.yuan.model.Student;
import com.yuan.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-09-07 14:12
 */
@Service
public class StudentBizImpl implements StudentBiz {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public int deleteByPrimaryKey(String sid) {
        return studentMapper.deleteByPrimaryKey(sid);
    }

    @Override
    public int insert(Student record) {
        return studentMapper.insert(record);
    }

    @Override
    public int insertSelective(Student record) {
        return studentMapper.insertSelective(record);
    }

    @Override
    public Student selectByPrimaryKey(String sid) {
        return studentMapper.selectByPrimaryKey(sid);
    }

    @Override
    public int updateByPrimaryKeySelective(Student record) {
        return studentMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Student record) {
        return studentMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Student> selBySnamePager(Student student, PageBean pageBean) {
        return studentMapper.selBySnamePager(student);
    }


}

PagerAspect

package com.yuan.aspect;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuan.utils.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
 * @company 卓京公司
 * @create 2023-08-25 17:01
 */
@Aspect
@Component
public class PagerAspect {

    @Around("execution(* *..*Biz.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable {
        PageBean pageBean = null;
        //获取目标中的所有方法
        Object[] args1 = args.getArgs();
        for (Object o : args1) {
            if (o instanceof PageBean) {
                pageBean = (PageBean) o;
                break;
            }
        }
        if (pageBean != null && pageBean.isPagination()) {
            PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
        }
        Object proceed = args.proceed();
        if (pageBean != null && pageBean.isPagination()) {
            PageInfo pageInfo = new PageInfo((List) proceed);
            pageBean.setTotal((int) pageInfo.getTotal());
        }
        return proceed;
        }

}

PageTag

package com.yuan.tag;

import com.yuan.utils.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.getMap(); 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(""); // 分页执行的JS代码 sb.append(""); return sb.toString(); } }

2.实现代码功能

StudentController

package com.yuan.web;

import com.yuan.Biz.StudentBiz;
import com.yuan.model.Student;
import com.yuan.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 叶秋
 * @site
 * @company 卓京公司
 * @create 2023-09-07 16:52
 */
@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentBiz studentBiz;

    @RequestMapping("/list")
    public String list(Student student, HttpServletRequest request){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List<Student> students = studentBiz.selBySnamePager(student, pageBean);
        request.setAttribute("list",students);
        request.setAttribute("pageBean",pageBean);
        return "stu/list";
    }

    @RequestMapping("/add")
    public String add(Student student){
        studentBiz.insertSelective(student);
        return "redirect:list";
    }

    @RequestMapping("/del/{sid}")
    public String add(@PathVariable("sid") String sid){
        studentBiz.deleteByPrimaryKey(sid);
        return "redirect:/student/list";
    }

    @RequestMapping("/edit")
    public String edit(Student student){
        studentBiz.updateByPrimaryKeySelective(student);
        return "redirect:list";
    }

    @RequestMapping("/pareSave")
    public String pareSave(Student student, Model model){
        if(student!=null && student.getSid()!=null){
            Student s = studentBiz.selectByPrimaryKey(student.getSid());
            model.addAttribute("s",s);
        }
        return "stu/edit";

    }


}

3.JSP页面代码

List.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
DOCTYPE html >
<html>
<head>
<%@ include file="/common/header.jsp" %>
head>
<body>
<form class="form-inline"
      action="/student/list" method="post">
    <div class="form-group mb-2">
        <input type="text" class="form-control-plaintext" name="sname"
               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="/student/pareSave">新增a>
form>

<table class="table table-striped ">
    <thead>
    <tr>
        <th scope="col">学生编号th>
        <th scope="col">学生名称th>
        <th scope="col">学生年龄th>
        <th scope="col">学生性别th>
        <th scope="col">操作th>
    tr>
    thead>
    <tbody>
    <c:forEach  var="s" items="${list }">
        <tr>
            <td>${s.sid }td>
            <td>${s.sname }td>
            <td>${s.sage }td>
            <td>${s.ssex }td>
            <td>
                <a href="/student/pareSave?sid=${s.sid}">修改a>
                <a href="/student/del/${s.sid}">删除a>
            td>
        tr>
    c:forEach>
    tbody>
table>

<z:page pageBean="${pageBean }">z:page>
${pageBean}
body>
html>

edit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
DOCTYPE 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 s ? 'student/add' : 'student/edit'}" method="post">
    学生编号:<input type="text" name="sid" value="${s.sid }"><br>
    学生姓名:<input type="text" name="sname" value="${s.sname }"><br>
    学生年龄:<input type="text" name="sage" value="${s.sage }"><br>
    学生性别:<input type="text" name="ssex" value="${s.ssex }"><br>
    <input type="submit">
form>
body>
html>

heard.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"%>
DOCTYPE html >
<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>
    <base href="${pageContext.request.contextPath }" />
head>

4. 运行截图

“构建高效的SpringMVC增删改查应用“_第2张图片

“构建高效的SpringMVC增删改查应用“_第3张图片
“构建高效的SpringMVC增删改查应用“_第4张图片

总结

在本文中,我们详细介绍了如何使用SpringMVC框架来实现高效的增删改查功能。我们讨论了创建数据库模型、配置SpringMVC框架以及实现查询、新增、修改和删除功能的步骤。通过学习本文,您将能够构建出功能完善且高效的SpringMVC应用程序。
希望本文对您有所帮助,谢谢阅读!

你可能感兴趣的:(spring,mybatis,java,tomcat,maven,idea)