JSP student management system

The prototype of this example is the student management system connected to the database by JDBC, which is placed in the Servlet container and realizes the relevant interactive functions. The same as the original content are configuration files (Properties), connection database (BaseDAO), teacher classes, teacher interfaces and implementations.

Since there are many steps to avoid confusion, proceed to the next step after the function of each step is fully realized. There will be a prompt at the echo below and above. Just look back and forth to see the corresponding methods. This is implemented according to the directory order!

For Properties and BaseDAO, please refer to: Java_Dao_MySQL_ Student management system

To connect to the database, refer to: JDBC connection MySQL instance

Overview

File directory

The file directory is as follows:

db.properyies, BaseDAO and teacherdao are the same as before_ Impl . Different from the original will be mentioned one by one below (in units according to the en route directory).

Realize function

Teacher: registration, login

Student: full query of information, full query by name, query by ID, delete by ID, modify student information, add student

Eneity

Student

The student in the entity class is slightly adjusted from the original one, and the id attribute is added. The attributes in the corresponding database are:

public int stu_id;
public String stu_username;
public String stu_password;

Note: override the get/set method

For later convenience, you can write a structure with parameters and a structure without parameters. (not required)

public Student(){};
public Student(String stu_username, String stu_password){
    this.stu_username = stu_username;
    this.stu_password = stu_password;
}

Teacher

Similarly, a parameter construct and a lunch construct are added to the entity class of teacher. (not required)

public Teacher(){};
public Teacher(String tea_username, String tea_password){
    this.tea_username = tea_username;
    this.tea_password = tea_password;
}

DAO

It defines the relevant methods for interacting with the database, and provides a public interface for subclasses to implement.

BaseDAO

The content in BaseDAO is the same as the original (the same as the original), and the information of the corresponding database in it can be used by changing it to its own.

TeacherDAO

The abstract methods in the TeacherDAO interface are the same as the original ones, and will not be repeated.

StudentDAO

This includes the relevant functions corresponding to students. (mentioned above)

public interface StudentDAO {
    public List<Student> getAll();              //Full check
    public List<Student> getName(String name);  //Query by name
    public int getDel(Object... id);            //Delete by ID
    public Student getId(int id);               //Query the corresponding information according to the ID
    public int getUpdate(Student student);      //modify
    public int Insert(Student student);         //Add student
}

DAO_Impl

It implements the inheritance interface and the corresponding abstract methods.

TeacherDAO_Impl

TeacherDAO_Impl's implementation is the same as the original, so I won't repeat it.

StudentDAO_Impl

Functions: full query of information, full query by name, query by ID, delete by ID, modify student information and add students

Function 1: full information check

Method description:

  1. All the fields in the table are returned from the full query, so the List set needs to be used to store the returned value of the query;
  2. SQL statement of full query;
  3. Call the query method written in BaseDAO, pass the SQL statement as a parameter, and return the ResultSet;
  4. You need to judge whether the return value has a value. If there is a next value, assign the value to the student entity class (including stu_id, stu_username and stu_password);
  5. Add each student entity class in the loop to the defined List collection and return the List.
/**
 * No parameter
 * @return Student List collection of type
 */
