【问题标题】:Restart Servlet after form submit提交表单后重启 Servlet
【发布时间】:2021-10-08 03:58:45
【问题描述】:

我对在 JSP 中使用 servlet 还很陌生,在提交表单 jsp 后尝试重定向回 servlet 主页 JSP 的开头时遇到了问题,我不确定如何完成此任务或者它是否甚至可以做到这一点,我尝试的方法充其量只能返回主页 jsp,但没有调用 servlet 默认函数来从 jdbc 获取数据。我已经尝试了 sendredirect() 并请求调度程序无济于事,如果我出错了,我们将不胜感激。

我有一个 servlet 代码来处理所有操作,包括插入和更新,这些操作在重定向/重新加载时会出现问题

public class StudentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private StudentDao studentDao;

    public StudentServlet() {
        this.studentDao = new StudentDao();
    }

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

    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sPath = request.getServletPath();
        //switch statement to call appropriate method
        switch (sPath) {
            case "/new":
                try {
                    showNewForm(request, response);
                } catch (ServletException | IOException e) {
                    e.printStackTrace();
                }
                break;
            case "/insert":
                try {
                    insertStudent(request, response);
                } catch (SQLException | IOException e) {
                    e.printStackTrace();
                } 
                break;
            case "/delete":
                try {
                    deleteStudent(request, response);
                } catch (SQLException | IOException e) {
                    e.printStackTrace();
                }
                break;
            case "/update":
                try {
                    updateStudent(request, response);
                } catch (SQLException | IOException e) {
                    e.printStackTrace();
                }
                break;
            case "/edit":
                try {
                    editStudent(request, response);
                } catch (ServletException | IOException e) {
                    e.printStackTrace();
                }
                break;
            case "/StudentServlet":
                try {
                    listAllStudents(request, response); 
                } catch (ServletException | IOException | SQLException e) {
                    e.printStackTrace();
                } 
                break;
            default:
                try {
                    listAllStudents(request, response); //home page = .../week04/StudentServlet
                } catch (ServletException | IOException | SQLException e) {
                    e.printStackTrace();
                } 
                break; 
            } 
    }

    // functions to fetch data from studentDao and display data on appropriate jsp
    private void listAllStudents(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException, SQLException {
        List<Student> allStudents = studentDao.selectAllStudents();
        request.setAttribute("listStudents", allStudents);
        RequestDispatcher dispatch = request.getRequestDispatcher("student-list.jsp"); 
        dispatch.forward(request, response);
    }
    
    private void showNewForm(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
        dispatch.forward(request, response);
    }

    private void insertStudent(HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException{
        String firstname = request.getParameter("firstname");
        String lastname = request.getParameter("lastname");
        String email = request.getParameter("email");
        Student newStudent = new Student(firstname, lastname, email);
        studentDao.insertStudent(newStudent); //student object inserted to table 
        response.sendRedirect("/StudentServlet"); //redirect to home page
    }
    
    private void deleteStudent(HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        studentDao.deleteStudent(id); //student object deleted
        response.sendRedirect("/StudentServlet");
    }
    
    private void updateStudent(HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException{
        String sId = request.getParameter("id");
        int id = Integer.parseInt(sId);
        String firstname = request.getParameter("firstname");
        String lastname = request.getParameter("lastname");
        String email = request.getParameter("email");
        Student updateStudent = new Student(id, firstname, lastname, email);
        studentDao.updateStudent(updateStudent); //student object updated
        response.sendRedirect("/StudentServlet");
    }
    
    private void editStudent(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Student currentStudent = studentDao.selectStudent(id);
        RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp"); //student form called with current student info loaded
        request.setAttribute("student", currentStudent); 
        dispatch.forward(request, response);
    }
    
}

这是我的 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://java.sun.com/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee" id="WebApp_ID" version="2.4">

 
  
  
  <servlet>
    <servlet-name>StudentServlet</servlet-name>
    <servlet-class>week04.web.StudentServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>StudentServlet</servlet-name>
    <url-pattern>/</url-pattern>
    <url-pattern>/StudentServlet</url-pattern>
    <url-pattern>/new</url-pattern>
    <url-pattern>/update</url-pattern>
    <url-pattern>/insert</url-pattern>
    <url-pattern>/delete</url-pattern>
    <url-pattern>/edit</url-pattern>
  </servlet-mapping>
</web-app>

这是我的主页 JSP,我将其命名为 student-list.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.util.*" import="week04.model.Student"%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" 
    integrity="sha38-...." crossorigin="anonymous">
</head>
<body>
    <nav class="navbar navbar-dark bg-primary pd-8">
         <a class="navbar-brand">&nbsp;&nbsp;&nbsp;&nbsp;XYZ University</a>
    </nav>
    <div class="container-fluid">
    <div class="container">

            <div class="form container-fluid p-4">
               <a href="<%=request.getContextPath()%>/new" class="btn btn-success" >Add
                    Student</a>
            </div>
            <br>
            
            <!--Assigning ArrayList object containing student data to the local object -->
            <% ArrayList<Student> studentList = (ArrayList) request.getAttribute("listStudents"); %> 
            <table class="table table-bordered">
            
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <%
                     if(request.getAttribute("listStudents") != null)  {
                            Iterator<Student> iterator = studentList.iterator();
                            while(iterator.hasNext()) {
                                Student studentDetails = iterator.next();
                    %>
                        <tr><td><%=studentDetails.getFirstname()%></td>
                            <td><%=studentDetails.getLastname()%></td>
                            <td><%=studentDetails.getEmail()%></td>
                            <td><a href="<%=request.getContextPath()%>/edit?id=<%=studentDetails.getId()%>">Update</a>
                                &nbsp;&nbsp;&nbsp;&nbsp; <a href="<%=request.getContextPath()%>/delete?id=<%=studentDetails.getId()%>">Delete</a></td>
                        </tr>
                    <% 
                            }
                     }
                    %>
                </tbody>
                
            </table>
            </div>
        </div>
         
    </body>
</html>

这是我处理插入和更新数据的表单文件:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, intial-scale=1 shink-to-fit=yes">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
     integrity="sha384-...">
</head>
<body>
    <nav class="navbar navbar-dark bg-primary pd-8">
         <a class="navbar-brand">&nbsp;&nbsp;&nbsp;&nbsp;XYZ University</a>
    </nav>
    <div class="container col-md-5 p-4">
        <div class="card">
            <div class="card-body">
        <% System.out.println(request.getAttribute("student") + "hello"); %>
                <% if (request.getAttribute("listStudents") != null || request.getAttribute("student") != null) { %>
                    <form action="<%=request.getContextPath()%>/update" method="post">
                    <% } else { %>
                    <form action="<%=request.getContextPath()%>/insert" method="post">
                    <% } %>
    
                    <div>
                        <h2>
                        <% if (request.getAttribute("student") != null) { %>
                            Edit Student
                        <% } else { %>
                            Add New Student
                        <% } %>
                        </h2>
                    </div>

                <% if (request.getAttribute("student") != null) { %>
                    <input type="hidden" name="id" value="${student.id}" />
                <% } %>

                <fieldset class="form-group">
                    <legend> First Name</legend>
                    <% if (request.getAttribute("student") != null) { %>
                       <input type="text" value="${student.firstname}" class="form-control" 
                       name="fistname" required="required">
                    <% }  else { %>
                        <input type="text" value="" class="form-control" name="firstname" required="required">
                    <% } %>
                </fieldset>
                
                <fieldset class="form-group">
                    <legend>Last Name</legend>
                    <% if (request.getAttribute("student") != null) { %>
                       <input type="text" value="${student.lastname}" class="form-control" 
                       name="lastname" required="required">
                    <% }  else { %>
                        <input type="text" value="" class="form-control" name="lastname" required="required">
                    <% } %>
                </fieldset>

                <fieldset class="form-group">
                <legend>Email</legend>
                <% if (request.getAttribute("student") != null) { %>
                    <input type="text" value="${student.email}" class="form-control" name="email">
                <% }  else { %>
                    <input type="text" value="" class="form-control" name="email">
                <% } %>     
                </fieldset>
                
                <button type="submit" class="t-3 btn btn-success">Save</button>
                </form>
            </div>
        </div>
    </div>
    
</body>
</html>

任何帮助将不胜感激,我不知道我的 servlet 配置、xml 或表单页面配置是否有问题。

【问题讨论】:

  • 服务器日志中有异常吗?
  • @Ravi K Thapliyal 是的,如果我包含 case 语句 /StudentServlet,我会得到一个 classnotfoundexception,如果我不包含它,我会成功加载页面
  • 我也试过使用response.sendRedirect("/")request.getRequestDispatcher("/") 但他们把我送回主页但现在数据没有插入数据库
  • 我得到一个 SQLIntergrityConstraintViolation 列 firstname 不能为空,尽管我在字段中输入了一个名称
  • @Ravi K Thapliyal response.sendRedirect("/") 诀窍是否必须将 if 语句重新包含到 jsp 表单代码中导致更新并在混淆的地方插入数据/变量

标签: java xml jsp servlets


【解决方案1】:

您收到异常

SQLIntergrityConstraintViolation:列名不能为空

因为您的 名字 表单组中有一个小错字。

<% if (request.getAttribute("student") != null) { %>
   <input type="text" value="${student.firstname}" class="form-control" 
    name="fistname" required="required">
<% }  else { %>
    <input type="text" value="" class="form-control" name="firstname" required="required">
<% } %>

if 块中,&lt;input&gt; 文本字段的name="fistname" 拼写错误,而name="firstname"else 块中是正确的。

这就是为什么您的 insert 仅在通过具有正确字段名称的 else 块时才能与 if-else 一起使用。一旦你改正了这个错字,insert 应该也可以在没有if-else 的情况下按照之前的规定开始工作。

【讨论】:

    猜你喜欢
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 2018-10-05
    相关资源
    最近更新 更多