MES管理系統(期中)

XYu1230發表於2024-11-04

寫在最前
自學的話是跟著b站上黑馬程式設計師的影片和文件資料,看的是這個影片

建議在黑馬公眾號,獲取課程資料,跟著課程資料裡的ppt或md文件自學,實在看不懂的在去看影片,如果一集一集刷,耗時

MES管理系統

1.新建一個java的maven專案

2.maven中匯入相關依賴

(需要學習maven相關知識)

<?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>com.stdu</groupId>
    <artifactId>MES</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <!--            匯入Servlet API-->
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>

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

        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/taglibs/standard -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>



    </dependencies>



    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>

        <maven.compiler.target>1.8</maven.compiler.target>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <!--            tomcat 外掛-->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <!--                <configuration>-->
                <!--                    <port>80</port>-->
                <!--                    &lt;!&ndash;                    <path>/</path>&ndash;&gt;-->
                <!--                </configuration>-->
            </plugin>
        </plugins>
    </build>

</project>

3.在resources下建立mybatis-config.xml

(需要學習mybatis相關知識)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--    起別名-->
    <typeAliases>
        <package name="com.stdu.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///test?useSSL=false&amp;allowPublicKeyRetrieval=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.stdu"/>
    </mappers>
</configuration>

4.Project Structure->Facets 新增webapp包和web.xml,然後將WEB-INF包拖到webapp包下

(webapp包下放一些前端程式碼檔案)

5.建立java實體類Plan , 建立資料庫表

5.1 Plan實體類

package com.stdu.pojo;

public class Plan {
    private Integer  id;//編號,用於資料庫自增
    private String name;//生產批次
    private String planId;//工號
    private String worker;//工人姓名
    private int outNumber;//轉出總數
    private int outGoodNumber;//轉出合格數
    private int defect;//次品數
    private int lost; //丟失數
    private String time;//上報日期


    public Plan() {
    }

    public Plan(Integer id, String name, String planId, String worker, int outNumber, int outGoodNumber, int defect, int lost, String time) {
        this.id = id;
        this.name = name;
        this.planId = planId;
        this.worker = worker;
        this.outNumber = outNumber;
        this.outGoodNumber = outGoodNumber;
        this.defect = defect;
        this.lost = lost;
        this.time = time;
    }

    /**
     * 獲取
     * @return id
     */
    public Integer getId() {
        return id;
    }

    /**
     * 設定
     * @param id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 獲取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 設定
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 獲取
     * @return planId
     */
    public String getPlanId() {
        return planId;
    }

    /**
     * 設定
     * @param planId
     */
    public void setPlanId(String planId) {
        this.planId = planId;
    }

    /**
     * 獲取
     * @return worker
     */
    public String getWorker() {
        return worker;
    }

    /**
     * 設定
     * @param worker
     */
    public void setWorker(String worker) {
        this.worker = worker;
    }

    /**
     * 獲取
     * @return outNumber
     */
    public int getOutNumber() {
        return outNumber;
    }

    /**
     * 設定
     * @param outNumber
     */
    public void setOutNumber(int outNumber) {
        this.outNumber = outNumber;
    }

    /**
     * 獲取
     * @return outGoodNumber
     */
    public int getOutGoodNumber() {
        return outGoodNumber;
    }

    /**
     * 設定
     * @param outGoodNumber
     */
    public void setOutGoodNumber(int outGoodNumber) {
        this.outGoodNumber = outGoodNumber;
    }

    /**
     * 獲取
     * @return defect
     */
    public int getDefect() {
        return defect;
    }

    /**
     * 設定
     * @param defect
     */
    public void setDefect(int defect) {
        this.defect = defect;
    }

    /**
     * 獲取
     * @return lost
     */
    public int getLost() {
        return lost;
    }

    /**
     * 設定
     * @param lost
     */
    public void setLost(int lost) {
        this.lost = lost;
    }

    /**
     * 獲取
     * @return time
     */
    public String getTime() {
        return time;
    }

    /**
     * 設定
     * @param time
     */
    public void setTime(String time) {
        this.time = time;
    }

    public String toString() {
        return "Plan{id = " + id + ", name = " + name + ", planId = " + planId + ", worker = " + worker + ", outNumber = " + outNumber + ", outGoodNumber = " + outGoodNumber + ", defect = " + defect + ", lost = " + lost + ", time = " + time + "}";
    }
}

5.2 在資料庫中建立plan表

(需要學習sql語句基本增刪改查操作)

