一个 Servlet 需要调用另一个 Servlet 以及响应和请求

One Servlet need to Call another Servlet along with response & request

这是代码(Validate.java Servlet 文件)

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String username = request.getParameter("u");
    String password = request.getParameter("p");
    Connection con = DBConnection.Connect();
    String sql = "select *from users where name=? and pass=?";
    try {
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, username);
        ps.setString(2, password);
        ResultSet rs = ps.executeQuery();

        request.getRequestDispatcher("WelcomeServlet").forward(request, response); //This line calls another servlet
        
    } catch (SQLException e) {
        System.out.println(e.toString());
    }

}

}


WelcomeServlet.java Servlet 文件

public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String username = request.getParameter("username");
    response.setContentType("html/text");
    PrintWriter pw = response.getWriter();
    pw.write("<html><body>");
    pw.write("<title>Welcome User</title>");
    pw.write("<h1>" + username + "</h1>");
    pw.write("</body></html>");
    pw.close();
}

输出

我希望验证 servlet 调用欢迎 servlet,但它询问我是否下载验证 servlet 文件 .PFA 以获取更多详细信息 I am getting the popup to download Validate Ser

内容类型应该是text/html(你写的是html/text)否则浏览器不知道如何处理该文件并要求下载它。

代码中还有一些其他问题值得一提

  1. 你并没有真正从数据库中查看结果,所以即使用户不存在你也会转发。
  2. 您在一个 servlet 中使用参数名称 u,但在另一个 servlet 中使用 username