簡體   English   中英

使用 servlet 在登錄頁面本身顯示密碼錯誤消息

[英]Display password error message in login page itself using servlet

我想在登錄頁面的特定<div>中顯示用戶名或密碼錯誤消息。

這是我的 login.html 代碼。

<div class="wrapper">
            <form class="form-signin" method="POST" action="j_security_check">       
                <h2 class="form-signin-heading text-center" id="head">Login</h2>
                <input type="text" class="form-control"  id="txtuser" name="j_username" placeholder="Username" required="required" />
            <input type="password" class="form-control" id="txtuser" name="j_password" placeholder="Password" required="required"/>
            <div id="error"></div>  
                <button class="btn btn-lg btn-default btn-block login1" id="txtuser" type="submit"><span class="glyphicon glyphicon-log-in"></span> Login</button>   
            </form>
</div>

這是我的 servlet 代碼

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

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

  RequestDispatcher rd=request.getRequestDispatcher("/login.html");

  out.println("<script>");
  out.println("document.getElementById('error').innerText=Sorry UserName or Password Error");
  out.println("</script>");

  rd.include(request, response);
}

該消息未顯示在登錄文件的<div id="error">

我找到了答案。它正在工作

這是我的 JSP

<%
String login_msg=(String)request.getAttribute("error");  
if(login_msg!=null)
out.println("<font color=red size=4px>"+login_msg+"</font>");
%>

這是我的 Servlet

request.setAttribute("error","Invalid Username or Password");
RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");            
rd.include(request, response);

只需將請求中的錯誤消息設置為屬性,如果不為空則顯示錯誤 div。

小服務程序:

request.setAttribute("error","Invalid Username/password");

登錄.jsp:

使用 JSTL 和 EL 訪問 JSP 中的請求屬性。 您可以使用<c:if>來測試錯誤消息。

<c:if test="${not empty requestScope.error}">
      <!-- Show the error div with message-->
</c:if>

使用隱式對象requestScope從請求范圍獲取屬性。


如果您只想使用 HTML,請嘗試一下。 這不是一個好方法,但您可以為 login.html 和 login_error.html 創建兩個單獨的 HTML 頁面,然后在出現任何錯誤時重定向到 login_error.html。

request.getRequestDispatcher("/login_error.html");

嘗試這個:

request.getRequestDispatcher("signin.html").include(request, response);
out.println("<script>document.getElementById('error').innerHTML='Sorry UserName or Password'; </script>");

不要忘記對字符串使用單引號。

只需移動

rd.include(request, response);

在您的打印語句之前,它應該可以工作。 這是因為您希望腳本在定義 div 后執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM