SpringMVC实现增删改查

文章目录

  • 一、配置文件
    • 1.1 导入相关pom依赖
    • 1.2 jdbc.properties:配置文件
    • 1.3 generatorConfig.xml:代码生成器
    • 1.4 spring-mybatis.xml :spring与mybatis整合的配置文件
    • 1.5 spring-context.xml :上下文配置文件
    • 1.6 spring-mvc-xml: 配置Spring框架的一些关键组件和功能
    • 1.7 web.xml 配置
  • 二、引入工具类
    • 2.1 PageBean.java:
    • 2.2 PageTag.java
    • 2.3 xqx.tld
  • 三、发布项目
    • 3.1 逆向生成代码
    • 3.2 发布项目
  • 四、实现增删改查
    • 4.1 后端代码
    • 4.2 前端代码
    • 4.3 运行结果

一、配置文件

1.1 导入相关pom依赖



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

  <name>xqxzySSM 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>
      <scope>testscope>
    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>XqxzySSMfinalName>
    <resources>
      
      <resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.xmlinclude>
        includes>
      resource>
      
      <resource>
        <directory>src/main/resourcesdirectory>
        <includes>
          <include>*.propertiesinclude>
          <include>*.xmlinclude>
        includes>
      resource>
    resources>
    <pluginManagement>
      <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>
    pluginManagement>
  build>

project>

1.2 jdbc.properties:配置文件

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

1.3 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:\\develop\\apache-maven-3.5.0-bin\\apache-maven-3.5.0-bin\\apache-maven-3.5.0-bin\\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.xqx.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.xqx.mapper"
                         targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false"/>
        sqlMapGenerator>

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

        
        
        
        
        
        
        
        
        
        
        
        
        

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



    context>
generatorConfiguration>

1.4 spring-mybatis.xml :spring与mybatis整合的配置文件

xml version="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.xqx"/>

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

1.5 spring-context.xml :上下文配置文件

xml version="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="spring_mybatis.xml">import>
beans>

1.6 spring-mvc-xml: 配置Spring框架的一些关键组件和功能

xml version="1.0" encoding="UTF-8"?>
<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"
       xmlns="http://www.springframework.org/schema/beans"
       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.xqx"/>

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

1.7 web.xml 配置

xml version="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>

二、引入工具类

2.1 PageBean.java:

package com.xqx.utils;
 
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
 
public class PageBean implements Serializable {
 
	private static final long serialVersionUID = 2422581023658455731L;
 
	//页码
	private int page=1;
	//每页显示记录数
	private int rows=10;
	//总记录数
	private int total=0;
	//是否分页
	private boolean isPagination=true;
	//上一次的请求路径
	private String url;
	//获取所有的请求参数
	private Map<String,String[]> map;
	
	public PageBean() {
		super();
	}
	
	//设置请求参数
	public void setRequest(HttpServletRequest req) {
		String page=req.getParameter("page");
		String rows=req.getParameter("rows");
		String pagination=req.getParameter("pagination");
		this.setPage(page);
		this.setRows(rows);
		this.setPagination(pagination);
		this.url=req.getContextPath()+req.getServletPath();
		this.map=req.getParameterMap();
	}
	public String getUrl() {
		return url;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public Map<String, String[]> getMap() {
		return map;
	}
 
	public void setMap(Map<String, String[]> map) {
		this.map = map;
	}
 
	public int getPage() {
		return page;
	}
 
	public void setPage(int page) {
		this.page = page;
	}
	
	public void setPage(String page) {
		if(null!=page&&!"".equals(page.trim()))
			this.page = Integer.parseInt(page);
	}
 
	public int getRows() {
		return rows;
	}
 
	public void setRows(int rows) {
		this.rows = rows;
	}
	
	public void setRows(String rows) {
		if(null!=rows&&!"".equals(rows.trim()))
			this.rows = Integer.parseInt(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 isPagination;
	}
	
	public void setPagination(boolean isPagination) {
		this.isPagination = isPagination;
	}
	
	public void setPagination(String isPagination) {
		if(null!=isPagination&&!"".equals(isPagination.trim()))
			this.isPagination = Boolean.parseBoolean(isPagination);
	}
	
	/**
	 * 获取分页起始标记位置
	 * @return
	 */
	public int getStartIndex() {
		//(当前页码-1)*显示记录数
		return (this.getPage()-1)*this.rows;
	}
	
	/**
	 * 末页
	 * @return
	 */
	public int getMaxPage() {
		int totalpage=this.total/this.rows;
		if(this.total%this.rows!=0)
			totalpage++;
		return totalpage;
	}
	
	/**
	 * 下一页
	 * @return
	 */
	public int getNextPage() {
		int nextPage=this.page+1;
		if(this.page>=this.getMaxPage())
			nextPage=this.getMaxPage();
		return nextPage;
	}
	
	/**
	 * 上一页
	 * @return
	 */
	public int getPreivousPage() {
		int previousPage=this.page-1;
		if(previousPage<1)
			previousPage=1;
		return previousPage;
	}
 
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
				+ "]";
	}
}

2.2 PageTag.java

package com.xqx.utils;
 
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
 
public class PageBean implements Serializable {
 
