我已经用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>
<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 :(得分:0)
而不是写out.print ....而是将错误设置为请求属性,并在index.jsp中使用${requestAttributeKey}
访问请求属性,其中requestAttributeKey是您的请求属性的键。