SpringMVC系列(三)之CRUD增删改查

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: SpringMVC系列(三)之CRUD增删改查

SpringMVC实现增删改查

1. 导入相关依赖

pom.xml

<?xml version="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.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>xisslzy_ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>xisslzy_ssm Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
    <!--添加jar包依赖-->
    <!--1.spring 5.0.2.RELEASE相关-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!--2.mybatis相关-->
    <mybatis.version>3.4.5</mybatis.version>
    <!--mysql-->
    <mysql.version>5.1.44</mysql.version>
    <!--pagehelper分页jar依赖-->
    <pagehelper.version>5.1.2</pagehelper.version>
    <!--mybatis与spring集成jar依赖-->
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
    <!--3.dbcp2连接池相关 druid-->
    <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
    <commons.pool2.version>2.4.3</commons.pool2.version>
    <!--4.log日志相关-->
    <log4j2.version>2.9.1</log4j2.version>
    <!--5.其他-->
    <junit.version>4.12</junit.version>
    <servlet.version>4.0.0</servlet.version>
    <lombok.version>1.18.2</lombok.version>
  </properties>
  <dependencies>
    <!--1.spring相关-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--2.mybatis相关-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!--pagehelper分页插件jar包依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>${pagehelper.version}</version>
    </dependency>
    <!--mybatis与spring集成jar包依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>
    <!--3.dbcp2连接池相关-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>${commons.dbcp2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>${commons.pool2.version}</version>
    </dependency>
    <!--4.log日志相关依赖-->
    <!--核心log4j2jar包-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--5.其他-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
<!--      <scope>test</scope>-->
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- jsp依赖-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>xisslzy_ssm</finalName>
    <resources>
      <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>jdbc.properties</include>
          <include>*.xml</include>
        </includes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <dependencies>
          <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
          </dependency>
        </dependencies>
        <configuration>
          <overwrite>true</overwrite>
        </configuration>
      </plugin>
      <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
  </build>
</project>

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 Application</display-name>
  <!-- Spring和web项目集成start -->
  <!-- spring上下文配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context.xml</param-value>
  </context-param>
  <!-- 读取Spring上下文的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- Spring和web项目集成end -->
  <!-- 中文乱码处理 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- Spring MVC servlet -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <!--web.xml 3.0的新特性,是否支持异步-->
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

2. 添加配置文件

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

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!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"/>
    <!--指定数据库jdbc驱动jar包的位置-->
    <classPathEntry location="D:\\maven\\mvn_repository\\mysql\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
    <!-- 一个数据库一个context -->
    <context id="infoGuardian">
        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
            <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>
        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 01 指定javaBean生成的位置 -->
        <!-- targetPackage:指定生成的model生成所在的包名 -->
        <!-- targetProject:指定在该项目下所在的路径  -->
        <javaModelGenerator targetPackage="com.xissl.model"
                            targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="false"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>
        <!-- 02 指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.xissl.mapper"
                         targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 03 生成XxxMapper接口 -->
        <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
        <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
        <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
        <javaClientGenerator targetPackage="com.xissl.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <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>

spring-mvc.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"
       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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.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">
    <!--1) 扫描com.xissl及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <context:component-scan base-package="com.xissl"/>
    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <mvc:annotation-driven />
    <!--3) 创建ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
<!--    处理controller层发送请求到biz,会经过切面的拦截处理-->
    <aop:aspectj-autoproxy/>
</beans>

3. 逆向生成对应的类

实体类

package com.xissl.model;
import lombok.ToString;
@ToString
public class Student {
    private String sid;
    private String sname;
    private String sage;
    private String ssex;
    public Student(String sid, String sname, String sage, String ssex) {
        this.sid = sid;
        this.sname = sname;
        this.sage = sage;
        this.ssex = ssex;
    }
    public Student() {
        super();
    }
    public String getSid() {
        return sid;
    }
    public void setSid(String sid) {
        this.sid = sid;
    }
    public String getSname() {
        return sname;
    }
    public void setSname(String sname) {
        this.sname = sname;
    }
    public String getSage() {
        return sage;
    }
    public void setSage(String sage) {
        this.sage = sage;
    }
    public String getSsex() {
        return ssex;
    }
    public void setSsex(String ssex) {
        this.ssex = ssex;
    }
}