CREATE TABLE plan (
    pid int primary key auto_increment,
    id varchar(30),
    name VARCHAR(50) NOT NULL,
    overview varchar(50), -- 計劃概述
    pmethod VARCHAR(10), -- 排產方式
    startTime varchar(15),
    endTime varchar(15),
    process varchar(50)
);

6. 在web-app下建立一個主頁面index.html

(需要學習html相關語法知識)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主頁面</title>
    <link href="css/mainPage.css" rel="stylesheet"></link>
</head>
<body>
<h1 align="center">MES管理系統</h1>
<br>
<br>
<br>
<div align="center">
    <table border="0" width="150" height="300">
        <thead>
        <tr><td>功能列表</td></tr>
        </thead>
        <tbody>
        <tr><td><a href = "add.html">提交日報</a></td></tr>
        <tr><td><a href = "update.html">修改日報</a></td></tr>
        <tr><td><a href = "delete.html">刪除日報</a></td></tr>
        <tr><td><a href = "query.html">查詢日報</a></td></tr>
        </tbody>
    </table>
</div>

</body>
</html>

介面展示

可以為介面新增css樣式,讓頁面變得更好看(需要學習css相關知識)

接下來只展示新增和查詢的操作,刪除和修改與之類似,不再贅述

7.新增操作

7.1先寫dao層操控資料庫的程式碼

在com.stdu.mapper下定義PlanMapper介面以及在resouces.com.stdu.mapper下寫PlanMapper.xml配置檔案
其中PlanMapper介面:

package com.stdu.mapper;
import com.stdu.pojo.Plan;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;

public interface PlanMapper {
  //註解實現sql新增語句,
    @Insert("insert into plan(name,planId,worker,outNumber,outGoodNumber,defect,lost,time) values(#{name},#{planId},#{worker},#{outNumber},#{outGoodNumber},#{defect},#{lost},#{time})")
    void add(Plan p);

@Select("select * from plan")
    List<Plan> selectAll();
}

PlanMapper.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.stdu.mapper.PlanMapper">

</mapper>

7.2 service層

(層次的話可以看一下MVC架構)

PlanService介面

package com.stdu.service;

import com.stdu.mapper.PlanMapper;
import com.stdu.pojo.Plan;
import com.stdu.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class PlanService {
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    /**
     * 查詢所有
     * @return
     */
    public List<Plan> selectAll(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PlanMapper mapper = sqlSession.getMapper(PlanMapper.class);
        List<Plan> plans = mapper.selectAll();
        sqlSession.commit();
        sqlSession.close();
        return plans;
    }

    public void add(Plan p){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PlanMapper mapper = sqlSession.getMapper(PlanMapper.class);
        mapper.add(p);
        sqlSession.commit();
        sqlSession.close();
    }
}

其中用到的工具類SqlSessionFactoryUtils是需要自己寫的,SqlSessionFactoryUtils工具類的作用就是封裝一些程式碼,避免寫一些重複的程式碼
SqlSessionFactoryUtils

package com.stdu.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;
    }
}

7.3 接下來書寫Servlet程式碼

這裡用來處理前端表單傳來的資料,封裝為一個Plan類,新增進資料庫
AddServlet

package com.stdu.web;

import com.stdu.mapper.PlanMapper;
import com.stdu.pojo.Plan;
import com.stdu.service.PlanService;
import com.stdu.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

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 PlanService service = new PlanService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解決亂碼問題
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name = req.getParameter("name");
        String planId = req.getParameter("planId");
        String worker = req.getParameter("worker");
        String outNumber = req.getParameter("outNumber");
        String outGoodNumber = req.getParameter("outGoodNumber");
        String defect = req.getParameter("defect");
        String lost = req.getParameter("lost");
        String time = req.getParameter("time");
        Plan p = new Plan(null, name, planId, worker, Integer.parseInt(outNumber),Integer.parseInt(outGoodNumber),Integer.parseInt(defect),Integer.parseInt(lost),time);
        service.add(p);
        req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
    }

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

這裡在新增完之後,請求轉發到了selectAllServlet,目的是為了新增完後自動執行查詢操作,使看到新增結果,查詢講解往下

7.4 最後一步前端介面add.html

生產批次和工號要新增javascript程式碼取值,判斷是否格式正確
日報押平判斷規則也要寫js程式碼判斷,如果押平,表單可以提交,否則,表單不能提交,並彈出警告
add.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>add</title>
    <link rel="stylesheet" href="css/mainPage.css"></link>
