jsp+servlet+jdbc to realize CRUD of student table

Posted by nathan1 on Fri, 10 Dec 2021 17:43:02 +0100

1. Technology use

jsp+Servlet+jdbc

idea 2020.3

Mysql 5.8

tomcat 8.5

sqlYog 8.7

2. Prepare tools

jdbc Driver Download:

For mysql drivers above 5.8, a special upgrade driver is required

Portal: mysql-connector-java-8.0.13.jar/.keep · xuge/java - Gitee.com

3. Frame construction

3.1 establish student information table

CREATE TABLE studentbase (
id INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Student number',
NAME VARCHAR(75)   COMMENT 'full name',
sex VARCHAR(30) COMMENT 'Gender',
age INT (11) COMMENT 'Age',
major VARCHAR(120) COMMENT 'major',
department VARCHAR(120) COMMENT 'Faculty',
telephone VARCHAR(45)  COMMENT 'Telephone number',
email VARCHAR(120) COMMENT 'mailbox',
PRIMARY KEY(id)
	
) ENGINE=INNODB;

3.2 creating a Web project

src directory

Web directory

4. Appetizer

At this point, you should have executed the creation of tables

4.1 connecting data sources

Click DataBase on the right

Data Source -->Mysql --

Test connection

Connect through

4.2 javaBean component for database tables

According to the ID, name, age sex...., Establish properties in turn, private, and provide interfaces

package com.domain;

/**
 * @author yjx
 * @version 1.0
 */
public class student {
    private int  id;
    private String name;
    private String sex;
    private int age;
    private String major;
    private String department;
    private String telephone;
    private String email;

    public student() {

    }

    public student(int id, String name, String sex, int age, String major, String department,
                        String telephone, String email) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.major = major;
        this.department = department;
        this.telephone = telephone;
        this.email = email;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", major='" + major + '\'' +
                ", department='" + department + '\'' +
                ", telephone='" + telephone + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

4.3 tool class for obtaining database connection object

package com.utils;

/*
 * @author yjx
 * @version 1.0
 */


import org.junit.Test;

import java.sql.*;

/**
 * Database tools
 */
public class DBUtil {
    private static String dbUrl = "jdbc:mysql://localhost:3306/student?user=root&password=609483" +
            "&useUnicode=true&characterEncoding=UTF8"; //Database address
    private static String dbUser = "root"; //Database user
    private static String dbPwd = "609483"; //Database password
    private static String dbDriver = "com.mysql.cj.jdbc.Driver"; //Database driven

    private static Connection conn = null;

