首页 > 数据库 >连接数据库实现页面的增删改查

连接数据库实现页面的增删改查

时间:2024-11-13 19:22:32浏览次数:1  
标签:String req 改查 id mes 增删 import public 页面

创建项目,选择maven为构建系统

在pom.xml文件中添加war包

在idea创建web项目并修改路径为src\main\webapp

再配置tomcat


以下是项目的类和文件

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>untitled5</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>22</maven.compiler.source>
        <maven.compiler.target>22</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </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>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
    </build>


</project>

2.在pojo包中定义数据类

点击查看代码
package com.itwhx.pojo;

public class mes {
    private Integer id;
    private String production;
    private String workNumber;
    private String workerName;
    private Integer outn;
    private Integer outgood;
    private Integer defec;
    private Integer lose;
    private String reportdate;

    public mes() {
    }

    public mes(Integer id, String production, String workNumber, String workerName, Integer outn, Integer outgood, Integer defec, Integer lose, String reportdate) {
        this.id = id;
        this.production = production;
        this.workNumber = workNumber;
        this.workerName = workerName;
        this.outn = outn;
        this.outgood = outgood;
        this.defec = defec;
        this.lose = lose;
        this.reportdate = reportdate;
    }

    public Integer getId() {
        return id;
    }

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

    public String getProduction() {
        return production;
    }

    public void setProduction(String production) {
        this.production = production;
    }

    public String getWorkNumber() {
        return workNumber;
    }

    public void setWorkNumber(String workNumber) {
        this.workNumber = workNumber;
    }

    public String getWorkerName() {
        return workerName;
    }

    public void setWorkerName(String workerName) {
        this.workerName = workerName;
    }

    public Integer getOutn() {
        return outn;
    }

    public void setOutn(Integer outn) {
        this.outn = outn;
    }

    public Integer getOutgood() {
        return outgood;
    }

    public void setOutgood(Integer outgood) {
        this.outgood = outgood;
    }

    public Integer getDefec() {
        return defec;
    }

    public void setDefec(Integer defec) {
        this.defec = defec;
    }

    public Integer getLose() {
        return lose;
    }

    public void setLose(Integer lose) {
        this.lose = lose;
    }

    public String getReportdate() {
        return reportdate;
    }

    public void setReportdate(String reportdate) {
        this.reportdate = reportdate;
    }

    @Override
    public String toString() {
        return "mes{" +
                "id=" + id +
                ", production='" + production + '\'' +
                ", workNumber='" + workNumber + '\'' +
                ", workerName='" + workerName + '\'' +
                ", out=" + outn +
                ", outgood=" + outgood +
                ", defec=" + defec +
                ", lose=" + lose +
                ", reportdate='" + reportdate + '\'' +
                '}';
    }
}

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

点击查看代码
package com.itwhx.mapper;

import com.itwhx.pojo.mes;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface MesMapper {

    @Select("select * from tb_mes")
    @ResultMap("mesResultMap")
    List<mes> selectAll();

    @Select("insert into tb_mes values(null,#{production},#{workNumber},#{workerName},#{outn},#{outgood},#{defec},#{lose},#{reportdate})")
    void add(mes mes);

    @Select("select * from tb_mes where id = #{id}")
    @ResultMap("mesResultMap")
    mes selectById(int id);

    @Select("update tb_mes set production = #{production},work_number = #{workNumber},worker_name = #{workerName},outn = #{outn},outgood = #{outgood},defec = #{defec},lose = #{lose},reportdate = #{reportdate} where id = #{id} ")
    void update(mes mes);

    @Select("delete  from tb_mes 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.itwhx.mapper.MesMapper">

    <resultMap id="mesResultMap" type="mes">

        <result column="work_number" property="workNumber"></result>
        <result column="worker_name" property="workerName"></result>
    </resultMap>

</mapper>

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

点击查看代码
package com.itwhx.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;
    }
}

4.Service层中调用mapper的方法

点击查看代码
package com.itwhx.service;

