当前位置: 首页 > 知识库问答 >
问题:

在servlet上使用switch语句运行依赖JSP链接的方法[重复]

鄢翰藻
2023-03-14

嗨,我对使用JSP和servlet构建web页面相当陌生,我试图使用switch语句来运行依赖于用户单击的链接/按钮的函数,但我尝试的每一个代码都无法运行函数或重定向到新页面,任何帮助都将不胜感激。我尝试使用html标记和request.getContextPath但没有用...它返回404错误或返回空白页

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();
                } 
            default:
                try {
                    listAllStudents(request, response);
                } 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"); //home page week04/StudentServlet | list all objects from table
        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 name = request.getParameter("name");
        String email = request.getParameter("email");
        Student newStudent = new Student(name, email);
        studentDao.insertStudent(newStudent); //student object inserted to table 
        response.sendRedirect("listStudents"); //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("listStudents");
    }
    
    private void updateStudent(HttpServletRequest request, HttpServletResponse response) 
            throws SQLException, IOException{
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        Student updateStudent = new Student(id, name, email);
        studentDao.updateStudent(updateStudent); //student object updated
        response.sendRedirect("listStudents");
    }
    
    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");
        request.setAttribute("student", currentStudent); //student object updated
        dispatch.forward(request, response);
    }

}
<%@ 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="sha384-... " crossorigin="anonymous">
</head>
<body>
    <div class="container-fluid">
    <nav class="navbar navbar-dark bg-primary pd-8">
        <a class="navbar-brand">XYZ University</a>
    </nav>
    <div class="container">

            <div class="container-fluid p-4">
               <a href="/new" class="btn btn-success" action="/new">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>ID</th>
                        <th>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.getId()%></td>
                            <td><%=studentDetails.getName()%></td>
                            <td><%=studentDetails.getEmail()%></td>
                            <td><a href="<%=request.getContextPath()%>/update">Update</a>
                                &nbsp;&nbsp;&nbsp;&nbsp; <a href="<%=request.getContextPath()%>/delete">Delete</a></td>
                        </tr>
                    <% 
                            }
                     }
                    %>
                </tbody>
                
            </table>
            </div>
        </div>
         
    </body>
</html>

这是我的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>
    <description></description>
    <display-name>StudentServlet</display-name>
    <servlet-name>StudentServlet</servlet-name>
    <servlet-class>week04.web.StudentServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>StudentServlet</servlet-name>
    <url-pattern>/StudentServlet</url-pattern>
  </servlet-mapping>
</web-app>

如果能帮助我做错什么,我将不胜感激。

共有1个答案

阮才俊
2023-03-14

您需要告诉web.xml中的servlet它处理指定的URL。

  <servlet-mapping>
    <servlet-name>StudentServlet</servlet-name>
    <url-pattern>/StudentServlet</url-pattern>
    <url-pattern>/new</url-pattern>
  </servlet-mapping>

此外,必须正确指定href。

<div class="container-fluid p-4">
    <a href="new" class="btn btn-success" action="/new">Add Student</a>
</div>
 类似资料:
  • 使用依赖注入框架(比如HK2)管理的服务时,使用方法链接是否可以接受? 我不确定是否允许它“缓存”实例,即使它只在注入范围内。 创建比萨饼的示例服务: 在这里,服务被注入到JAX-RS资源中:

  • 我有一个开关语句,它将与一组进行比较,其中每个匹配调用不同的方法。 然而,对我来说,这听起来像是可以通过使用链接到包含方法和参数数量的操作的哈希映射(HashMap)更优雅、更有效地实现的,这样我可以将每个方法都链接到哈希映射(HashMap),例如: 因此,Operation类将有N个不同的实例,每个实例都包含字符串、方法和参数数量 然后,我可以简单地使用类似的方法调用该方法(我知道这不是使用i

  • 问题内容: 由于各种业务原因,我想在我的一个类中保存一些静态ID。它们本来是但我想将它们更改为,以便可以对它们进行平等处理(即避免使用NPE) 当我将它们更改为Integer时,我的switch语句中出现错误。该文件说,整数应该是交换机内确定。 报价 [Switch]还适用于枚举类型(在Enum Types中讨论),String类和一些包装某些基本类型的特殊类:Character,Byte,Sho

  • switch 语句可以替代多个 if 判断。 switch 语句为多分支选择的情况提供了一个更具描述性的方式。 语法 switch 语句有至少一个 case 代码块和一个可选的 default 代码块。 就像这样: switch(x) { case 'value1': // if (x === 'value1') ... [break] case 'value2':