JSP和Servlet服务器端验证

JSP和Servlet服务器端验证

问题描述:

我已经用JSP和Servlet完成了代码.当凭据不匹配时,我想在JSP页面中显示错误消息.我已经在servlet中编写了代码,但未正确显示在jsp页面中.我想在密码文本框下方显示错误消息.如果有任何可用的例子,请告诉我,这将是很大的帮助.

I have done code with JSP and Servlet. I want to show error message in JSP page when credentials doesn't match. I have written code in servlet but it's not displaying in jsp page correctly. I want to show error message below password text box. If any examples available pls let me know it would be a great help.

index.jsp

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

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

这是我的代码,请更正它.

Here is my code pls correct it.

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

Instead of writing out.print....set the error as a request attribute and in your index.jsp access the request attribute using ${requestAttributeKey} where requestAttributeKey is the key of your request attribute.