</head>


<body>
    <center>
        <h1>新增生產計劃</h1>
        <form action="/TestOne/addServlet" method="post" id="form">
            生產批次: <input type="text" name="name" id = "i1"> <span id="id_err" style="display: none">生產批次必須為10位</span><br><br>
            工號: <input type="text" name="planId" id = "i2"> <span id = "planId_err" style="display: none">工號必須為6位</span><br><br>
            工人姓名: <input type="text" name="worker"><br><br>
            轉出總數: <input type="text" name="outNumber"><br><br>
            轉出合格數: <input type="text" name="outGoodNumber"><br><br>
            次品數: <input type="text" name="defect"><br><br>
            丟失數: <input type="text" name="lost"><br><br>
            上報日期: <input type="text" name="time"><br><br>
            <input type="submit" value="提交"></input>
             </br></br></input>
        </form>
    </center>


<script>

    let id1 = document.getElementById("i1");
    //失去焦點
    id1.onblur = function () {
        let j = id1.value.trim();
        if(j.length != 10){
            document.getElementById("id_err").style.display = "block";
            document.getElementById("id_err").style.color = "red";
        }
        else document.getElementById("id_err").style.display = "none";

    }

    //判斷工號是否為6位
    let planId = document.getElementById("i2");
    planId.onblur = function () {
        let j2 = planId.value.trim();
        if(j2.length != 6){
            document.getElementById("planId_err").style.display = "block";
            document.getElementById("planId_err").style.color = "red";
        }
        else document.getElementById("planId_err").style.display = "none";
    }

    //判斷轉出總數 = 轉出合格數+次品數+丟失數,如果相等可以提交,否則警告
    let outNumber = document.getElementsByName("outNumber")[0];
    let outGoodNumber = document.getElementsByName("outGoodNumber")[0];
    let defect = document.getElementsByName("defect")[0];
    let lost = document.getElementsByName("lost")[0];
    //提交判斷
    document.getElementById("form").onsubmit = function () {
        let sum = parseInt(outNumber.value) - parseInt(outGoodNumber.value) - parseInt(defect.value) - parseInt(lost.value);
        if(sum != 0){
            alert("上報資料有誤");
            return false;
        }
        else return true;
    }

</script>

</body>
</html>

介面展示

8. 查詢操作

查詢操作dao層和service層與新增類似,不再寫
主要是Servlet的程式碼和jsp的程式碼
SelectAllServlet

package com.stdu.web;

import com.stdu.pojo.Plan;
import com.stdu.service.PlanService;

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 PlanService service = new PlanService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 從service層獲取所有計劃資訊
        List<Plan> plans = service.selectAll();
        // 將獲取到的計劃資訊設定到請求範圍中,以便在JSP頁面中使用
        req.setAttribute("plans",plans);
        // 列印計劃資訊,用於除錯(已註釋掉)
        //System.out.println(plans);
        // 轉發請求到/plan.jsp頁面,以便顯示計劃資訊
        req.getRequestDispatcher("/plan.jsp").forward(req,resp);
    }

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

從selectAllServlet中轉發來的plan物件,可透過${}的形式在jsp檔案中展示出來
plan.jsp
(需要學習jsp和jstl相關知識)

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2024/10/24
  Time: 16: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" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" id = 'add' value="返回">
<hr>
<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>
    </tr>

    <c:forEach items="${plans}" var="plan">
        <tr align="center">
           <td>${plan.name}</td>
            <td>${plan.planId}</td>
            <td>${plan.worker}</td>
            <td>${plan.outNumber}</td>
            <td>${plan.outGoodNumber}</td>
            <td>${plan.defect}</td>
            <td>${plan.lost}</td>
            <td>${plan.time}</td>
            <td><a href="/TestOne/updateServlet?time=${plan.time}">修改 </a> <a href = "/TestOne/deleteByIdServlet?id=${plan.id}" onclick='return confirm("是否要刪除?");'>刪除</a></td>
        </tr>
    </c:forEach>
</table>
</body>
<script>
    document.getElementById("add").onclick = function () {
        location.href = "/TestOne/index.html";
    }
</script>
</html>

介面展示

這是查詢全部的程式碼,具體按什麼查詢,只需書寫各自的dao層,service層和Servlet和html程式碼,最終都轉發到plan.jsp中進行展示

寫在最後
程式碼有些小bug,如果出現相同日期的日報,則會出現修改和刪除錯誤,所以沒寫..

相關文章