mapper接口

package com.xissl.mapper;
import com.xissl.model.Student;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface StudentMapper {
    int deleteByPrimaryKey(String sid);
    int insert(Student record);
    int insertSelective(Student record);
    Student selectByPrimaryKey(String sid);
    int updateByPrimaryKeySelective(Student record);
    int updateByPrimaryKey(Student record);
    List<Student> listPager(Student student);
}

sql映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xissl.mapper.StudentMapper" >
  <resultMap id="BaseResultMap" type="com.xissl.model.Student" >
    <constructor >
      <idArg column="sid" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="sname" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="sage" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="ssex" jdbcType="VARCHAR" javaType="java.lang.String" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    sid, sname, sage, ssex
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from t_mysql_student
    where sid = #{sid,jdbcType=VARCHAR}
  </select>
  <select id="listPager" resultType="com.xissl.model.Student" parameterType="com.xissl.model.Student" >
    select
    <include refid="Base_Column_List" />
    from t_mysql_student
    <where>
      <if test="sname != null">
        and sname like concat('%',#{sname},'%')
      </if>
    </where>
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from t_mysql_student
    where sid = #{sid,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.xissl.model.Student" >
    insert into t_mysql_student (sid, sname, sage, 
      ssex)
    values (#{sid,jdbcType=VARCHAR}, #{sname,jdbcType=VARCHAR}, #{sage,jdbcType=VARCHAR}, 
      #{ssex,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.xissl.model.Student" >
    insert into t_mysql_student
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="sid != null" >
        sid,
      </if>
      <if test="sname != null" >
        sname,
      </if>
      <if test="sage != null" >
        sage,
      </if>
      <if test="ssex != null" >
        ssex,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="sid != null" >
        #{sid,jdbcType=VARCHAR},
      </if>
      <if test="sname != null" >
        #{sname,jdbcType=VARCHAR},
      </if>
      <if test="sage != null" >
        #{sage,jdbcType=VARCHAR},
      </if>
      <if test="ssex != null" >
        #{ssex,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.xissl.model.Student" >
    update t_mysql_student
    <set >
      <if test="sname != null" >
        sname = #{sname,jdbcType=VARCHAR},
      </if>
      <if test="sage != null" >
        sage = #{sage,jdbcType=VARCHAR},
      </if>
      <if test="ssex != null" >
        ssex = #{ssex,jdbcType=VARCHAR},
      </if>
    </set>
    where sid = #{sid,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.xissl.model.Student" >
    update t_mysql_student
    set sname = #{sname,jdbcType=VARCHAR},
      sage = #{sage,jdbcType=VARCHAR},
      ssex = #{ssex,jdbcType=VARCHAR}
    where sid = #{sid,jdbcType=VARCHAR}
  </update>
</mapper>

4. 后台代码编写

业务逻辑层

package com.xissl.biz;
import com.xissl.model.Student;
import com.xissl.utils.PageBean;
import java.util.List;
public interface StudentBiz {
    int deleteByPrimaryKey(String sid);
    int insert(Student record);
    int insertSelective(Student record);
    Student selectByPrimaryKey(String sid);
    int updateByPrimaryKeySelective(Student record);
    int updateByPrimaryKey(Student record);
    List<Student> listPager(Student student, PageBean pageBean);
}

实现接口

package com.xissl.biz.impl;
import com.xissl.biz.StudentBiz;
import com.xissl.mapper.StudentMapper;
import com.xissl.model.Student;
import com.xissl.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * @author xissl
 * @create 2023-09-07 16:07
 */
@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> listPager(Student student, PageBean pageBean) {
        return studentMapper.listPager(student);
    }
}

controller层

package com.xissl.web;
import com.xissl.biz.StudentBiz;
import com.xissl.model.Student;
import com.xissl.utils.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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
 * @author xissl
 * @create 2023-09-07 16:59
 */
@Controller
@RequestMapping("/stu")
public class StudentController {
    @Autowired
    private StudentBiz studentBiz;
//    增
    @RequestMapping("/add")
    public String add(Student student){
        int i = studentBiz.insertSelective(student);
        return "redirect:list";
    }
//    删
    @RequestMapping("/del")
    public String del(String sid){
        studentBiz.deleteByPrimaryKey(sid);
        return "redirect:/stu/list";
    }
//    改
    @RequestMapping("/edit")
    public String edit(Student student){
        studentBiz.updateByPrimaryKey(student);
        return "redirect:list";
    }
//    查
    @RequestMapping("/list")
    public String list(Student student, HttpServletRequest request){
//        Student student是前台用来给后台传递参数的
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        List<Student> students = studentBiz.listPager(student, pageBean);
        request.setAttribute("list",students);
        request.setAttribute("pageBean",pageBean);
        return "stu/list";
    }
//    数据回显
    @RequestMapping("/preSave")
    public String preSave(Student student, Model model){
        if(student != null && student.getSid()!=null){
            Student s = studentBiz.selectByPrimaryKey(student.getSid());
            model.addAttribute("s",s);
        }
        return "stu/edit";
    }
}

5. 前台代码编写

list.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 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 }/stu/list" method="post">
    <div class="form-group mb-2">
        <input type="text" class="form-control-plaintext" name="sname"
               placeholder="请输入学生姓名">
        <!--      <input name="rows" value="20" type="hidden"> -->
        <!-- 不想分页 -->