    //Get connection
    public static Connection getConn() {
        if (null == conn) {
            try {
                Class.forName(dbDriver);
                conn = DriverManager.getConnection(dbUrl);
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }
    ///Testing
    @Test
    public void test(){
        if(getConn() != null){
            System.out.println("Database connection succeeded");
        }else{
            System.out.println("Database connection failed");
        }
    }
}
 

To test whether the database is connected by unit test, JUnit 4.12.1 needs to be introduced jar

4.4 Student object processing in database (CRUD)

package com.dao;

import com.domain.student;
import com.utils.DBUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author yjx
 * @version 1.0
 */
public class studentDao {
    PreparedStatement pst = null;

    public List<student> getAllUser() {
        List<student> list = new ArrayList<>();
        Connection conn = DBUtil.getConn();
        String sql = "select * from studentbase";

        try {
            pst = conn.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                student stu = new student();
                stu.setId(rs.getInt("id"));
                stu.setName(rs.getString("name"));
                stu.setSex(rs.getString("sex"));
                stu.setAge(rs.getInt("age"));
                stu.setMajor(rs.getString("major"));
                stu.setDepartment(rs.getString("department"));
                stu.setTelephone(rs.getString("telephone"));
                stu.setEmail(rs.getString("email"));
                list.add(stu);
            }
//            Iterator iterator=list.iterator();
//            System.out.println("= = = = student information is as follows = = = =");
//            while (iterator.hasNext()) {
//                Object next =  iterator.next();
//                System.out.println(next);
//
//            }

            rs.close();
            pst.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public boolean addStudent(student stu) {
        String sql = "insert into studentbase(id,NAME,sex,age,major,department,telephone,email) " +
                "values(?,?,?,?,?,?,?,?)";
        Connection conn = DBUtil.getConn();

        try {
            pst = conn.prepareStatement(sql);
            pst.setInt(1, stu.getId());
            pst.setString(2, stu.getName());
            pst.setString(3, stu.getSex());
            pst.setInt(4, stu.getAge());
            pst.setString(5, stu.getMajor());
            pst.setString(6, stu.getDepartment());
            pst.setString(7, stu.getTelephone());
            pst.setString(8, stu.getEmail());

            int count = pst.executeUpdate();
            pst.close();
            return count > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteUser(int id) {
        String sql = "delete from studentbase where id = ?";
        Connection conn = DBUtil.getConn();

        try {
            pst = conn.prepareStatement(sql);
            pst.setInt(1, id);
            int count = 0;
            count = pst.executeUpdate();
            System.out.println(count);
            pst.close();
            if (count > 0) {
                System.out.println("delete success!!");
            } else {
                System.out.println("failed");
            }
            return count > 0;
        } catch (SQLException e) {
            System.out.println(e.getErrorCode() + "Deletion failed....");
        }
        return false;
    }

    public boolean updateUser(student stu,int id) {
        String sql = "update studentbase set id =?,NAME=?,sex=? ,age=?,major=?,department=?," +
                "telephone=?,email=?" +
                " where id="+id;
        Connection conn = DBUtil.getConn();

        try {
            pst = conn.prepareStatement(sql);
            pst.setInt(1, stu.getId());
            pst.setString(2, stu.getName());
            pst.setString(3, stu.getSex());
            pst.setInt(4, stu.getAge());
            pst.setString(5, stu.getMajor() + "");
            pst.setString(6, stu.getDepartment());
            pst.setString(7, stu.getTelephone());
            pst.setString(8, stu.getEmail());


            int count = pst.executeUpdate();
            pst.close();
            return count > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public student findUserById(int id) {
        String sql = "select * from studentbase where id = " + id;
        Connection conn = DBUtil.getConn();
        student stu = null;

        try {
            pst = conn.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                stu = new student();
                stu.setId(rs.getInt("id"));
                stu.setName(rs.getString("name"));
                stu.setSex(rs.getString("sex"));
                stu.setAge(rs.getInt("age"));
                stu.setMajor(rs.getString("major"));
                stu.setDepartment(rs.getString("department"));
                stu.setTelephone(rs.getString("telephone"));
                stu.setEmail(rs.getString("email"));


            }

            pst.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return stu;
    }

    @Test
    public void test() {
        student stu = new student();
       stu.setId(1004);
       stu.setName("yjx");
       stu.setSex("male");
       stu.setAge(20);
       stu.setMajor("secretary");
       stu.setDepartment("Mathematics and computer");
       stu.setTelephone("485545454");
       stu.setEmail("@45454.com");
        studentDao sd = new studentDao();
        sd.addStudent(stu);
        boolean b = false;

//        if(b){
//            System.out.println("add success!!");
//        }else{
//            System.out.println("failed!!");
//        }

//        b=sd.deleteUser("1003");
//        System.out.println(sd.findUserById(10));
//        if (b) {
//            System.out.println("modify success!!");
//        } else {
//            System.out.println("failed!!");
//        }
        sd.updateUser(stu,1004);


    }


}
 

You can test the methods in turn as I wrote. Of course, the premise is that the database is connected. Otherwise, NullPointerException is not my business. Ha ha ha

5. About the interaction with the previous jsp page (dinner)

AddServlet: when adding users to the front end, submit the form to the servlet for processing, and then return to the front end page

package com.servlet;

import com.dao.studentDao;
import com.domain.student;

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.text.ParseException;

/**
 * @author yjx
 * @version 1.0
 */
  @WebServlet("/addServlet")
    public class AddServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");

            int  id= Integer.parseInt(request.getParameter("id"));
            String name = request.getParameter("name");
            String sex = request.getParameter("sex");
            int age = Integer.parseInt(request.getParameter("age"));
            String major = request.getParameter("major");
            String department = request.getParameter("department");
            String telephone = request.getParameter("telephone");
            String email = request.getParameter("email");


            student stu = new student();
            stu.setId(id);
            stu.setName(name);
            stu.setSex(sex);
            stu.setAge(age);
            stu.setMajor(major);
            stu.setDepartment(department);
            stu.setTelephone(telephone);
            stu.setEmail(email);
        /*u.setUsername(new String(username.getBytes("ISO-8859-1"),"UTF-8"));
        u.setPassword(new String(password.getBytes("ISO-8859-1"),"UTF-8"));*/
            studentDao sd = new studentDao();
            sd.addStudent(stu);
//            request.setCharacterEncoding("UTF-8");
            request.getRequestDispatcher("showServlet").forward(request,response);
        }

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


}
 

DeleteServlet

package com.servlet;

import com.dao.studentDao;
import org.omg.PortableInterceptor.INACTIVE;

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;

/**
 * @author yjx
 * @version 1.0
 */
@WebServlet("/deleteServlet")
public class DeleteServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
//        response.setContentType("utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String idStr = request.getParameter("id");
        int id1=Integer.parseInt(idStr);
        studentDao sd = new studentDao();
        if (sd.deleteUser(id1)) {
            request.setAttribute("deleted", "Delete succeeded!");
            request.getRequestDispatcher("showServlet").forward(request, response);
        } else {
            response.sendRedirect("showServlet");
        }
    }

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

    }
}
 

searchServlet

package com.servlet;

import com.dao.studentDao;
import com.domain.student;

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 javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author yjx
 * @version 1.0
 */
@WebServlet("/searchServlet")
public class searchServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
//        response.setContentType("utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        doPost(request,response);

//        String idStr = request.getParameter("id");
//        if (idStr != null && !idStr.equals("")) {
//            int id = Integer.parseInt(idStr);
//            studentDao sd = new studentDao();
//            student user = sd.findUserById(id);
//            request.setAttribute("user", user);
//        }
//        request.getRequestDispatcher("search.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = -1;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        student stu = new student();
        studentDao sd = new studentDao();

        if(id!=-1){
            if(sd.findUserById(id)!=null){
                stu=sd.findUserById(id);
                HttpSession session = request.getSession();
                session.setAttribute("list",stu);
                request.getRequestDispatcher("searchSuccess.jsp").forward(request, response);
            }else{
                request.getRequestDispatcher("failed.jsp").forward(request, response);
            }
        }else{
            request.getRequestDispatcher("showServlet").forward(request, response);
        }



    }
}

 

Don't ask me why I don't use request to obtain the data in the domain object. This pit is set with request. It's impossible to use request to obtain the data in the jsp page. Then I use the user session to save the list set (student), and then use the session to obtain the data in the domain object (i.e. the set composed of student objects) in the jsp page

UpdateServlet

package com.servlet;

import com.dao.studentDao;
import com.domain.student;

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 javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author yjx
 * @version 1.0
 */

@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
//        response.setContentType("utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //doPost(request,response);
//
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.equals("")) {
            int id = Integer.parseInt(idStr);
            studentDao sd = new studentDao();
            student user = sd.findUserById(id);
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            request.getRequestDispatcher("update.jsp").forward(request, response);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = 0;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        int age = 0;
        try {
            age = Integer.parseInt(request.getParameter("age"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        String major = request.getParameter("major");
        String department = request.getParameter("department");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        //modify
        student stu = new student();
        stu.setId(id);
        stu.setName(name);
        stu.setSex(sex);
        stu.setAge(age);
        stu.setMajor(major);
        stu.setDepartment(department);
        stu.setTelephone(telephone);
        stu.setEmail(email);
        studentDao sd = new studentDao();
        sd.updateUser(stu,id);

        request.getRequestDispatcher("showServlet").forward(request, response);


    }

}

showServlet

package com.servlet;

import com.dao.studentDao;
import com.domain.student;
import com.sun.deploy.util.SessionState;

import javax.ejb.SessionContext;
import javax.jms.Session;
import javax.jws.soap.SOAPBinding.Use;
import javax.servlet.ServletContext;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author yjx
 * @version 1.0
 */
@WebServlet("/showServlet")
public class showServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       // request.setCharacterEncoding("utf-8");
//        response.setContentType("utf-8");
//        response.setCharacterEncoding("UTF-8");response.setContentType("text/html; charset=Utf-8");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        studentDao sd = new studentDao();
        List<student> list1 = sd.getAllUser();
        HttpSession session = request.getSession();
        session.setAttribute("list",list1);
//        ServletContext context   =   this.getServletContext();
//        context.setAttribute("list", list1);
//        if (!list1.isEmpty()) {
//            for (int i = 0; i < list1.size(); i++) {
//                student st = list1.get(i);
//                response.getWriter().print("<tr>");
//                response.getWriter().print("<td>" + st.getId() + "</td>");
//                response.getWriter().print("<td>" + st.getName() + "</td>");
//                response.getWriter().print("<td>" + st.getSex() + "</td>");
//                response.getWriter().print("<td>" + st.getSex() + "</td>");
//                response.getWriter().print("<td>" + st.getAge() + "</td>");
//                response.getWriter().print("<td>" + st.getMajor() + "</td>");
//                response.getWriter().print("<td>" + st.getTelephone() + "</td>");
//                response.getWriter().print("<td>" + st.getEmail() + "</td>");
//                response.getWriter().print("</tr>");
//            }
//        }

//            request.setAttribute("list", list1);
            request.getRequestDispatcher("/index.jsp").forward(request, response);
        }

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

On the problem of garbled code

package com.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class manageFilter implements Filter {
    protected String encoding = "UTF-8";
    protected FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest res = (HttpServletRequest) request;
        res.setCharacterEncoding(encoding);
        chain.doFilter(request, response);
    }

    public void destroy() {
        this.filterConfig = null;
    }
}
 