import com.itwhx.mapper.MesMapper;
import com.itwhx.pojo.mes;
import com.itwhx.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * 查询所有
 */
public class MesService {

    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    public List<mes> selectAll(){

        SqlSession sqlSession = sqlSessionFactory.openSession();

        MesMapper mesMapper = sqlSession.getMapper(MesMapper.class);

        List<mes> mess = mesMapper.selectAll();

        sqlSession.close();
        return mess;

    }

    /**
     * 提交日报
     */
    public void add(mes mes){
        SqlSession sqlSession = sqlSessionFactory.openSession();

        MesMapper mapper = sqlSession.getMapper(MesMapper.class);

        mapper.add(mes);

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

    }

    /**
     * 通过id回显数据
     */
    public mes selectById(int id){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        MesMapper mapper = sqlSession.getMapper(MesMapper.class);

        mes mes = mapper.selectById(id);

        sqlSession.close();

        return mes;
    }

    /**
     * 修改
     */
    public void update(mes mes){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        MesMapper mapper = sqlSession.getMapper(MesMapper.class);
        mapper.update(mes);
        sqlSession.commit();
        sqlSession.close();
    }

    /**
     * 删除
     */
    public void deleteById(int id){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        MesMapper mapper = sqlSession.getMapper(MesMapper.class);
        mapper.deleteById(id);
        sqlSession.commit();
        sqlSession.close();
    }
}

5.在web中定义具体操作类

(1)添加操作类

点击查看代码
package com.itwhx.web;

import com.itwhx.pojo.mes;
import com.itwhx.service.MesService;

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 MesService service = new MesService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        String production = req.getParameter("production");
        String workNumber = req.getParameter("workNumber");
        String workerName = req.getParameter("workerName");
        String outn = req.getParameter("outn");
        String outgood = req.getParameter("outgood");
        String defec = req.getParameter("defec");
        String lose = req.getParameter("lose");
        String reportdate = req.getParameter("reportdate");

        mes mes = new mes();

        mes.setProduction(production);
        mes.setWorkNumber(workNumber);
        mes.setWorkerName(workerName);
        mes.setOutn(Integer.parseInt(outn));
        mes.setOutgood(Integer.parseInt(outgood));
        mes.setDefec(Integer.parseInt(defec));
        mes.setLose(Integer.parseInt(lose));
        mes.setReportdate(reportdate);

        service.add(mes);

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

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

(2)删除类
点击查看代码
package com.itwhx.web;

