servlet和JSP之间的链接第二次不起作用

时间:2017-08-09 08:57:58

标签: java jsp servlets java-ee jdbc

使用MVC方式的JDBC,JSP和Servlet开发一个简单的CRUD应用程序。 在Container上运行代码之后,在单击更新链接的主页面中,它将被定向到一个JSP,我们可以在JSP中进行更改并遍历到主页面。

问题1 - 如果我尝试更新同一字段中的数据或更新按钮第二次不起作用的其他字段,则上次操作仅在Container上运行代码后第一次发生。

问题 - 2一旦我点击学生表中的更新链接,我将在点击保存“此页面上的按钮”后重定向到更新页面我应该被重定向回带有学生表的主页,但是此操作完成后,更新的学生即被删除。

如何解决这个问题?

我已附加此链接https://drive.google.com/file/d/0B7vBkqbv3cQUdnA3aFp3ZEpJSFk/view,人们可以在此处下载此应用并在您的系统上运行以防万一。

此致 -Shhiv。

StudentControlllerServlet - Servlet

package WebJDBC;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
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.sql.*;
import java.sql.*;
import java.util.List;

@WebServlet("/StudentControlllerServlet")
public class StudentControlllerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @ Resource (name ="jdbc/web_student_tracker")
    private DataSource datasource;

    @Override
    public void init() throws ServletException {
        super.init();

        //Create a instance of the student DB util
        //pass the connection pool datasource
        try{
        StudentDButil dbobject = new StudentDButil(datasource);
        }
        catch(Exception exe)
        {
            throw new ServletException(exe);
        }
    }

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

            String theCommand = request.getParameter("command");
            if(theCommand==null)
            {
                theCommand="LIST";
            }

            switch (theCommand)
            {
            case "LIST":
            listStudents(request,response);
            break;

            case "ADD":
                addStudents(request,response);
                break;

            case "LOAD":
                loadStudents(request,response);

            case "UPDATE":
                UpdateStudent(request,response);

            default:
                listStudents(request,response);
            }


        } catch (Exception e) {
            throw new ServletException(e);
        }

    }


private void UpdateStudent(HttpServletRequest request, HttpServletResponse response) throws Exception {

    int id = Integer.parseInt(request.getParameter("studentID"));
    String fname = request.getParameter("firstName");
    String lname = request.getParameter("lastName");
    String email = request.getParameter("email");

    Student updatedStudentdetails = new Student(id,fname,lname,email);

    StudentDButil.updateStudents(updatedStudentdetails);

    listStudents(request,response);

    }

//Used to create a pre-populated form for student upgrade
    private void loadStudents(HttpServletRequest request, HttpServletResponse response) throws Exception {


        //Read the student id from  the form data
    String studentID = request.getParameter("studentID");


        //get the student from the DB (dbutil)
        Student students = StudentDButil.getStudents(studentID);


        //place that student in the request attribute
        request.setAttribute("studentId", students);



        //Sending these stuff to the JSP page
        RequestDispatcher disp = request.getRequestDispatcher("update.jsp");
        disp.forward(request, response);
    }




    //Used to get the vaule from the form
    private void addStudents (HttpServletRequest request, HttpServletResponse response) throws Exception{


        //read the student info from the form
            String fname = request.getParameter("firstName");
            String lname = request.getParameter("lastName");
            String email = request.getParameter("email");


            //Create a new student object
            Student student = new Student(fname,lname,email);


            //add the student to the DB
            StudentDButil.addStudent(student);


            //send them back to the main list
            listStudents(request,response);
    }


    //Copying the student objects from the List in getStudents() to the students List ---- Forwarding the request to the View
    private void listStudents(HttpServletRequest request, HttpServletResponse response) throws Exception {


        // Get students from the DB util;

        List<Student> students = StudentDButil.getStudents();


        //Add students to the request object;
        request.setAttribute("List_Students", students );

        //Send it too the JSP

        RequestDispatcher dispatcher = request.getRequestDispatcher("/list_Student.jsp");
        dispatcher.forward(request, response);
    }




}

Student.java - 助手类

package WebJDBC;

public class Student {

    private int studentID;
    private String firstname;
    private String lastname;
    private String email;
    public Student(int id, String firstname, String lastname, String email) {
        super();
        this.studentID = id;
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
    }
    public Student(String firstname, String lastname, String email) {
        super();
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
    }

    public int getStudentID() {
        return studentID;
    }