@Override
public List<Student> getAll() {
    List<Student> studentList = new ArrayList<>();
    String sql = "select * from student";
    ResultSet resultSet = BaseDAO.executeQuery(sql);
    Student student = null;
    try {
        while (resultSet.next()){
            student = new Student();
            student.setStu_id(resultSet.getInt("stu_id"));
            student.setStu_username(resultSet.getString("stu_username"));
            student.setStu_password(resultSet.getString("stu_password"));
            studentList.add(student);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return studentList;
}

Function 2: check all by name

Method description:

  1. The basic idea is the same as full query, but the difference is SQL statement;
  2. Query the corresponding student information according to the name or according to a word in the name. At this time, the like keyword needs to be used;
  3. The return value is not necessarily one. You need to use the List collection to receive it.
/**
 * @param name Gets the name or a word in the name
 * @return Student List collection of type
 */
@Override
public List<Student> getName(String name) {
    List<Student> studentList = new ArrayList<>();
    String sql = "SELECT * FROM student WHERE `stu_username` like '%"+ name + "%' ";
    ResultSet resultSet = BaseDAO.executeQuery(sql);
    Student student = null;
    try {
        while (resultSet.next()){
            student = new Student();
            student.setStu_id(resultSet.getInt("stu_id"));
            student.setStu_username(resultSet.getString("stu_username"));
            student.setStu_password(resultSet.getString("stu_password"));
            studentList.add(student);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return studentList;
}

Function 3: query by ID

Method description:=

  1. It is also a query, but the incorporated parameter is ID and there is only one return value, so the return value is assigned to the Student's entity class.
/**
 * @param id int id of type
 * @return Returns the number of affected rows, of type int
 */
@Override
public Student getId(int id) {
    ResultSet resultSet = null;
    Student student = null;
    String sql = "select * from student where stu_id = ? ";
    resultSet = BaseDAO.executeQuery(sql, id);
    try{
        if(resultSet.next()){
            student = new Student();
            student.setStu_id(resultSet.getInt("stu_id"));
            student.setStu_username(resultSet.getString("stu_username"));
            student.setStu_password(resultSet.getString("stu_password"));
        }
    }catch (SQLException e){
        e.printStackTrace();
    }finally {
        try {
            BaseDAO.GetClose(conn, null, resultSet);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return student;
}

Function 4: delete according to ID

Method description:

  1. Through this method, multiple pieces of information can be deleted at one time, so the obtained parameters should be array type, and the ID corresponding to the information to be deleted is stored in it;
  2. From the above, we know that Object... Is also an array. When the number of ID S is unknown, this array can be applied;
  3. Use the for loop to traverse the ID value in the array, call the method in BaseDAO according to the SQL statement and ID, and return the number of affected rows (int type).
  4. Each cycle adds one to the number of affected rows, so that the final result is a total
/**
 * @param id Get the id of array type, Object...: the array can be empty
 * @return
 */
@Override
public int getDel(Object... id) {
    int i = 0;
    for (int j = 0; j < id.length; j++) {
        String sql = "delete from student where stu_id = ? ";
        i = BaseDAO.executeUpdate(sql, id[j]);
        i += 1;
    }
    return i;
}

Considering the problem of new energy:

Each cycle requires cumbersome steps such as calling methods, establishing database connections, precompiling, blocking values, calling executeupdate, closing resources and returning results, which consume considerable resources. Therefore, the above methods can be further improved by using the in keyword of SQL to uniformly put ID S into them. Such cumbersome steps need to be followed.

/**
 * @param id Gets the array id of Student type
 * @return Returns the number of affected rows, of type int
 */
public int getDel(Student[] id) {
    int i = 0;
    if (id != null && id.length > 0){
        String sql = "delete from student where stu_id in (";
        for (int j = 0; j < id.length; j++){
            if (i == id.length - 1){
                sql = sql + id[j];
            }else{
                sql = sql + id[j] + ",";
            }
        }
        sql = sql + ")";
        i = BaseDAO.executeUpdate(sql);
    }
    return i;
}

Function 5: student information modification

Method description:

  1. Get the entity class passed in and pass the value in the entity class to the BaseDAO method;
  2. Returns the number of rows affected.
/**
 * @param student Student Entity class of type
 * @return Returns the number of affected rows, of type int
 */
@Override
public int getUpdate(Student student){
    int i = 0;
    String sql = "update student set stu_username = ? , stu_password = ? where stu_id = ? ";
    i = BaseDAO.executeUpdate(sql, student.getStu_username(), student.getStu_password(), student.getStu_id());
    return i;
}

Function 6: add students

Method description:

  1. Get the entity class passed in and pass the value in the entity class to the BaseDAO method;
  2. Returns the number of rows affected.
/**
 * @param student Student Entity class of type
 * @return Returns the number of affected rows, of type int
 */
@Override
public int Insert(Student student) {
    int i=0;
    String sql = "insert into student(stu_username, stu_password) values( ? , ? )";
    i = BaseDAO.executeUpdate(sql, student.getStu_username(), student.getStu_password());
    return i;
}

Service

Now, the implementation of the logic layer can copy the corresponding interface in the DAO and implement it without additional modification, which seems to be a chicken rib. However, when the business logic increases, its convenience can be reflected.

The later interaction with the front-end page is to call the methods in the Service, which is equivalent to the interaction (decoupling) between the presentation layer and the business logic layer.

StudentService

Completely copy the abstract methods in StudentDAO without modification.

TeaService

Completely copy the abstract methods in TeacherDAO without modification.

Service_Impl

Implement the Service interface.

StudentsService_Impl

Implement the student interface corresponding to the Service, and the return value of each method is StudentDAO_Impl method.

public class StudentService_Impl implements StudentService {
    @Override
    public List<Student> getAll() {
        return new StudentDAO_Impl().getAll();
    }
    @Override
    public List<Student> getName(String name) {

        return new StudentDAO_Impl().getName(name);
    }
    @Override
    public int getDel(Object... id) {
        return new StudentDAO_Impl().getDel(id);
    }
    @Override
    public Student getId(int id) {
        return new StudentDAO_Impl().getId(id);
    }
    @Override
    public int getUpdate(Student student) {
        return new StudentDAO_Impl().getUpdate(student);
    }
    @Override
    public int Insert(Student student) {
        return new StudentDAO_Impl().Insert(student);
    }
}

TeaService_Impl

Implement the teacher interface corresponding to Service, and the return value of each method is TeacherDAO_Impl method.

public class TeaService_Impl implements TeaService {
    @Override
    public Teacher Login(String username, String password) {
        return new TeacherDAO_Impl().Login(username,password);
    }
    @Override
    public int SignIn(Teacher teacher) {
        return new TeacherDAO_Impl().SignIn(teacher);
    }
}

Servlet

I can't tell what Servlet is. If you want to know, you can take a look at this article: What is the essence of servlet s and how does it work?

After reading that article, look at JSP: How to learn JSP?

In short, here we can interact with the front-end page! For ease of understanding, I intersperse servlet s and jsp pages. Here, you may wish to go through the methods implemented by student before continuing.

Teacher registration / login

The files used include index.jsp, SignInServlet, Login.jsp and LoginServlet.

index.jsp

Main page for teacher registration.

Registration page: form and form verification.

Document description:

  1. Submit the form to SignInServlet;
  2. The user name and password are given different names;
  3. Verify the form according to the form submission, and judge whether the field is empty. If it is empty, it will not be processed.
<%--Form part--%>
<h1>Registration page</h1>
<form id="form" method="post" action="/SignInServlet">
    user name:<input name="teaName"><br/>
    password:<input name="teaPass"><br/><br/>
    <input type="submit" value="Confirm registration">
    <input type="reset" value="Reset">
</form>
<%--Form validation section--%>
<script src="js/jquery-3.6.0.js" type="text/javascript"></script>
<script>
    $(function () {
        $("#form").submit(function () {
            var teaName = $("input[name='teaName']").val();
            var teaPass = $("input[name='teaPass']").val();
            if (teaName.trim().length == 0  && teaPass.trim().length == 0) {
                alert("Field cannot be empty!");
                return false;
            }
        })
    })
</script>

SignInServlet

Create a new Servlet and a class file named SignInServlet.

You can configure the servlet mapping in web.xml. If you don't want to configure it manually, you can write directly on the class:

@WebServlet(name = "SignInServlet", value = "/SignInServlet")

servlet process:

  1. Inherit HttpServlet;

  2. To implement the doGet/doPost method, if you want to default the request to post request (not necessarily), call the doPost method in doGet.

  3. Set the encoding format through the setCharacterEncoding method of the request object;

  4. Obtain the corresponding data in the form through the getParameter method of the request object;

  5. Assign data to a parametric construct of Teacher type;

  6. Instantiate a TeaService_Impl object;

  7. Call the login method SignIn of the object, and the parameters passed are the Teacher object; (this is the last method)

  8. Use the value of int type to obtain the return value of the method;

  9. Judge whether the value is greater than 0. If it is true, the registration is successful, and forward the page to Login.jsp; If false, redirect to the original registration page.

@WebServlet(name = "SignInServlet", value = "/SignInServlet")
public class SignInServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String teaName = request.getParameter("teaName");
        String teaPass = request.getParameter("teaPass");
        Teacher teacher = new Teacher(teaName, teaPass);
        TeaService_Impl userService_ = new TeaService_Impl();
        int i = userService_.SignIn(teacher);
        if(i>0){
            //Jump to login page
            request.getRequestDispatcher("Login.jsp").forward(request, response);
        }else{
            response.sendRedirect("index.jsp");
        }

    }
}

Login.jsp

The teacher login page, which will be displayed when the registration is successful.

This page is similar to the login page. After login, you should enter the main page of student management. Therefore, after clicking submit, go to the login servlet to make a layer of judgment.

<h1>Login page</h1>
<form id="form" method="post" action="/LoginServlet">
    user name:<input name="teaName"><br/>
    password:<input name="teaPass"><br/><br/>
    <input type="submit" value="Confirm login">
    <input type="reset" value="Reset">
</form>

<script src="js/jquery-3.6.0.js" type="text/javascript"></script>
<script>
    $(function () {
        $("#form").submit(function () {
            var teaName = $("input[name='teaName']").val();
            var teaPass = $("input[name='teaPass']").val();
            if (teaName.trim().length == 0 && teaPass.trim().length == 0) {
                alert("Field cannot be empty!");
                return false;
            }
        })
    })
</script>

LoginServlet

This servlet is roughly the same as SignInServlet, except that it calls the teacher's login method (the previous method) and jumps to the AllServlet corresponding to the student management page.

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String teaName = request.getParameter("teaName");
        String teaPass = request.getParameter("teaPass");
        TeaService_Impl teaService_ = new TeaService_Impl();
        Teacher teacher = teaService_.Login(teaName, teaPass);
        if(teacher != null){
            request.getRequestDispatcher("/AllServlet").forward(request, response);
        }else {
            response.sendRedirect("index.jsp");
        }

    }
}

Student management

The files used include AllServlet, Main.jsp, Insert.jsp and Update.jsp. There are many steps here. Let's go on according to the order of functions. AllServlet needs to inherit HttpServlet first and override the two methods inside.

The page is as follows:

Full query of information, full query by name, query by ID, delete by ID, add student and modify student information.

Full information query: after the teacher logs in successfully, he can see the information of all students, as shown in the above figure, so the full query function should be used as the function of the main page.

Query by name: click the page button to query the corresponding student information according to the name or a word entered in the input box. There can be multiple results.

Query by ID: This is the page button. You can query according to the ID entered in the input box, and there is only one result.

Delete by ID: the user checks the student information to be deleted and clicks delete to delete it. If you want to select all, you need to check the top selection box, which realizes the selection of all.

Add student: page button, jump to the add page, enter the student's name and password according to the user, click the button to add the page, and then return to the main page.

Student information modification: each information can be modified. Click Modify to jump to the modification page. The corresponding information of the user is displayed by default, and single modification and full modification can be realized.

Note: the refresh button on the page is just a redirection.

Preliminary description:

  • AllServlet sets the encoding format
  • StudentService instantiates a subclass of objects for use (polymorphic).
  • Since all the servlets related to students are written in AllServlet, in order to distinguish different functions of the page, it is necessary to define an ID (action, which is not the action submitted by the form) to judge. For example, when the user clicks and deletes, it only completes the deletion function.
request.setCharacterEncoding("utf-8");
StudentService studentService = new StudentService_Impl();
String action = request.getParameter("action");

Full information check

Servlet/JSP step description:

  1. When the action is empty, you can check all the information. Because the teacher logs in, this ID is empty;
  2. Call the full query method in studentService (no parameters); (see getAll() above)
  3. The full query returns multiple pieces of information, which needs to be received by collection;
  4. This collection of saved information needs to be reflected in the front-end page, so the jsp page needs to obtain this collection;
  5. Here, the session in the jsp object is used to save the change set;
  6. After the servlet completes its work, finally redirect the page to the main page Main.jsp;
  7. The Main page uses the getAttribute method to get the previous collection and save it in a new collection;
  8. The Main page is traversed by foreach.

ALLServlet.java:

//If the ID is empty, perform a full query
if (action == null) {
    //Use a collection of Student types to receive return values
    List<Student> studentList = studentService.getAll();
    //If the return value is not empty, the collection is saved in the session object
    if (studentList != null) {
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("all", studentList);
        //Redirect to Main.jsp
        response.sendRedirect("Main.jsp");
    } 
    //If the collection is empty, it will be redirected to Login.jsp (ignoring the case where the database table is empty)
    else {
        response.sendRedirect("Login.jsp");
    }
}

Main.jsp:

<%
    List<Student>  studentList = (List<Student>) session.getAttribute("all");
%>
<%
    for (Student stu : studentList){
%>
<tr>
    <td><%=stu.getStu_id()%></td>
    <td><%=stu.getStu_username()%></td>
    <td><%=stu.getStu_password()%></td>
    <td><a href="#"> Modify</a></td>
</tr>
<%
    }
%>

Check all by name

Servlet/JSP step description:

  1. Judge the identification. When the value of the identification is the button name, enter the part of querying the name in ALLServlet;
  2. Obtain the information entered in the input field;
  3. Call the full query method in studentService (the parameter is the input field information); (you can view the getName above)
  4. The query name returns multiple pieces of information, which also needs to be received by collection;
  5. Replace the new set with the old set in the original session; (it is not judged whether the new set is empty)
  6. After the servlet completes its work, finally redirect the page to the main page Main.jsp;
  7. The rest are consistent with the whole investigation.

ALLServlet.java:

//Enter when the ID is query name
else if (action.equals("Query name")) {
    String stuName = request.getParameter("stuName");
    List<Student> studentList = studentService.getName(stuName);
    HttpSession httpSession = request.getSession();
    //Replace the old collection
    httpSession.setAttribute("all", studentList);
    response.sendRedirect("Main.jsp");
}

Main.jsp:

Query:<input type="text" name="stuName">
<input type="submit" name="action" value="Query name">

Query by ID

Servlet/JSP step description:

  1. Judge the identification. When the value of the identification is the button name, enter the part of ALLServlet to query the ID;
  2. Obtain the information entered in the input field;
  3. Call the method of querying ID in studentService (the parameter is input field information); (see getDel above)
  4. The query ID returns only one piece of information, so the Student object is used to receive it;
  5. Since the Main page uses the collection to receive, for convenience, the object is added to the information collection;
  6. Replace the new set with the old set in the original session; (it is not judged whether the new set is empty)
  7. After the servlet completes its work, finally redirect the page to the main page Main.jsp;
  8. The rest are consistent with the whole investigation.

ALLServlet.java:

//Enter when the ID is the query ID
else if (action.equals("query ID")) {
    int stuName = Integer.parseInt(request.getParameter("stuName"));
    Student student = studentService.getId(stuName);
    List<Student> studentList = new ArrayList<>();
    //Add the Student object to the collection
    studentList.add(student);
    HttpSession httpSession = request.getSession();
    //Replace the old collection
    httpSession.setAttribute("all",studentList);
    response.sendRedirect("Main.jsp");
}

Main.jsp:

Query:<input type="text" name="stuName">
<input type="submit" name="action" value="query ID">

Delete by ID

Servlet/JSP step description:

  1. When the user checks the information to be deleted, it can be one or more;
  2. Click the delete button;
  3. Judge the identification. When the value of the identification is the button name, enter the ALLServlet and delete the ID part;
  4. Since there may be multiple pieces of information to be deleted, you need to use the getParameterValues method to receive (this method obtains the information that multiple boxes are selected), the student ID is obtained, and the return value is an array type of String type;
  5. Call the method of deleting ID in studentService (the parameter is input field information); (see getDel above)
  6. The delete ID method returns the number of affected rows (int type);
  7. After the servlet completes its work, finally redirect the page to AllServlet (equivalent to refreshing the page);

ALLServlet.java:

//Enter when the ID is delete
else if (action.equals("delete")) {
    System.out.println(action);
    //Accept the return value with an array class
    String[] del_Id = request.getParameterValues("delId");
    int i = studentService.getDel(del_Id);
    response.sendRedirect("/AllServlet");
}

Main.jsp:

Delete button:

<input type="submit" name="action" id="delID" value="delete">

Information header:

<tr>
    <td>
        <input type="checkbox" name="allDel" οnclick="allCheck(this)">
    </td>
    <td>Student number</td>
    <td>Student name</td>
    <td>Student password</td>
    <td>operation</td>
</tr>

Select all:

function allCheck(obj){
    var delId = $("[name=delId]");
    for (var i = 0; i < delId.length; i++) {
        delId[i].checked = obj.checked;
    }
}

Information table: the value of checkbox gives the student ID

<tr>
    <td>
        <input type="checkbox" name="delId" class="checked" value="<%=stu.getStu_id()%>">
    </td>
    <td><%=stu.getStu_id()%></td>
    <td><%=stu.getStu_username()%></td>
    <td><%=stu.getStu_password()%></td>
    <td>
        <a href="#"> Modify</a>
    </td>
</tr>

Add student

Servlet/JSP step description:

  1. Click the Add button to enter ALLServlet;
  2. Judge the identification. When the value of the identification is the button name, enter the part added in ALLServlet;
  3. Redirect the page to the add page Insert.jsp;
  4. The addition page contains the student's user name and password (the ID is self increasing and does not need to be added). When clicking to confirm the addition, first verify the form to judge whether the input field is empty; (the form verification part is consistent with the teacher's)
  5. If the input fields are not empty, submit to ALLServlet;
  6. Judge the identification. When the value of the identification is the button name, enter the ALLServlet to confirm the added part;
  7. Obtain the user input student's user name and password;
  8. Instantiate a Student's parameterized object (parameterized construction), and the parameter is the input value;
  9. Call the Insert method in studentService (parameter Student object); (see Insert above)
  10. Use the value of int type to obtain the return value of the method;
  11. Judge whether the value is greater than 0. If it is true, it proves that the addition is successful, and forwards the page to the login page ALLServlet; if it is false, it redirects to the original addition page.

ALLServlet.java:

//Enter when the ID is confirm to add
else if (action.equals("Confirm add")) {
    System.out.println(action);

    String stuName = request.getParameter("stuName");
    String stuPass = request.getParameter("stuPass");
    Student student = new Student(stuName, stuPass);
    int i = studentService.Insert(student);
    if (i > 0) {
        response.sendRedirect("/AllServlet");
    } else {
        response.sendRedirect("Insert.jsp");
    }
}

Main.jsp:

<input type="submit" name="action" value="add to">

Insert.jsp:

<h1>Add student</h1>
<form method="post" action="AllServlet" id="form">
    user name:<input name="stuName"><br/>
    password:<input name="stuPass"><br/><br/>
    <input type="submit" name="action" value="Confirm add">
    <input type="reset" value="Reset">
</form>

Student information modification

Servlet/JSP step description:

  1. Click Modify in the operation box to enter the modification page Update.jsp. At the same time, the information to be submitted includes student ID, student user name and password;
  2. After entering the modify page, the corresponding student information is displayed in the input box. The student ID cannot be modified and is set to read-only;
  3. The user can modify the user name and password, single or all;
  4. Click the confirm modification button to enter ALLServlet;
  5. Judge the identification. When the value of the identification is the button name, enter the part added in ALLServlet;
  6. Instantiate a Student object;
  7. Assign all the information obtained to the student to the object;
  8. Call the modification method (parameter Student object) in studentService; (see getUpdate above)
  9. Use the value of int type to obtain the return value of the method;
  10. Judge whether the value is greater than 0. If it is true, it proves that the addition is successful, and forwards the page to the login page ALLServlet; if it is false, it redirects to the original modified page.

ALLServlet.java:

//Enter when the ID is confirm modification
else if(action.equals("Confirm modification")) {
    Student student = new Student();
    student.setStu_id(Integer.parseInt(request.getParameter("stuID")));
    student.setStu_username(request.getParameter("stuName"));
    student.setStu_password(request.getParameter("stuPass"));
    int i = studentService.getUpdate(student);
    if (i > 0) {
        response.sendRedirect("/AllServlet");
    } else {
        response.sendRedirect("Update.jsp");
    }
}

Main.jsp: get the ID, name and password of the corresponding student

<td>
    <a href="./Update.jsp?stuID=<%=stu.getStu_id()%>&stuName=<%=stu.getStu_username()%>&stuPass=<%=stu.getStu_password()%>">modify</a>
</td>

Update.jsp:

<form method="post" action="AllServlet" id="form">
    user ID: <input name="stuID" id="stuID" readonly><br/>
    user name:<input name="stuName" id="stuName"><br/>
    password:<input name="stuPass" id="stuPass"><br/><br/>
    <input type="submit" name="action" value="Confirm modification">
    <input type="reset" value="Reset">
</form>

Get student = information: intercept the characters in the url.

<script src="js/jquery-3.6.0.js" type="text/javascript"></script>
<script>
    $(document).ready(function () {
        var url = window.location.href;
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            strs = str.split("?")[1];
            strs = strs.split("&");
            var stuID = strs[0].split("=")[1];
            var stuName = decodeURI(strs[1].split("=")[1]);
            var stuPass = strs[2].split("=")[1];
            $("#stuID").val(stuID);
            $('#stuName').val(stuName);
            $('#stuPass').val(stuPass);
        }
    })