	private static final long serialVersionUID = 2422581023658455731L;
 
	//页码
	private int page=1;
	//每页显示记录数
	private int rows=10;
	//总记录数
	private int total=0;
	//是否分页
	private boolean isPagination=true;
	//上一次的请求路径
	private String url;
	//获取所有的请求参数
	private Map<String,String[]> map;
	
	public PageBean() {
		super();
	}
	
	//设置请求参数
	public void setRequest(HttpServletRequest req) {
		String page=req.getParameter("page");
		String rows=req.getParameter("rows");
		String pagination=req.getParameter("pagination");
		this.setPage(page);
		this.setRows(rows);
		this.setPagination(pagination);
		this.url=req.getContextPath()+req.getServletPath();
		this.map=req.getParameterMap();
	}
	public String getUrl() {
		return url;
	}
 
	public void setUrl(String url) {
		this.url = url;
	}
 
	public Map<String, String[]> getMap() {
		return map;
	}
 
	public void setMap(Map<String, String[]> map) {
		this.map = map;
	}
 
	public int getPage() {
		return page;
	}
 
	public void setPage(int page) {
		this.page = page;
	}
	
	public void setPage(String page) {
		if(null!=page&&!"".equals(page.trim()))
			this.page = Integer.parseInt(page);
	}
 
	public int getRows() {
		return rows;
	}
 
	public void setRows(int rows) {
		this.rows = rows;
	}
	
	public void setRows(String rows) {
		if(null!=rows&&!"".equals(rows.trim()))
			this.rows = Integer.parseInt(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 isPagination;
	}
	
	public void setPagination(boolean isPagination) {
		this.isPagination = isPagination;
	}
	
	public void setPagination(String isPagination) {
		if(null!=isPagination&&!"".equals(isPagination.trim()))
			this.isPagination = Boolean.parseBoolean(isPagination);
	}
	
	/**
	 * 获取分页起始标记位置
	 * @return
	 */
	public int getStartIndex() {
		//(当前页码-1)*显示记录数
		return (this.getPage()-1)*this.rows;
	}
	
	/**
	 * 末页
	 * @return
	 */
	public int getMaxPage() {
		int totalpage=this.total/this.rows;
		if(this.total%this.rows!=0)
			totalpage++;
		return totalpage;
	}
	
	/**
	 * 下一页
	 * @return
	 */
	public int getNextPage() {
		int nextPage=this.page+1;
		if(this.page>=this.getMaxPage())
			nextPage=this.getMaxPage();
		return nextPage;
	}
	
	/**
	 * 上一页
	 * @return
	 */
	public int getPreivousPage() {
		int previousPage=this.page-1;
		if(previousPage<1)
			previousPage=1;
		return previousPage;
	}
 
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
				+ "]";
	}
}

2.3 xqx.tld


 
<taglib xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/j2ee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
        version="2.0">
 
    <description>xqx 1.1 core librarydescription>
    <display-name>xqx coredisplay-name>
    <tlib-version>1.1tlib-version>
    <short-name>xqxshort-name>
    <uri>http://jsp.veryedu.cnuri>
 
    <tag>
        <name>pagename>
        <tag-class>com.xqx.tag.PageTagtag-class>
        <body-content>JSPbody-content>
        <attribute>
            <name>pageBeanname>
            <required>truerequired>
            <rtexprvalue>truertexprvalue>
        attribute>
    tag>
 
taglib>

三、发布项目

3.1 逆向生成代码

利用generatorConfig生成代码
SpringMVC实现增删改查_第1张图片

3.2 发布项目

SpringMVC实现增删改查_第2张图片

四、实现增删改查

4.1 后端代码

biz

package com.xqx.biz;
 
import com.xqx.model;
import com.xqx.util.PageBean;
 
import java.util.List;
public interface booktBiz {
    int deleteByPrimaryKey(Integer cid);
 
    int insert(Book record);
 
    int insertSelective(Book record);
 
    List<Cat> selectByPrimaryKey(Integer cid);
 