6. Front

End page

index.jsp

<%@ page import="com.domain.student" %>
<%@ page import="java.util.List" pageEncoding="utf-8"%><%--<jsp:useBean id="deleted" scope="request" type=""/>--%>
<%--<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>--%>
<%--
  Created by IntelliJ IDEA.
  User: yjx
  Date: 2021/12/9
  Time: 20:06
  To change this template use File | Settings | File Templates.
--%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%-- take out servlet It's from transit request Domain object and returns a object Object, this Object Object is the forwarded domain object --%>
<%
    Object deleted = request.getAttribute("deleted");
    request.setAttribute("deleted", "Delete succeeded");
%>
<%-- Re store to request In domain --%>


<html>
<head>
    <title>User presentation</title>
    <script type="text/javascript">
        function confirmDialog(){
            return window.confirm("Are you sure you want to delete this message?");
        }
    </script>
</head>
<body>
<h1>User presentation</h1>
<%--<h2>${deleted}</h2>--%>
<table border="2 solid">
    <tr>
        <td>Student number</td>
        <td>full name</td>
        <td>Gender</td>
        <td>Age</td>
        <td>Faculty</td>
        <td>major</td>
        <td>Telephone</td>
        <td>mailbox</td>
        <td colspan="2">operation</td>
    </tr>