</script>

Write at the end

All the contents are packaged and uploaded, and you need to download them yourself.

Note nodes:

  1. Isolate the presentation layer from data access (low coupling);
  2. The contents of Service and DAO are consistent, and the contents of Service_Impl and DAO_Impl are consistent;
  3. There are two methods for Servlet mapping;
  4. Teacher registration and login use forwarding;
  5. Form verification appears in teacher registration, teacher login and adding students;
  6. action is used as an identifier to judge the functions to be completed;
  7. In the student part, query relevant functions, redirect to the Main page, and add, delete and change to ALLServlet;
  8. When modifying, the information obtained on the modified page is achieved by string interception.

 

❤️ END ❤️

6.0.js" type="text/javascript">



# Write at the end

All the contents are packaged and uploaded, and you need to download them yourself.

**Note nodes:**

1. Isolate the presentation layer from data access (low coupling);
2. Service And DAO The contents are consistent, Service_Impl And DAO_Impl The contents are consistent;
3. Servlet There are two methods of mapping;
4. Teacher registration and login use forwarding;
5. Form verification appears in teacher registration, teacher login and adding students;
6. action As an identification, it is used to judge the functions to be completed;
7. In the student section, query the relevant functions and redirect to the home page Main,Add, delete, change and redirect to `ALLServlet` ;
8. When modifying, the information obtained on the modified page is achieved by string interception.



&nbsp;

------

<div align="center">❤️&nbspEND&nbsp❤️</div>



Tags: Java MySQL JSP Tomcat servlet

Posted on Mon, 20 Sep 2021 04:09:55 -0400 by amir1985