<%--        <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 }/stu/preSave">新增</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="b" items="${list }">
        <tr>
            <td>${b.sid }</td>
            <td>${b.sname }</td>
            <td>${b.sage }</td>
            <td>${b.ssex }</td>
            <td>
                <a href="${pageContext.request.contextPath }/stu/preSave?sid=${b.sid}">修改</a>
                <a href="${pageContext.request.contextPath }/stu/del?sid=${b.sid}">删除</a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
</table>
<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>

edit.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/${empty s ? 'stu/add' : 'stu/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>
相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
12月前
|
Java 数据库连接 数据库
SpringMVC之增删改查(CRUD)项目模拟
SpringMVC之增删改查(CRUD)项目模拟
91 0
|
6月前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
|
3月前
|
前端开发 应用服务中间件 数据库
SpringMVC入门到实战------八、RESTful案例。SpringMVC+thymeleaf+BootStrap+RestFul实现员工信息的增删改查
这篇文章通过一个具体的项目案例,详细讲解了如何使用SpringMVC、Thymeleaf、Bootstrap以及RESTful风格接口来实现员工信息的增删改查功能。文章提供了项目结构、配置文件、控制器、数据访问对象、实体类和前端页面的完整源码,并展示了实现效果的截图。项目的目的是锻炼使用RESTful风格的接口开发,虽然数据是假数据并未连接数据库,但提供了一个很好的实践机会。文章最后强调了这一章节主要是为了练习RESTful,其他方面暂不考虑。
SpringMVC入门到实战------八、RESTful案例。SpringMVC+thymeleaf+BootStrap+RestFul实现员工信息的增删改查
|
6月前
|
前端开发 Java 网络安全
ssh(Spring+Spring mvc+hibernate)简单增删改查案例
ssh(Spring+Spring mvc+hibernate)简单增删改查案例
|
11月前
|
前端开发 数据库
SpringMVC之CRUD(增删改查)
SpringMVC之CRUD(增删改查)
49 0
|
11月前
|
数据库
SpringMVC之CRUD------增删改查
SpringMVC之CRUD------增删改查
54 0
|
11月前
|
前端开发 Java 数据库连接
SpringMVC实现增删改查
SpringMVC实现增删改查
70 0
|
12月前
|
前端开发 数据库连接 数据库
SpringMVC实现增删改查(CRUD)--全面详细讲解
SpringMVC实现增删改查(CRUD)--全面详细讲解
100 0
|
12月前
|
XML Java 数据格式
学习SpringMvc第三战-利用SpringMvc实现CRUD
学习SpringMvc第三战-利用SpringMvc实现CRUD
|
6月前
|
设计模式 前端开发 JavaScript
Spring MVC(一)【什么是Spring MVC】
Spring MVC(一)【什么是Spring MVC】