页面的增删改查小案例

171 阅读3分钟

BrandMapper接口

package com.itheima.mapper;

import com.itheima.pojo.Brand;

import java.util.List;

public interface BrandMapper {
    List<Brand> selectAll(); //查询所有数据进行展示 封装成一个List集合
    void add(Brand brand); // 添加功能 根据request获取的数据进行封装 存到数据库中
    void deleteById(int id); // 删除功能 根据request获取的id进行删除
    Brand select(int id); // 根据id查询数据封装成一个Brand对象将Brand对象的信息回显到修改页面中
    void update(Brand brand);// 修改数据 根据request获取的数据封装成Brand对象,对数据库信息进行修改
}

BrandMapper.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">
<!--namespace:名称空间 -->
<mapper namespace="com.itheima.mapper.BrandMapper">
    <resultMap id="map" type="brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>
    <insert id="add">
        insert into tb_brand (id, brand_name, company_name, ordered, description, status)
        values (null,#{brandName},#{companyName},#{ordered},#{description},#{status});
    </insert>
    <update id="update">
        update tb_brand
        set id = #{id},brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status}
        where id = #{id};
    </update>
    <delete id="deleteById">
        delete
        from tb_brand
        where id = #{id};
    </delete>


    <select id="selectAll" resultMap="map">
        select *
        from tb_brand;
    </select>
    <select id="select" resultMap="map">
        select *
        from tb_brand
        where id = #{id};
    </select>
</mapper>

Brand实体类

package com.itheima.pojo;

public class Brand {
    private Integer id;
    private String brandName;
    private String companyName;
    private Integer ordered;
    private String description;
    private Integer status;

    public Integer getId() {
        return id;
    }

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

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brandName='" + brandName + ''' +
                ", companyName='" + companyName + ''' +
                ", ordered=" + ordered +
                ", description='" + description + ''' +
                ", status=" + status +
                '}';
    }
}

BrandService

package com.itheima.service;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    // 查询所有进行展示
    public List<Brand> selectAll(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.selectAll();
        sqlSession.close();
        return brands;
    }
    // 添加
    public void add(Brand brand){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.add(brand);
        sqlSession.commit();
        sqlSession.close();
    }
    // 根据id删除数据
    public void deleteById(int id){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.deleteById(id);
        sqlSession.commit();
        sqlSession.close();
    }
    // 根据id查询数据 用于数据的回显
    public Brand select(int id){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        Brand brand = mapper.select(id);
        sqlSession.close();
        return brand;
    }
    // 修改数据
    public void update(Brand brand){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.update(brand);
        sqlSession.commit();
        sqlSession.close();
    }
}

AddServlet(添加)

package com.itheima.web;

import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
    private   BrandService brandService = new BrandService();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 修改字符集为utf-8
        request.setCharacterEncoding("utf-8");
        //获取数据 因为id是在数据库进行自增长且唯一所以不需要获取
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        // 将获取的数据封装成Brand对象
        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));

        //调用brandService的add方法 将Brand对象添加到数据库
        brandService.add(brand);
        // 访问selectAllServlet重新展示数据
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }


}

DeleteByIdServlet (删除)

package com.itheima.web;

import com.itheima.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/deleteByIdServlet")
public class DeleteByIdServlet extends HttpServlet {
    private   BrandService brandService = new BrandService();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //获取id
        String id = request.getParameter("id");
        //调用brandService的deleteById方法 根据获取到的id进行删除
        brandService.deleteById(Integer.parseInt(id));
        //访问selectAllServlet重新展示页面数据
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }


}

SelectServlet(查询数据,用于修改时数据的回显)

package com.itheima.web;