<%--    <jsp:useBean id="list" scope="request" type="java.util.List"/>--%>
    <%
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        List<student> sl=(List<student>)session.getAttribute("list");
        if(sl==null||sl.size()==0){
            System.out.println("no data...");
        }else{
            for(int i=0;i<sl.size();i++){
                student st=sl.get(i);
                out.print("<tr>");
                out.print("<td>"+st.getId()+"</td>");
                out.print("<td>"+st.getName()+"</td>");
                out.print("<td>"+st.getSex()+"</td>");
                out.print("<td>"+st.getAge()+"</td>");
                out.print("<td>"+st.getMajor()+"</td>");
                out.print("<td>"+st.getDepartment()+"</td>");
                out.print("<td>"+st.getTelephone()+"</td>");
                out.print("<td>"+st.getEmail()+"</td>");

    %>
    <td><a href="${pageContext.request.contextPath}/deleteServlet?id=<%=st.getId() %>"
           onclick="return confirmDialog()">delete
    </a></td>

    <td><a href="${pageContext.request.contextPath}/updateServlet?id=<%=st.getId() %>">modify
    </a></td>
    <%
                out.print("</tr>");
            }
        }
    %>


</table>
<a href="${pageContext.request.contextPath}/showServlet"><input type="submit" value="list"> </a></td>
<a href="add.jsp"><input type="submit" value="register"> </a></td>
<a href="search.jsp"><input type="submit" value="lookup"></a></td>
<a href="update1.jsp"><input type="submit" value="modify"></a></td>
<a href="delete.jsp"><input type="submit" value="delete"></a></td>

</body>
</html>
 

add.jsp

<%--
  Created by IntelliJ IDEA.
  User: yjx
  Date: 2021/12/9
  Time: 21:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page language="java" pageEncoding="utf-8"%>
