我知道之前已经有人问过类似的问题,但由于某种原因它不起作用。我只是想检查用户是否已输入登录页面上的两个字段。如果没有,那么我想在 jsp 上显示消息,说明他们需要输入两个凭据。这是我的 JSP:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<h2>Some App</h2>
<form action="login" method="post">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="uname"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="pass" name="pass"></td>
</tr>
</table>
<br> <input type="button" value="Submit">
</form>
<c:out value= "${error}"/>
</body>
</html>
然后这是 servlet:
@WebServlet("/login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Login() {
super();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//Getting values from the form
String username = request.getParameter("uname");
String password = request.getParameter("pass");
System.out.println("Username is: "+ username);
System.out.println("Password is: "+ password);
//User user = new User();
if((username.equals(""))|| password.equals("")){
String message = "Please enter both the credentials";
request.setAttribute("error", message);
//RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
//rd.forward(request, response);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}
else{
RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
//Setting values in the session
session.setAttribute("username", username);
session.setAttribute("password", password);
}
}
由于我正在尝试使用 Maven 进行实验,因此这是我的 pom.xml 文件,其中添加了 jSTL jar 的依赖项:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
为什么 c:out 标签不打印任何内容?我究竟做错了什么?任何帮助将不胜感激。谢谢。
您正在混合两种向客户端返回响应的方式。尝试使用以下代码传递错误消息:
if((username == null)|| password == null) {
String message = "Please enter both the credentials";
request.setAttribute("error", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}
经验法则是,您必须将 request.setAttribute()
与 forward()
结合使用,将 request.getSession().setAttribute()
与 response.sendRedirect()
结合使用。
我是一名优秀的程序员,十分优秀!