    List<Cat>  selectLikePager(Book cat,PageBean pageBean);
 
    int updateByPrimaryKeySelective(Book record);
 
    int updateByPrimaryKey(Book record);
}
package com.xqx.biz;
 
import com.xqx.mapper.BookMapper;
import com.xqx.model;
import com.xqx.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.List;

@Service
public class BookBizImpl implements BookBiz {
    @Autowired
    private BookMapper BookBiz;
    @Override
    public int deleteByPrimaryKey(Integer cid) {
        return BookBiz.deleteByPrimaryKey(cid);
    }
 
    @Override
    public int insert(Book record) {
        return BookBiz.insert(record);
    }
 
    @Override
    public int insertSelective(Book record) {
        return BookBiz.insertSelective(record);
    }
 
    @Override
    public List<Book> selectByPrimaryKey(Integer cid) {
        return BookBiz.selectByPrimaryKey(cid);
    }
 
    @Override
    public List<Book> selectLikePager(Book Book, PageBean pageBean) {
 
        return BookBiz.selectLikePager(Book);
    }
 
    @Override
    public int updateByPrimaryKeySelective(Book record) {
        return BookBiz.updateByPrimaryKeySelective(record
        );
    }
 
    @Override
    public int updateByPrimaryKey(Book record) {
        return BookBiz.updateByPrimaryKey(record);
    }
}

web

package com.xqx.web;
 
import com.xqx.biz.BookBiz;
import com.xqx.model;
import com.xqx.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;

@Controller
@RequestMapping("/xqxssm")
@Slf4j
public class BookController {
    @Autowired
    private BookBiz BookBiz;
    //增加
    @RequestMapping("/add")
    public String add(Book Book){
        BookBiz.insertSelective(Book);
        return "redirect:list";
    }
    // 删除
    @RequestMapping("/del")
    public String del(Book Book){
        BookBiz.deleteByPrimaryKey(Book.getCid());
        return "redirect:list";
    }
    // 修改
    @RequestMapping("/upd")
    public String upd(Book Book){
        BookBiz.updateByPrimaryKeySelective(Book);
        return "redirect:list";
    }
    // 查询
    @RequestMapping("/list")
    public String list(Book Book, HttpServletRequest request){
        PageBean pageBean=new PageBean();
        List<Book> Books = BookBiz.selectLikePager(Book, pageBean);
        request.setAttribute("list",Books);
        request.setAttribute("pageBean",pageBean);
        return "index";
    }
    //数据回显
    @RequestMapping("/preSave")
    public String preSave(Book Book, Model model){
        if(Book!=null && Book.getCid()!=null){
            List<Book> Books = BookBiz.selectByPrimaryKey(Book.getCid());
            model.addAttribute("b",Books.get(0));
        }
        return "edit";
    }
 
}

4.2 前端代码

booList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="x" uri="http://jsp.xqx.cn"%>
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=ISO-8859-1">
<title>Insert title heretitle>
<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;
}
.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 }/book.action?methodName=list" method="post">
		<div class="form-group mb-2">
			<input type="text" class="form-control-plaintext" name="bname"
				placeholder="请输入书籍名称">
		div>
		<button type="submit" class="btn btn-primary mb-2">查询button>
				<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book.action?methodName=toEdit">新增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 items="${list }" var="b">
			<tr>
				<td>${b.bid }td>
				<td>${b.bname }td>
				<td>${b.price }td>
				<td> <a href="${pageContext.request.contextPath }/book.action?methodName=toEdit&bid=${b.bid}">修改a>
					<a href="${pageContext.request.contextPath }/book.action?methodName=delete&bid=${b.bid}">删除a>td>
			tr>
			c:forEach>

		tbody>
	table>
	
 	<x:page pageBean="${pageBean }">x:page>  
body>
html>

bookEdit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.xqx.cn" prefix="x"%>	
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>	
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">
<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>
head>
<body>
	<form class="form-inline"
		action="${pageContext.request.contextPath }/book.action?methodName=${empty edit ? 'add' : 'edit'}" method="post">
		书籍ID:<input type="text" name="bid" value="${edit.bid }"><br>
		书籍名称:<input type="text" name="bname" value="${edit.bname }"><br>
		书籍价格:<input type="text" name="price" value="${edit.price }"><br>
		<input type="submit">
	form>


body>
html>

4.3 运行结果

查询
SpringMVC实现增删改查_第3张图片

新增
SpringMVC实现增删改查_第4张图片
SpringMVC实现增删改查_第5张图片

修改
SpringMVC实现增删改查_第6张图片

你可能感兴趣的:(sql,mybatis,java)