Shangamesh T
Shangamesh T

Reputation: 3

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

This is the code (Validate.java Servlet File)

    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 File

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();
}

Output

I want the validate servlet to call welcome servlet but its asking me whether to download a validate servlet file .PFA for more details I am getting the popup to download Validate Ser

Upvotes: 0

Views: 934

Answers (1)

Henry
Henry

Reputation: 43798

The content type should be text/html (you wrote html/text) otherwise the browser does not know what to do with the file and asks for downloading it.

There are also a few other problems with the code worth mentioning

  1. You do not really check the result from the DB, so you will forward even if the user does not exist.
  2. You use the parameter name u in one servlet but username in the other.

Upvotes: 1

Related Questions