<% request.setCharacterEncoding("UTF-8");%>.
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<html>
<head>
    <title>User add</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/addServlet" method="post">
    <table border="2px">

        <tr>
            <td> Student No.:</td>
            <td>
                <input type="text" name="id" class="{required:true}" title="Student number must be numeric"/>
            </td>
        </tr>

        <tr>
            <td> full name:</td>
            <td><input type="text" name="name" title="Name cannot be empty"/></td>

        </tr>

        <tr>
            <td>Age:</td>
            <td><input type="text" name="age" title="Age must be a number"/></td>

        </tr>

        <tr>
            <td>Gender:</td>
            <td>
                <select name="sex">
                    <option value="male" selected>male</option>
                    <option value="female">female</option>
                </select>
            </td>

        </tr>

        <tr>
            <td> Faculty:</td>
            <td>
                <input type="text" name="department"/>
            </td>

        </tr>

        <tr>
            <td>Major:</td>
            <td>
                <input type="text" name="major" title="Specialty cannot be blank">
            </td>

        </tr>

        <tr>
            <td>Telephone:</td>
            <td><input type="text" name="telephone"></td>

        </tr>

        <tr>
            <td>mailbox:</td>
            <td><input type="text" name="email"></td>


        </tr>
        <tr colspan="2">
            <td><input type="submit" value="Submit"></td>
            <td><input type="reset" value="Reset"></td>
        </tr>

    </table>
</form>
</body>
</html>

delete.jsp

<%--
  Created by IntelliJ IDEA.
  User: yjx
  Date: 2021/12/9
  Time: 21:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page language="java" pageEncoding="utf-8"%>
<% request.setCharacterEncoding("UTF-8");%>.
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<html>
<head>
    <title>User delete</title>
</head>
<body>
<jsp:include page="index.jsp" />
<form action="${pageContext.request.contextPath}/deleteServlet" method="post">

    <p>  Please enter the student number to delete:
        <input type="text" name="id" />
        <input type="submit" />
        <input type="button" value="Back" onclick="history.go(-1)"/>
    </p>


</form>
<%--<jsp:include page="index.jsp" />--%>
</body>
</html>
 

search.jsp

<%--
  Created by IntelliJ IDEA.
  User: yjx
  Date: 2021/12/10
  Time: 19:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Query page</title>
</head>
<body>
<jsp:include page="index.jsp" />
<form action="${pageContext.request.contextPath}/searchServlet" method="post">

    <p>  Please enter the student number to query:
        <input type="text" name="id" />
        <input type="submit"  />
        <input type="button" value="Back" onclick="history.go(-1)"/>
    </p>


</form>

</body>
</html>
 

searchSuccess.jsp

<%@ page import="com.domain.student" %><%--
  Created by IntelliJ IDEA.
  User: yjx
  Date: 2021/12/10
  Time: 20:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Search succeeded</title>
</head>
<body>
<table border="2 solid">
    <tr>
        <td>Student number</td>
        <td>full name</td>
        <td>Gender</td>
        <td>Age</td>
        <td>Faculty</td>
        <td>major</td>
        <td>Telephone</td>
        <td>mailbox</td>
    </tr>

    <%--    <jsp:useBean id="list" scope="request" type="java.util.List"/>--%>
        <%
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        student stu=(student)session.getAttribute("list");
        if(stu==null){
            System.out.println("no data...");
        }else{
                out.print("<tr>");
                out.print("<td>"+stu.getId()+"</td>");
                out.print("<td>"+stu.getName()+"</td>");
                out.print("<td>"+stu.getSex()+"</td>");
                out.print("<td>"+stu.getAge()+"</td>");
                out.print("<td>"+stu.getMajor()+"</td>");
                out.print("<td>"+stu.getDepartment()+"</td>");
                out.print("<td>"+stu.getTelephone()+"</td>");
                out.print("<td>"+stu.getEmail()+"</td>");
        %>
    <%
                out.print("</tr>");

        }
    %>
</table>
<a href="add.jsp"><input type="submit" value="register"> </a></td>
<a href="search.jsp"><input type="submit" value="lookup"></a></td>
<a href="update1.jsp"><input type="submit" value="modify"></a></td>
<a href="delete.jsp"><input type="submit" value="delete"></a></td>

</body>
</html>
 

failed.jsp

<%--
  Created by IntelliJ IDEA.
  User: yjx
  Date: 2021/12/10
  Time: 20:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Search failed</title>
</head>
<body>
<table border="2 solid">
    <tr>
        <td>Student number</td>
        <td>full name</td>
        <td>Faculty</td>
        <td>major</td>
        <td>Telephone</td>
        <td>mailbox</td>
    </tr>


</table>
<a href="add.jsp"><input type="submit" value="register"> </a></td>
<a href="search.jsp"><input type="submit" value="lookup"></a></td>
<a href="update1.jsp"><input type="submit" value="modify"></a></td>
<a href="delete.jsp"><input type="submit" value="delete"></a></td>

</body>
</html>
 

update.jsp