    public void setStudentID(int studentID) {
        this.studentID = studentID;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getEmail() {
        return email;
    }

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

    public String toString() {
        return "Student [studentID=" + studentID + ", firstname=" + firstname + ", lastname=" + lastname + ", email="
                + email + "]";
    }




}

StudentDButil - 模型Servlet

package WebJDBC;

import java.util.ArrayList;
import java.util.List;

import javax.sql.*;
import java.sql.*;

public class StudentDButil {

    private static DataSource datasource;

    public StudentDButil(DataSource thedatasource)
    {
        datasource = thedatasource;
    }

    public static List<Student> getStudents() throws Exception
    {
        List<Student> stud = new ArrayList<Student>();
        Connection myCon = null;
        Statement myStat = null;
        ResultSet myRs = null;



        try{
            // Get a connection
            myCon = datasource.getConnection();

            // SQL statement

            myStat = myCon.createStatement();

            // Executing the query
            myRs = myStat.executeQuery("select * from student order by last_name");

            //Process ResultSet
            while(myRs.next())
            {
                // retrieve data from the result set
                int id = myRs.getInt("id");
                String firstname = myRs.getString("first_name");
                String lastname = myRs.getString("last_name");
                String email = myRs.getString("email");

                //create new student object
                Student newStudent = new Student(id, firstname, lastname, email);

                //add it to the list of students
                stud.add(newStudent);
            }

            return stud;
        }

        finally{
            close(myCon,myStat, myRs);

        }

    }

