我知道類似的問題早些時候被問過,但由於某些原因,它不起作用。我只是想檢查用戶是否在登錄頁面上輸入了兩個字段。如果沒有,那麼我想在jsp上顯示消息,說他們需要輸入兩個憑證。這裏是我的JSP:從jsp發送值到servlet然後返回到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標籤不打印任何東西?我究竟做錯了什麼?任何幫助將不勝感激。謝謝。
你看到你的輸出是什麼?您可以調試的一種方法是在您的方法中添加一些System.out.println()值,以確保您達到所需的區域。此外,請注意,您在「index.jsp」中輸入了「I」 – bphilipnyc
@bphilipnyc我無法訪問servlet。請在下面檢查我對NaMaN用戶的回覆。我現在也正在更新我的代碼以用於servlet。謝謝。 – user3044240