<%@ page import="com.domain.student" %>
<%@ page import="java.time.temporal.Temporal" %><%--<jsp:useBean id="user" scope="request" type="com.sun.corba.se.impl.ior.GenericIdentifiable"/>--%>
<%--
  Created by IntelliJ IDEA.
  User: yjx
  Date: 2021/12/9
  Time: 21:31
  To change this template use File | Settings | File Templates.
--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page language="java" pageEncoding="utf-8"%>
<% request.setCharacterEncoding("UTF-8");%>.
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<html>
<head>
    <title>User editing</title>
</head>
<body>
<%
    student stu= null;

        stu = (student)session.getAttribute("user");
    if(stu==null){
        response.getWriter().print("You entered id The number is not among them..");
    }else{
        int id = stu.getId();
        String name = stu.getName();
        String sex = stu.getSex();
        int age = stu.getAge();
        String major = stu.getMajor();
        String department = stu.getDepartment();
        String telephone = stu.getTelephone();
        String email = stu.getEmail();


//        int id = stu.getId();
//        String name = stu.getName();
//        String sex = stu.getSex();
//        int age = stu.getAge();
//        String major = stu.getMajor();
//        String department = stu.getDepartment();
//        String telephone = stu.getTelephone();
//        String email = stu.getEmail();
//

%>
<form action="${pageContext.request.contextPath}/updateServlet" method="post" style="align-items: center">
    <table border="1" >
        <tr>
            <td colspan="2"><h1>User modification</h1></td>
        </tr>
        <tr>
            <td>Student number</td>
            <td><input type="text" name="id" value="<%=id%>" /></td>
        </tr>
        <tr>
            <td>full name</td>
            <td><input type="text" name="name" value="<%=name%>" /></td>
        </tr>
        <tr>
            <td>Gender</td>
            <td><input type="text" name="sex" value="<%=sex%>" /></td>
        </tr>
        <tr>
            <td>Age</td>
            <td><input type="text" name="age" value="<%=age%>" /></td>
        </tr>
        <tr>
            <td>major</td>
            <td><input type="text" name="department" value="<%=major%>" /></td>
        </tr>
        <tr>
            <td>Faculty</td>
            <td><input type="text" name="major" value="<%=department%>" /></td>
        </tr>
        <tr>
            <td>Telephone</td>
            <td><input type="text" name="telephone" value="<%=telephone%>" /></td>
        </tr>
        <tr>
            <td>mailbox</td>
            <td><input type="text" name="email" value="<%=email%>" /></td>
        </tr>

        <tr>
            <td colspan="2">
                <input type="submit" value="Submit"/>
                <input type="button" value="Back" onclick="history.go(-1)"/>
            </td>

        </tr>
    </table>
    <%} %>

</form>
</body>

 

update1.jsp

<%--
  Created by IntelliJ IDEA.
  User: yjx
  Date: 2021/12/10
  Time: 20:42
  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>
<jsp:include page="index.jsp" />
<form action="${pageContext.request.contextPath}/updateServlet" method="get">

    <p>  Please enter the student number to be modified:
        <input type="text" name="id" />
        <input type="submit" />
        <input type="button" value="Back" onclick="history.go(-1)"/>
    </p>


</form>

</body>
</html>
 

7. Summary and reflection

  • The problem of garbled code has not been solved

  • Secondly, some exceptions will be reported in some pages. For example, the session object is empty by default, so I added a button

  • In some cases, the page needs to go back to the home page to realize the function

8. Operation

register

lookup

The code needs to depend on the situation. At that time, I will consider giving links (open source)

The general operation type of the code is right. Novices can learn, but veterans don't spray. Now they all use the framework. Just share my learning journey!!

catalogue

1. Technology use

2. Prepare tools

3. Frame construction

3.1 establish student information table

3.2 creating a Web project

src directory

Web directory

4. Appetizer

4.1 connecting data sources

4.2 javaBean component for database tables

4.3 tool class for obtaining database connection object

4.4 Student object processing in database (CRUD)

5. About the interaction with the previous jsp page (dinner)

AddServlet: when adding users to the front end, submit the form to the servlet for processing, and then return to the front end page

DeleteServlet

searchServlet

UpdateServlet

showServlet

On the problem of garbled code

6. Front

End page

index.jsp

add.jsp

delete.jsp

search.jsp

searchSuccess.jsp

failed.jsp

update.jsp

update1.jsp

7. Summary and reflection

8. Operation

register

lookup

Topics: Java Database MySQL Junit