一尘不染

JSP和Servlet服务器端验证

jsp

我已经用JSP和Servlet完成了代码。当凭据不匹配时,我想在JSP页面中显示错误消息。我已经在servlet中编写了代码,但是未正确显示在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

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

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


阅读 213

收藏
2020-06-10

共1个答案

一尘不染

无需写出.print
....将错误设置为请求属性,而在index.jsp中,使用${requestAttributeKey}requestAttributeKey是请求属性的键来访问请求属性。

2020-06-10