import com.itwhx.service.MesService;

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 DeleteServlet extends HttpServlet {
private MesService mesService = new MesService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");

        mesService.deleteById(Integer.parseInt(id));

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
(3)修改
点击查看代码
package com.itwhx.web;

import com.itwhx.pojo.mes;
import com.itwhx.service.MesService;

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 MesService service = new MesService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        String id = req.getParameter("id");
        String production = req.getParameter("production");
        String workNumber = req.getParameter("workNumber");
        String workerName = req.getParameter("workerName");
        String outn = req.getParameter("outn");
        String outgood = req.getParameter("outgood");
        String defec = req.getParameter("defec");
        String lose = req.getParameter("lose");
        String reportdate = req.getParameter("reportdate");

        mes mes = new mes();

        mes.setId(Integer.parseInt(id));
        mes.setProduction(production);
        mes.setWorkNumber(workNumber);
        mes.setWorkerName(workerName);
        mes.setOutn(Integer.parseInt(outn));
        mes.setOutgood(Integer.parseInt(outgood));
        mes.setDefec(Integer.parseInt(defec));
        mes.setLose(Integer.parseInt(lose));
        mes.setReportdate(reportdate);

        service.update(mes);

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

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
(4)id查询和查询所有
点击查看代码
package com.itwhx.web;

import com.itwhx.pojo.mes;
import com.itwhx.service.MesService;

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("/selectByIdServlet")
public class SelectByIdServlet extends HttpServlet {

    private MesService service = new MesService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");

        mes mes = service.selectById(Integer.parseInt(id));

        req.setAttribute("mes", mes);

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

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

点击查看代码
package com.itwhx.web;

import com.itwhx.pojo.mes;
import com.itwhx.service.MesService;

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 MesService mesService = new MesService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        List<mes> mess = mesService.selectAll();

        request.setAttribute("mess", mess);

        request.getRequestDispatcher("selectAll.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
6.前端的html文件与jsp文件

(1)主界面

点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>主界面</title>
  <title>Center Text with CSS</title>
  <style>
    .center-text {
      text-align: center;
    }
  </style>
</head>
<body>
<div class="center-text"><h1>MES管理系统</h1></div>

<div class="center-text">
  <h3>功能列表</h3><br>
  <a href="/untitled5/selectAllServlet">查询所有</a><br><br>
  <a href="/untitled5/addMes.jsp">提交日报</a><br><br>
  <a href="/untitled5/selectAllServlet">修改日报</a><br><br>
  <a href="/untitled5/selectAllServlet">删除日报</a>
</div>

</body>
</html>
(2)添加页面
点击查看代码
<%--
  Created by IntelliJ IDEA.
  User: wuhaoxiang
  Date: 2024/11/9
  Time: 14:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>提交日报</title>
    <title>Center Text with CSS</title>
    <style>
        .center-text {
            text-align: center;
        }
    </style>
</head>
<body>

<form action="/untitled5/addServlet" method="post">
<div class="center-text">
    <h1>提交日报</h1><br>
    生产批次:<input name="production"><br>
    工号:<input name="workNumber"><br>
    工人姓名:<input name="workerName"><br>
    转出总数:<input name="outn"><br>
    转出合格数:<input name="outgood"><br>
    次品数:<input name="defec"><br>
    丢失数:<input name="lose"><br>
    上报日期:<input name="reportdate"><br>
    <input type="submit" value="提交日报">
</div>



</form>

</body>
</html>

(3)查找页面
点击查看代码
<%--
  Created by IntelliJ IDEA.
  User: wuhaoxiang
  Date: 2024/11/9
  Time: 12:30
  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>

<input type="button" value="返回" id = "back"><br>
<table border="1" cellspacing="0" width="80%">
<tr>
    <th>序号</th>
    <th>生产批次</th>
    <th>工号</th>
    <th>工人姓名</th>
    <th>转出总数</th>
    <th>转出合格数</th>
    <th>次品数</th>
    <th>丢失数</th>
    <th>上报日期</th>
    <th>操作</th>
</tr>

    <c:forEach items="${mess}" var="mes" varStatus="status">
        <tr align="center">
            <td>${status.count}</td>
            <td>${mes.production}</td>
            <td>${mes.workNumber}</td>
            <td>${mes.workerName}</td>
            <td>${mes.outn}</td>
            <td>${mes.outgood}</td>
            <td>${mes.defec}</td>
            <td>${mes.lose}</td>
            <td>${mes.reportdate}</td>
            <td><a href="/untitled5/selectByIdServlet?id=${mes.id}">修改</a><a href="/untitled5/deleteByIdServlet?id=${mes.id}">删除</a> </td>
        </tr>
    </c:forEach>
</table>

<script>
    document.getElementById("back").onclick = function (){
        location.href = "/untitled5/index.html";
    }
</script>

</body>
</html>
(4)修改页面
点击查看代码
<%--
  Created by IntelliJ IDEA.
  User: wuhaoxiang
  Date: 2024/11/9
  Time: 14:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改日报</title>
    <title>Center Text with CSS</title>
    <style>
        .center-text {
            text-align: center;
        }
    </style>
</head>
<body>
<div class="center-text">
    <h1>修改日报</h1>
    <form action="/untitled5/updateServlet" method="post">
        <input type="hidden" name="id" value="${mes.id}">
        生产批次:<input name="production" value="${mes.production}"><br>
        工号:<input name="workNumber" value="${mes.workNumber}"><br>
        工人姓名:<input name="workerName" value="${mes.workerName}"><br>
        转出总数:<input name="outn"  value="${mes.outn}"><br>
        转出合格数:<input name="outgood"  value="${mes.outgood}"><br>
        次品数:<input name="defec"  value="${mes.defec}"><br>
        丢失数:<input name="lose"  value="${mes.lose}"><br>
        上报日期:<input name="reportdate"  value="${mes.reportdate}"><br>
        <input type="submit" value="修改">
    </form>
</div>

</body>
</html>
代码部分完成,运行即可 代码中有错误未修改,只可实现添加功能

标签:String,req,改查,id,mes,增删,import,public,页面
From: https://www.cnblogs.com/abc233/p/18544561

相关文章

  • Vue网站发布到iis后提示404页面不可访问
    vue重定向和跨域配置:https://zhuanlan.zhihu.com/p/5306882511.安装组件:URLRewrite:https://www.iis.net/downloads/microsoft/url-rewriteApplicationRequestRouting:https://www.iis.net/downloads/microsoft/application-request-routing2.新建一个web.config放到发布到文件......
  • 散列表-HashMap的增删改查-Java
    在Java中,HashMap 是一种基于散列表的Map接口实现,可以使用null值和null键。以下是对 HashMap<Character,Integer> 进行的增删改查操作:1.增(put) map.put(key,value)、查(get) Integervalue=map.get(key)importjava.util.HashMap;publicclasstest{public......
  • RadSystems 自定义页面全攻略:个性化任务管理系统的实战设计
    系列文章目录探索RadSystems:低代码开发的新选择(一)......
  • github action自动部署angular页面
    angular.jsonprojects>{your-project-name}>architect>build>options>outputPath如果默认生成静态网页在browser下,记得修改/添加属性"baseHref":"/browser/",安装angular-cli-ghpagesngaddangular-cli-ghpages.github/workflows下创建工作流nam......
  • python-27-Python ORM系列之彻底搞明白ORM概念,对ORM进行封装结合FastAPI实现数据库的
    python-27-PythonORM系列之彻底搞明白ORM概念,对ORM进行封装结合FastAPI实现数据库的增删改查,联表查询等接口一.简介在Python基础系列ORM部分为大家介绍了如何搭建MySQL数据和MySQL一些访问配置,同时也介绍了pymysql库的封装来实现对数据库的增删改查功能,但是截止以上都没......
  • HTML静态网页成品作业(HTML+CSS)——游戏战地介绍设计制作(4个页面)
    ......
  • uniapp中uni.setTabBarItem方法在非tabbar页面使用会报错
    背景:uniapp在开发小程序多语言切换功能时,使用uni.setTabBarItem方法切换tabbar语言时报错,查阅文档发现微信小程序该功能只能在tabbar页面或其子页面中使用,不能在其他页面直接使用。解决:在tabbar页面中使用onShow方法监听切换语言设置,部分代码示例如下:<scriptsetup>import{......
  • Flink日志输出查看方式 通过web页面 Stdout 查看控制台日志
    Flink日志输出查看方式在网上查看flink日志查看方式,竟然查询不到,因此写下这篇文章,给有此困惑的小盆友们,也给自己做个总结!前情提要:我是通过flinkwebui提交的flink任务的,因此通过flinkui查看自身控制台打印输出的。第一步:打开flink的Dashboard看到TaskManager的控制面......
  • VUE3 script setup里面如何动态更新整个页面的背景图片
    1.使用内联样式和响应式数据步骤一:创建响应式数据来存储背景图片的URL在scriptsetup中,可以使用ref来创建一个响应式的变量来存储背景图片的URL。<template><div><button@click="changeBackground">更换背景图片</button></div></template><scriptsetup>......
  • vue跨页面调用函数
    1、在utils文件夹下创建中间件middle.js//中间件实现跨页面调用方法importVuefrom'vue'exportdefaultnewVue2、被调用页面代码<template></template><script>importMiddlefrom'@/utils/middle.js';exportdefault{mounted(){let......