[FIXED] RequestDispatcher Showing Page's source code Java Servlet


Everything is working fine else why RequestDispatcher showing source code of page?

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        String uName=req.getParameter("uEmail");
        String uPass=req.getParameter("uPass");
            DBConnection con=new DBConnection();
            if(con.login(uName, uPass)){
                HttpSession on = req.getSession();
                on.setAttribute("u_id", uName);
                RequestDispatcher dis= getServletContext().getRequestDispatcher("/login.jsp");
                PrintWriter write = res.getWriter();
                write.println("Wrong Username or Passowrd");
                dis.include(req, res);
        }catch(ClassNotFoundException | SQLException e){}


Page redirecting fine to given url /login.jsp and also showing the error message, but why as source code?

Wrong Username or Passowrd

<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <form action="LoginServlet" method="POST" />
            <input type="text" name="uEmail" />
            <br /><br />
            <input type="text" name="uPass" />
            <br /><br />
            <input type="Submit" name="Register" value="Register" />
            <br /><br />

direct link to login.jsp works fine.


from http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse)

The include method of Request Dispatcher gets the content of the resource that why you are getting the source code in browser.

I think what you want to do is forward the request to login.jsp so use forward method of request dispatcher.

As @JBNizet mentioned in his comment due to your message from Servlet, HTML is going to be invalid.

Answered By – Neenad

Answer Checked By – Robin (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published