首页 > 编程语言 >JAVA的第一个项目---品牌增删改查的案例

JAVA的第一个项目---品牌增删改查的案例

时间:2024-11-01 19:59:53浏览次数:1  
标签:JAVA String brand req 改查 public --- import id

这几周通过对javaweb的持续学习,终于做出了第一个项目
界面比较简单,如下:

通过超链接来查询表单的所有内容

其下有新增,修改和删除三个按钮
新增页面,点击提交增加数据

修改页面用到了和新增一样的界面,通过id回显显示选中的品牌

删除键进行删除直接回到查询表单界面

项目创建分为三层架构:
1、dao层中BrandMapper进行定义初始的增删改查方法,并使用注解的方式实现对数据库的增删改查的SQL语句。
2、Service层中调用brandMapper的方法。
3、Web层中接收数据,封装brand对象等操作,然后调用Service层中的方法,最后转发到相应的jsp页面。

代码如下:
1、首先是javabeen的封装基本属性

package com.stuwhx.pojo;

/**
 * 品牌实体类
 */

public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;


    public Brand() {
    }

    public Brand(Integer id, String brandName, String companyName, String description) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.description = description;
    }

    public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = 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 +
                '}';
    }
}

mapper中定义增删改查的方法并通过注解方式定义sql语句

package com.stuwhx.mapper;

