从一个doPost转发的RequestDispatcher将始终只转到另一个doPost?

时间:2015-04-16 18:26:18

标签: jsp servlets

我想我无法理解请求调度程序在场景中的工作方式。我只想了解Servlet如何交互以及如何调用其中的不同方法。

的login.html

<form action="LoginHandling" method="post">

    <table>
        <tr>
            <td>Username</td>
            <td><input type="text" id="one" name="username"></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><input type="password" id="two" name="password"></td>
        </tr>
    </table>
    <br>
    <button type="submit" value="submit">Submit</button>

Servlet处理Login.html

@WebServlet("/LoginHandling")
public class LoginHandling extends HttpServlet {

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

    HttpSession session = request.getSession();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    session.setAttribute("user", username);
    session.setAttribute("pass", password); 
    RequestDispatcher dispatcher = request.getRequestDispatcher("/WelcomeServlet");
    dispatcher.forward(request, response);
}

WelcomeServlet

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

    PrintWriter out= response.getWriter();
    HttpSession session = request.getSession();
    response.setContentType("text/html");

    String userIs = (String)session.getAttribute("user");
    String passwordEntered = (String)session.getAttribute("pass");

    if (passwordEntered.equals("accept")) {

        out.println("<html>");
        out.println("<head>");
        out.println("<title>");
        out.println("Welcome,"+ userIs);
        out.println("</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h2>Welcome, "+userIs+"</h2>"+"<br>");
        out.println("<p>This is the welcome page of our application</p><br><br>");
        out.println("</body>");
        out.println("</html>");
    } else {
        RequestDispatcher dispatcher = request.getRequestDispatcher("/Error.html");
        dispatcher.forward(request, response);
    }   

所以我所做的就是要求调度员将请求转发给/WelcomeServlet但是它如何识别该servlet中需要被调用的doPost()方法?是因为我doPost()中只有一个/WelcomeServlet,这会导致它表现得那样吗?如果有doGet()doPut()doDelete()怎么办?我将如何根据我的要求从Servlet中的一个方法与另一个不同Servlet中的另一个不同方法进行通信,例如从Servlet 2的Servlet 1到doGet()的{​​{1}}?也许我不能正确理解doPut()的正向方法。如何使用包括不同?我现在只是试图通过使用HTML页面来理解servlet间的通信,然后很快就会转向使用Servlet的JSP。谢谢。

0 个答案:

没有答案