2017-01-01 69 views
0

我已经完成了JSP和Servlet的代码。当证书不匹配时,我想在JSP页面中显示错误消息。我已经在servlet中编写代码,但它不能正确显示在jsp页面中。我想在密码文本框下方显示错误消息。如果有任何可用的例子,请让我知道这将是一个很大的帮助。JSP和Servlet服务器端验证

的index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
    pageEncoding="ISO-8859-1"%> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
     <title>Login Application</title> 
    </head> 
    <body> 
     <form action="loginServlet" method="post"> 
     User Login 
     <br> 
     User ID 
     <input type="text" name="username" > 
     <br><br> 
     Password 
     <input type="password" name="userpass"><br> 
     &nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Login" > 
     </form> 
    </body> 
</html> 

LoginServlet.java

package com.test.servlets; 
import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.RequestDispatcher; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 
import com.amzi.dao.LoginDao; 

public class LoginServlet extends HttpServlet{ 

    private static final long serialVersionUID = 1L; 

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

     response.setContentType("text/html"); 
     PrintWriter out = response.getWriter(); 

     String n=request.getParameter("username"); 
     String p=request.getParameter("userpass"); 

     HttpSession session = request.getSession(false); 
     if(session!=null) 
     session.setAttribute("name", n); 

     if(LoginDao.validate(n, p)){ 
      RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp"); 
      rd.forward(request,response); 
     } 
     else{ 
      out.print("Wrong Credentials"); 
      RequestDispatcher rd=request.getRequestDispatcher("index.jsp"); 

      rd.include(request,response); 


     } 

     out.close(); 
    } 
} 

这里是我的代码,请更正。

+0

LoginDao.validate()是否经过测试?这很可能是罪魁祸首 – GurV

回答

0

而不是写出out.print ....将错误设置为请求属性,并在您的index.jsp中使用${requestAttributeKey}访问请求属性,其中requestAttributeKey是请求属性的关键字。