import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/selectServlet")
public class SelectServlet extends HttpServlet {
    private  BrandService brandService = new BrandService();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取id
        String id = request.getParameter("id");
        //根据id查询Brand对象
        Brand brand = brandService.select(Integer.parseInt(id));
        // 将brand对象存到request域中
        request.setAttribute("brand",brand);
        // 访问update.jsp将brand对象回显到添加页面中
        request.getRequestDispatcher("/update.jsp").forward(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

UpdateServlet (修改)

package com.itheima.web;

import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {
    private BrandService brandService = new BrandService();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 修改字符集为utf-8
        request.setCharacterEncoding("utf-8");
        //获取数据
        String id = request.getParameter("id");//根据id修改所有获取id
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        Brand brand = new Brand();
        //将获取的数据封装成Brand对象
        brand.setId(Integer.parseInt(id));
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));

        // 调用brandService里的update方法 对数据库的数据进行修改
        brandService.update(brand);
        // 访问selectAllServlet重新展示数据
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }


}

SelectAllServlet(查询)

package com.itheima.web;

import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
    private BrandService brandService = new BrandService();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //调用brandService的selectAll方法 将数据库数据封装成List集合
        List<Brand> brands = brandService.selectAll();
        // 将集合存到request域中
        request.setAttribute("brands",brands);
        //访问brand.jsp将List集合展示到页面上
        request.getRequestDispatcher("/brand.jsp").forward(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }


}

展示页面

<%--
  Created by IntelliJ IDEA.
  User: WY
  Date: 2022/11/26
  Time: 16:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="button" value="新增" id="add"><br>
<hr>
<table border="1" cellspacing="0" width="80%">
    <tr>
        <th>序号</th>
        <th>品牌名称</th>
        <th>企业名称</th>
        <th>排序</th>
        <th>品牌介绍</th>
        <th>状态</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${brands}" var="brand" varStatus="status">
        <tr align="center">
            <td>${status.count}</td>
            <td>${brand.brandName}</td>
            <td>${brand.companyName}</td>
            <td>${brand.ordered}</td>
            <td>${brand.description}</td>
            <c:if test="${brand.status == 1}">
                <td>启用</td>
            </c:if>
            <c:if test="${brand.status != 1}">
                <td>禁用</td>
            </c:if>
            <td><a href="/Test/selectServlet?id=${brand.id}">修改</a> <a href="/Test/deleteByIdServlet?id=${brand.id}">删除</a></td>
        </tr>
    </c:forEach>
</table>
<script>
    document.getElementById("add").onclick = function (){
        location.href = "/Test/add.jsp"
    }
</script>
</body>
</html>

添加页面

<%--
  Created by IntelliJ IDEA.
  User: WY
  Date: 2022/12/3
  Time: 11:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/Test/addServlet" method="post">
  <input name="brandName"><br>
  <input name="companyName"><br>
  <input name="ordered"><br>
  <textarea cols="5" rows="6" name="description"></textarea><br>
  <input type="radio" name="status" value="1">启用
  <input type="radio" name="status" value="0">禁用
  <input type="submit">
</form>
</body>
</html>

修改页面

<%--
  Created by IntelliJ IDEA.
  User: WY
  Date: 2022/11/28
  Time: 16:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/Test/updateServlet" method="post">
    <input type="hidden" name="id" value="${brand.id}">
    品牌名称:<input name="brandName" value="${brand.brandName}"><br>
    公司名称:<input name="companyName" value="${brand.companyName}"><br>
    排序:<input name="ordered" value="${brand.ordered}"><br>
    品牌介绍:<textarea cols="5" rows="6" name="description">${brand.description}</textarea><br>
    状态:
    <c:if test="${brand.status == 1}">
        <input type="radio" name="status" value="1" checked="checked">启用
        <input type="radio" name="status" value="0">禁用
    </c:if>
    <c:if test="${brand.status == 0}">
        <input type="radio" name="status" value="1" >启用
        <input type="radio" name="status" value="0" checked="checked">禁用
    </c:if>
    <br>
    <input type="submit">
</form>
</body>
</html>

index

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="/Test/selectAllServlet">查询所有</a>
</body>
</html>