import com.stuwhx.pojo.Brand;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface BrandMapper {

    /**
     * 查询所有
     * @return
     */
    @Select("select * from tb_brand")
    @ResultMap("brandResultMap")
    List<Brand> selectAll();

    @Insert("INSERT into tb_brand values (null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    void add(Brand brand);

    @Select("select * from tb_brand where id =#{id}")
    @ResultMap("brandResultMap")
    Brand selectById(int id);

    /**
     * 修改
     * @param brand
     */
    @Update("update tb_brand set brand_name = #{brandName},company_name = #{companyName},ordered = #{ordered},description = #{description},status = #{status} where id = #{id}")
    void update(Brand brand);

    @Delete("delete from tb_brand where id = #{id}")
    void deleteById(int id);

}

还有与之对应的mapper.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.stuwhx.mapper.BrandMapper">

    <resultMap id="brandResultMap" type="brand">

        <result column="brand_name" property="brandName"></result>
        <result column="company_name" property="companyName"></result>
    </resultMap>


</mapper>

2、util工具类定义获取`sqlSessionFactory工厂

package com.stuwhx.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        //静态代码块会随着类的加载而自动执行,且只执行一次

        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

3、Service层中调用mapper的方法

package com.stuwhx.service;

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

import java.util.List;

public class BrandService {

    //调用BrandMapper.selectAll()
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();


    /**
     * 查询所有
     * @return
     */

        public List<Brand> selectAll(){

            //获取sqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();

            //获取BrandMapper对象
            BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

            //调用方法
            List<Brand> brands = brandMapper.selectAll();

            sqlSession.close();

            return brands;


        }

    /**
     * 添加
     * @param brand
     */
    public void add(Brand brand){

            //获取sqlSession对象
            SqlSession sqlSession = sqlSessionFactory.openSession();

            //获取BrandMapper对象
            BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

            //调用添加方法
            brandMapper.add(brand);

            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }

    /**
     * 根据id查询
     * @return
     */
    public Brand selectById(int id){

        //获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //获取BrandMapper对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //调用方法
        Brand brand = brandMapper.selectById(id);

        sqlSession.close();

        return brand;


    }

    /**
     * 修改
     * @param brand
     */
    public void update(Brand brand){

        //获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //获取BrandMapper对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //调用添加方法
        brandMapper.update(brand);

        //提交事务
        sqlSession.commit();
        sqlSession.close();
    }

    /**
     * 根据id删除
     * @param id
     */
    public void delete(int id){
        //获取sqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //获取BrandMapper对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //调用添加方法
        brandMapper.deleteById(id);

        sqlSession.commit();
        sqlSession.close();
    }


}

4、Web层使用servlet获取数据并进行封装和转发
添加

package com.stuwhx.web;

import com.stuwhx.pojo.Brand;
import com.stuwhx.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 service = new BrandService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        //接受表单提交的数据,封装
        String brandName = req.getParameter("brandName");
        String companyName = req.getParameter("companyName");
        String ordered = req.getParameter("ordered");
        String description = req.getParameter("description");
        String status = req.getParameter("status");


        Brand brand = new Brand();

        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));

        //调用service
        service.add(brand);

        //转发到查询所有
        req.getRequestDispatcher("/selectAllServlet").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

删除

package com.stuwhx.web;

import com.stuwhx.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("/deleteServlet")
public class DeleteServlet extends HttpServlet {

    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String id = req.getParameter("id");

        service.delete(Integer.parseInt(id));

        req.setAttribute("id",id);

        req.getRequestDispatcher("/selectAllServlet").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

修改,修改需要用id查询回显进行修改数据的显示

package com.stuwhx.web;

import com.stuwhx.pojo.Brand;
import com.stuwhx.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 service = new BrandService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        //接受表单提交的数据,封装
        String id = req.getParameter("id");
        String brandName = req.getParameter("brandName");
        String companyName = req.getParameter("companyName");
        String ordered = req.getParameter("ordered");
        String description = req.getParameter("description");
        String status = req.getParameter("status");


        Brand brand = new 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));

        //调用service
        service.update(brand);

        //转发到查询所有
        req.getRequestDispatcher("/selectAllServlet").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

package com.stuwhx.web;

import com.stuwhx.pojo.Brand;
import com.stuwhx.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 service = new BrandService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        //接受表单提交的数据,封装
        String id = req.getParameter("id");
        String brandName = req.getParameter("brandName");
        String companyName = req.getParameter("companyName");
        String ordered = req.getParameter("ordered");
        String description = req.getParameter("description");
        String status = req.getParameter("status");


        Brand brand = new 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));

        //调用service
        service.update(brand);

        //转发到查询所有
        req.getRequestDispatcher("/selectAllServlet").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

查询所有

package com.stuwhx.web;

import com.stuwhx.pojo.Brand;
import com.stuwhx.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 service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //调用BrandService对象
        List<Brand> brands = service.selectAll();

        //存入Request域中
        req.setAttribute("brands",brands);

        //转发brand.jsp
        req.getRequestDispatcher("/brand.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

前端通过jsp实现
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


    <a href="/brand-demo/selectAllServlet">查询所有</a>
</body>
</html>

addBrand.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>添加品牌</title>
</head>
<body>
<h3>添加品牌</h3>
<form action="/brand-demo/addServlet" method="post">
    品牌名称:<input name="brandName"><br>
    企业名称:<input name="companyName"><br>
    排序:<input name="ordered"><br>
    描述信息:<textarea rows="5" cols="20" name="description"></textarea><br>
    状态:
    <input type="radio" name="status" value="0">禁用
    <input type="radio" name="status" value="1">启用<br>

    <input type="submit" value="提交">
</form>
</body>
</html>

brand.jsp

<%--
  Created by IntelliJ IDEA.
  User: wuhaoxiang
  Date: 2024/10/31
  Time: 20:49
  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 lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<input type="button" value="新增" id = "add"><br>

<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="/brand-demo/selectByIdServlet?id=${brand.id}">修改</a> <a href="/brand-demo/deleteServlet?id=${brand.id}">删除</a> </td>
        </tr>
    </c:forEach>
</table>

<script>
    document.getElementById("add").onclick = function (){
        location.href = "/brand-demo/addBrand.jsp";
    }
</script>
</body>
</html>

update.jsp

<%--
  Created by IntelliJ IDEA.
  User: wuhaoxiang
  Date: 2024/11/1
  Time: 16:23
  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 lang="en">

<head>
    <meta charset="UTF-8">
    <title>修改品牌</title>
</head>
<body>
<h3>修改品牌</h3>
<form action="/brand-demo/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 rows="5" cols="20" name="description" }>${brand.description}</textarea><br>
    状态:
    <c:if test="${brand.status == 0}">
        <input type="radio" name="status" value="0" checked>禁用
        <input type="radio" name="status" value="1">启用<br>
    </c:if>
    <c:if test="${brand.status == 1}">
        <input type="radio" name="status" value="0">禁用
        <input type="radio" name="status" value="1" checked>启用<br>
    </c:if>


    <input type="submit" value="提交">
</form>
</body>
</html>

标签:JAVA,String,brand,req,改查,public,---,import,id
From: https://www.cnblogs.com/hx-top/p/18521063

相关文章

  • 并查集---Linux发行版的数量
    题目描述Linux操作系统有多个发行版,distrowatch.com提供了各个发行版的资料。这些发行版互相存在关联,例如Ubuntu基于Debian开发,而Mint又基于Ubuntu开发,那么我们认为Mint同Debian也存在关联。发行版集是一个或多个相关存在关联的操作系统发行版,集合内不包含没有关联的发行......
  • 牛客软件开发专项练习-Day2
    1.下列叙述中正确的是(A)A.顺序存储结构的存储一定是连续的,链式存储结构的存储空间不一定是连续的B.顺序存储结构只针对线性结构,链式存储结构只针对非线性结构C.顺序存储结构能存储有序表,链式存储结构不能存储有序表D.链式存储结构比顺序存储结构节省存储空间解释:链式存储结......
  • [NPUCTF2020]Anti-IDA
    [NPUCTF2020]Anti-IDAbuuctf刷题碰到的。没见到网上有wp就写一份吧很多无关的操作,只要不对输入数据影响就不需要管,最后exp如下enc=b"\x33\x44\x33\x39\x33\x41\x33\x37\x33\x34\x33\x43\x33\x39\x33\x37\x33\x41\x33\x34\x33\x41\x33\x37\x33\x44\x33\x36\x33\x36\x33\x41\......
  • 牛客软件开发专项练习-Day4
    1.下面关于并行和并发的区别,说法错误的是(C)A.并发计算是一种程序计算的形式,在系统中,至少有两个以上的计算在同时运作,计算结果可能同时发生B.并行计算指许多指令得以同时进行的计算模式。在同时进行的前提下,可以将计算的过程分解成小部份,之后以并发方式来加以解决C.并行是同时......
  • 熟练掌握并使用Java的NIO操作
    Java的NewInput/Output(NIO)库是一种非阻塞I/O操作的集合,旨在提高I/O操作的效率。相比于传统的JavaI/O(基于java.io包),NIO提供了更灵活、更强大的I/O处理能力。以下是一篇详细的文章,帮助你彻底熟练掌握并使用Java的NIO操作。一、JavaNIO概述JavaNIO(NewI/O)主要包含以下几个核......
  • 2024 -- 国庆集训 -- 临沂四中 -- 10月01 日 -- S/N模拟赛#1 题解
    A.2025--[炼石计划--NOIP模拟三]--T1--矩形赛时草了个\(O(n^4\log(n))\)竟然能过70分虽然本来就是这么分配的,发现正解只需将二分改为双指针就可以了,最气的是上面计算的时候用到还是尺取下面就用的二分(唐诗)。其实这题就是暴力,然后在低级的暴力上加一些操作变得稍微高级一......
  • CSP-S2024复盘
    CSP-S2024复盘好的:没有陷入100+100+100+0陷阱不好:写得太慢了痛失AK机会T1想得太慢了,没有观察样例读题的习惯所导致的,之后读题的时候应该大概理解完题意之后去看样例解释确保读对题以后再开始想。T2写的太慢了,第一次使用键盘在桌子下的电脑导致适应了15min才调整到了能......
  • [CSP-S 2024] 超速检测
    前言寄!算法计算超速区间容易发现可以计算出每一辆车的超速区间分讨策略大致如下voidCalc(intNow){if(Car[Now].v>V){if(Car[Now].a>=0){Car[Now].Left=Car[Now].d,Car[Now].Right=L;return;......
  • 基于java+SpringBoot+Vue的“衣依”服装销售平台设计与实现
    项目运行环境配置:Jdk1.8+Tomcat7.0+Mysql+HBuilderX(Webstorm也行)+Eclispe(IntelliJIDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot+mybatis+Maven+mysql5.7或8.0等等组成,B/S模式+Maven管理等等。环境需要1.运行环境:最好是javajdk1.8,我们在这个......
  • 基于java+SpringBoot+Vue的IT技术交流和分享平台设计与实现
    项目运行环境配置:Jdk1.8+Tomcat7.0+Mysql+HBuilderX(Webstorm也行)+Eclispe(IntelliJIDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot+mybatis+Maven+mysql5.7或8.0等等组成,B/S模式+Maven管理等等。环境需要1.运行环境:最好是javajdk1.8,我们在这个......