SpringBoot入门之JSP页面Form表单实现增删改查

项目GitHub传送门

写在前面:
使用SpringBoot创建项目,用SpringMVC的模式,用jsp做为前端显示,只是创建一个示例。将SpringMVC的项目迁移到SpringBoot创建的项目中,真正需要上线的项目不推荐使用这种方式。

技术点:

  1. Spring Boot
  2. Spring
  3. Jsp
  4. Mybatis
  5. MySQL

一、项目结构

在这里插入图片描述

二、数据库

数据库名:ceshi

CREATE TABLE `goods`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `price` decimal(10, 2) NULL DEFAULT NULL,
  `makedate` datetime(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 15 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Compact;

三、配置文件

1. pom.xml

可在创建SpringBoot项目时勾选Spring Web,Mybatis Framework,MySQL Driver,创建好项目后添加提供jsp支持的两个坐标

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.aaa</groupId>
    <artifactId>springboot-form</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-form</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.0.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <!-- spring web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- jsp -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <!-- spring-test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. application.properties

需要将datasource中的配置更改为自己数据库的配置

spring.application.name=springboot-form
# 配置服务器启动端口号
server.port=8090
# mybatis 映射文件所处位置
mybatis.mapper-locations=classpath:mapper/*.xml
# mybatis 连接数据库接口所处位置
mybatis.type-aliases-package=com.aaa.springbootform.mapper

# 配置jsp文件前后缀
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
# 配置datasource
spring.datasource.url=jdbc:mysql://localhost:3306/ceshi?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=****
spring.datasource.password=****

四、后端文件

1. Goods.java

package com.aaa.springbootform.entity;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class Goods {

  private long id;
  private String name;
  private double price;
  @DateTimeFormat(pattern="yyyy-MM-dd")
  private Date makedate;


  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }


  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }


  public double getPrice() {
    return price;
  }

  public void setPrice(double price) {
    this.price = price;
  }



  public Date getMakedate() {
    return makedate;
  }

  public void setMakedate(Date makedate) {
    this.makedate = makedate;
  }

  public void setMakedate(String makedate){
    String[] strings = makedate.split("-");
    Date dates = new Date(Integer.valueOf(strings[0]),Integer.valueOf(strings[1]),Integer.valueOf(strings[2]));
    System.out.println(dates);
    this.makedate = dates;
  }
  @Override
  public String toString() {
    return "Goods{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + ", makedate=" + makedate + '}';
  }
}

2. GoodsMapper.java

package com.aaa.springbootform.mapper;

import com.aaa.springbootform.entity.Goods;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface GoodsMapper {
    int insert(Goods goods);
    int update(Goods goods);
    int delete(Goods goods);
    List<Goods> findAll();
    Goods findOne(Goods goods);
}

3. GoodsService.java

package com.aaa.springbootform.service;

import com.aaa.springbootform.entity.Goods;

import java.util.List;

public interface GoodsService {
    int insert(Goods goods);

    int update(Goods goods);

    int delete(Goods goods);

    List<Goods> findAll();

    Goods findOne(Goods goods);
}

4. GoodsServiceImpl.java

package com.aaa.springbootform.service.impl;

import com.aaa.springbootform.entity.Goods;
import com.aaa.springbootform.mapper.GoodsMapper;
import com.aaa.springbootform.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired GoodsMapper mapper;
    @Override
    public int insert(Goods goods) {
        return mapper.insert(goods);
    }

    @Override
    public int update(Goods goods) {
        return mapper.update(goods);
    }

    @Override
    public int delete(Goods goods) {
        return mapper.delete(goods);
    }

    @Override
    public List<Goods> findAll() {
        return mapper.findAll();
    }

    @Override
    public Goods findOne(Goods goods) {
        return mapper.findOne(goods);
    }
}

5. GoodsController.java

package com.aaa.springbootform.controller;

import com.aaa.springbootform.entity.Goods;
import com.aaa.springbootform.service.GoodsService;
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 org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("goods")
public class GoodsController {
    @Autowired GoodsService service;

    @RequestMapping("findAll")
    public String findAll(Model model){
        model.addAttribute("list",service.findAll());
        return "list";
    }

    @RequestMapping("toAdd")
    public String toAdd(){
        return "add";
    }

    @RequestMapping("add")
    public ModelAndView add(Goods goods){
        service.insert(goods);
        ModelAndView modelAndView = new ModelAndView();
        return new ModelAndView("redirect:/goods/findAll");
    }

    @RequestMapping("toUpdate")
    public String toUpdate(Model model, Goods goods){
        Goods goods1 = service.findOne(goods);
        model.addAttribute("goods",goods1);
        return "update";
    }

    @RequestMapping("update")
    public ModelAndView update(Goods goods){
        service.update(goods);
        ModelAndView modelAndView = new ModelAndView();
        return new ModelAndView("redirect:/goods/findAll");
    }

    @RequestMapping("delete")
    public ModelAndView delete(Goods goods){
        service.delete(goods);
        ModelAndView modelAndView = new ModelAndView();
        return new ModelAndView("redirect:/goods/findAll");
    }
}

6. SpringbootFormApplication

package com.aaa.springbootform;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootFormApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootFormApplication.class, args);
    }
}

7. GoodsDao.xml

<?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.aaa.springbootform.mapper.GoodsMapper">
    <select id="findAll" resultType="com.aaa.springbootform.entity.Goods">
        select * from goods;
    </select>

    <insert id="insert" parameterType="com.aaa.springbootform.entity.Goods" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        insert into goods(name, price, makedate) values (#{name},#{price},#{makedate});
    </insert>

    <select id="findOne" resultType="com.aaa.springbootform.entity.Goods" parameterType="com.aaa.springbootform.entity.Goods">
        select * from goods where id = #{id};
    </select>

    <update id="update" parameterType="com.aaa.springbootform.entity.Goods">
        update goods set name = #{name},price=#{price},makedate=#{makedate} where id=#{id};
    </update>

    <delete id="delete" parameterType="com.aaa.springbootform.entity.Goods">
        delete from goods where id=#{id}
    </delete>
</mapper>

前端文件

1. index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<% response.sendRedirect("/goods/findAll");%>

2. list.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 uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<%@ page  isELIgnored="false"%>
<%request.setAttribute("pn", pageContext.getServletContext().getContextPath());%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>商品信息</title>
</head>
<body>
<table border="1" cellpadding="10" cellspacing="0">
    <thead>
    <caption><h1>商品管理</h1></caption>
    <tr>
        <th>名称</th>
        <th>价格</th>
        <th>生产日期</th>
        <th><a href="${pn }/goods/toAdd">添加</a></th>
        <th colspan="2">操作</th>
    </tr>
    </thead>
    <c:forEach items="${list }" var="map">
        <tr>
            <td>${map.name }</td>
            <td>${map.price }</td>
            <td><fmt:formatDate value='${map.makedate }' pattern='yyyy-MM-dd' /> </td>
            <td><a href="${pn }/goods/toUpdate?id=${map.id }">修改</a></td>
            <td><a href="JavaScript:void(0)" onclick="showDelete(${map.id })">删除</a></td>
        </tr>
    </c:forEach>
</table>
<script type="text/javascript">
    function showDelete(id) {
        var flag = confirm("确定要删除么?");
        if (flag) {
            location.href = "${pn }/goods/delete?id=" + id;
        }
    }
</script>
</body>
</html>

3. add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page  isELIgnored="false"%>
<%request.setAttribute("pn", pageContext.getServletContext().getContextPath());%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>添加商品信息</title>
</head>
<body>
<h2>添加商品信息</h2>
<form action="${pn }/goods/add" method="post">
    <table class="table table-hover">
        <tr>
            <td>商品名称</td>
            <td><input type="text" name="name"/></td>
        </tr>
        <tr>
            <td>商品价格</td>
            <td><input type="number" name="price"/></td>
        </tr>
        <tr>
            <td>生产日期</td>
            <td><input type="date" name="makedate"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="添加"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

4. update.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 uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ page  isELIgnored="false"%>
<%request.setAttribute("pn", pageContext.getServletContext().getContextPath());%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>修改商品信息</title>
</head>
<body>
<h2>修改商品信息</h2>
<form action="${pn }/goods/update?id=${goods.id}" method="post">
    <table class="table table-hover">
        <tr>
            <td>商品名称</td>
            <td><input type="text" name="name" value="${goods.name }"/></td>
        </tr>
        <tr>
            <td>商品价格</td>
            <td><input type="number" name="price" value="${goods.price }"/></td>
        </tr>
        <tr>
            <td>生产日期</td>
            <td><input type="date" name="makedate" value="${goods.makedate}"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="修改"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>
  • 1
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值