微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Servlet 上的 switch 语句运行依赖于 JSP 链接的方法

如何解决使用 Servlet 上的 switch 语句运行依赖于 JSP 链接的方法

嗨,我对使用 JSP 和 servlet 构建网页还很陌生,我正在尝试使用 switch 语句根据用户单击的链接/按钮运行函数,但我尝试过的每个代码都无法运行该函数重定向到新页面,任何帮助将不胜感激我尝试使用 html 标记和 request.getcontextpath 但无济于事...它返回 404 错误或返回一个空白页面

这是我的 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,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,IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        studentDao.deleteStudent(id); //student object deleted
        response.sendRedirect("listStudents");
    }
    
    private void updateStudent(HttpServletRequest request,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,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);
    }

}

这是我的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="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>

对我做错的任何帮助将不胜感激。

解决方法

您需要告诉 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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。