一切工作正常else 爲什麼RequestDispatcher顯示頁面的源代碼?RequestDispatcher顯示頁面的源代碼Java Servlet
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String uName=req.getParameter("uEmail");
String uPass=req.getParameter("uPass");
try{
DBConnection con=new DBConnection();
if(con.login(uName, uPass)){
HttpSession on = req.getSession();
on.setAttribute("u_id", uName);
res.sendRedirect("dashboard.jsp");
}
else{
RequestDispatcher dis= getServletContext().getRequestDispatcher("/login.jsp");
PrintWriter write = res.getWriter();
write.println("Wrong Username or Passowrd");
dis.include(req, res);
}
}catch(ClassNotFoundException | SQLException e){}
}
}
頁面重定向罰款定的url /login.jsp
並顯示錯誤消息,但爲什麼作爲源代碼?
Wrong Username or Passowrd
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<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 />
</form>
</body>
</html>
直接鏈接到login.jsp
工作正常。
因爲您在HTML標籤之前打印了「錯誤的用戶名或密碼」,導致HTML無效? –
@JBNizet那麼如何使用Dispatcher呢?我正在使用其他測試應用程序,即使相同的調度程序代碼也能正常工作。 – UnKnown
除了在包含JSP之前不應將文本寫入響應,您所擁有的都很好。通過這樣做,您就會生成無效的HTML。將錯誤消息存儲在請求屬性中,並讓您的JSP代碼從該屬性中獲取並在頁面內打印它必須打印的位置。沒有理由包括:你應該轉發。 –