    private static void close(Connection myCon, Statement myStat, ResultSet myRs) {
        try{
            if(myRs != null)
            {
                myRs.close();
            }
            if(myStat != null)
            {
                myStat.close();
            }
            if(myCon != null)
            {
                myRs.close();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void addStudent(Student student) throws SQLException  {
        //Create sql for insert 
        Connection myCon = null;
        PreparedStatement myPStat = null;
        ResultSet myRs = null;


            try
            {
                //get Connection
                myCon = datasource.getConnection();

                //Creating SQL insert
                String sql = "insert into student"
                            + "(first_name, last_name, email)"
                            + "values(?,?,?) ";

                myPStat = myCon.prepareStatement(sql);

                //Get values from the paramas
                myPStat.setString(1, student.getFirstname());
                myPStat.setString(2, student.getLastname());
                myPStat.setString(3, student.getEmail());

                //Execute SQL
                myPStat.execute();
            }
            finally
            {
                close(myCon, myPStat, myRs);
            }
    }

    public static Student getStudents(String studentID) throws Exception {
        Student theStudent =null;
        Connection myCon = null;
        PreparedStatement myPStat = null;
        ResultSet myRs = null;
        int studid;

        //Convert Student ID to int
        studid = Integer.parseInt(studentID);
        //Get connection to the database
        try
        {
        myCon = datasource.getConnection();
        String Sql = "Select* from student where id=?";
        //Create prepared statement 
        myPStat = myCon.prepareStatement(Sql);
        //Get params
        myPStat.setInt(1, studid);
        //Execute
        myRs = myPStat.executeQuery();

        if(myRs.next())
        {
            String First_Name = myRs.getString("first_name");
            String Last_Name = myRs.getString("last_name");
            String Email = myRs.getString("email");

            theStudent = new Student(studid, First_Name, Last_Name, Email);
        }

        else
        {
            throw new Exception ("Couldn't find student ID:" + studid);
        }
        return theStudent;
        }
        finally
        {
        close(myCon, myPStat, myRs);
        }
    }

    public static void updateStudents(Student updatedStudentdetails)throws Exception {
        Connection myCon = null;
        PreparedStatement myPStat = null;
        ResultSet myRs = null;

        try {
            myCon = datasource.getConnection();

            String Sql = "Update student "
                        + "set first_name=? , last_name=?, email=? "
                        + "where id=?";

            myPStat = myCon.prepareStatement(Sql);

            myPStat.setString(1, updatedStudentdetails.getFirstname());
            myPStat.setString(2, updatedStudentdetails.getLastname());
            myPStat.setString(3, updatedStudentdetails.getEmail());
            myPStat.setInt(4, updatedStudentdetails.getStudentID());

            myPStat.execute();
        } 
        finally {
            close(myCon, myPStat, myRs);
        }

    }

    public static void DeleteStudent(String studentID) throws Exception {

        int studeid = Integer.parseInt(studentID);

        Connection myCon = null;
        PreparedStatement myPStat = null;
        ResultSet myRs = null;

        try {
            myCon = datasource.getConnection();

            String SQL = "DELETE FROM student WHERE id = ?";

            myPStat = myCon.prepareStatement(SQL);

            myPStat.setInt(1, studeid);

            myPStat.execute();
        } 
        finally
        {
            close(myCon, myPStat, myRs);
        }

    }   


    }

list_Student.jsp - 查看页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

    <%@ page import = "WebJDBC.*" %>

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Data Table</title>



<link type= "text/css" rel="stylesheet" href="css/style.css">

</head>


<body>

<div id ="wrapper">

<div id ="header">
 <h1> <cite>  Foobar University </cite> </h1>


</div>

<div id="Container">

<div id ="content">

<br>
<input type="button" value="Add-Student" 
 onclick="window.location.href='add-student-form.jsp';return false;"
class="add-student-button"
/>

<table>
 <tr>
    <th> First name </th>
    <th> Last name </th>
    <th> Email </th>
    <th> Actions </th>
 </tr>


    <c:forEach var ="ts" items="${List_Students}">

    <c:url var="templink" value="StudentControlllerServlet">
        <c:param name="command" value="LOAD" />
        <c:param name="studentID" value="${ts.studentID}"/>
    </c:url>

    <c:url var="templink2" value="StudentControlllerServlet">
        <c:param name="command" value="DELETE" />
        <c:param name="studentID" value="${ts.studentID}"/>
    </c:url>

    <tr>
        <td> ${ts.firstname} </td>
        <td> ${ts.lastname} </td>
        <td> ${ts.email} </td>
        <td> <a href="${templink}"> UPDATE </a> | <a href="${templink2}" 
        onclick="if(!(confirm(''Are you sure you want to Delete this student'))) return false"> DELETE </a> </td>
    </tr>
    </c:forEach>
</table>

</div>

</div>
<div align="right">

  <h5> <i> <a href ="index.html"> Back to the starter page </a></i> </h5>


</div>
</div>

</body>
</html>

add-student-form.jsp用于添加学生的JSP代码

<html>

<head>
    <title>Add Student</title>

    <link type="text/css" rel="stylesheet" href="css/style.css">
    <link type="text/css" rel="stylesheet" href="css/add-student-style.css">    
</head>

<body>
    <div id="wrapper">
        <div id="header">
            <h2>FooBar University</h2>
        </div>
    </div>

    <div id="container">
        <h3 id="header"> Add Student </h3>

        <form action="StudentControlllerServlet" method="GET">

            <input type="hidden" name="command" value="ADD" />

            <table>
                <tbody>
                    <tr>
                        <td><label>First name:</label></td>
                        <td><input type="text" name="firstName" /></td>
                    </tr>

                    <tr>
                        <td><label>Last name:</label></td>
                        <td><input type="text" name="lastName" /></td>
                    </tr>

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

                    <tr>

                        <td><label></label></td>
                        <td><input type="submit" value="Save" class="save" /></td>

                    </tr>

                </tbody>
            </table>
        </form>


        <div align="right">
        <p>
            <a href="StudentControlllerServlet" >Back to List </a>
        </p>
        </div>
    </div>
</body>

</html>

update.jsp

<html>

<head>
    <title>Update Student</title>

    <link type="text/css" rel="stylesheet" href="css/style.css">
    <link type="text/css" rel="stylesheet" href="css/add-student-style.css">    
</head>

<body>
    <div id="wrapper">
        <div id="header">
            <h2>FooBar University</h2>
        </div>
    </div>

    <div id="container">
        <h3 id="header"> Update Student </h3>

        <form action="StudentControlllerServlet" method="GET">

            <input type="hidden" name="command" value="UPDATE" />
            <input type="hidden" name="studentID" value="${studentId.studentID}" />
            <table>
                <tbody>
                    <tr>
                        <td><label>First name:</label></td>
                        <td><input type="text" name="firstName" value="${studentId.firstname}" /></td>
                    </tr>

                    <tr>
                        <td><label>Last name:</label></td>
                        <td><input type="text" name="lastName" value="${studentId.lastname}" /></td>
                    </tr>

                    <tr>
                        <td><label>Email:</label></td>
                        <td><input type="text" name="email" value="${studentId.email}" /></td>
                    </tr>

                    <tr>

                        <td><label></label></td>
                        <td><input type="submit" value="update" class="save"  /></td>

                    </tr>

                </tbody>
            </table>
        </form>
        <div align="right">
        <p>
            <a href="StudentControlllerServlet" >Back to List </a>
        </p>
        </div>
        </div>
        </body>
        </html>

0 个答案:

没有答案