这是我尝试 servlet 的第一天。这只是一个简单的登录功能,但我收到一个错误,该错误无法解释我做错了什么。它只是说
404: The requested resource is not available.
这是我的 servlet:
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String key = "ole";
String username = request.getParameter("username");
String password = request.getParameter("password");
response.sendRedirect("NewFile.jsp");
if (session.getAttribute(username).equals(key)
&& session.getAttribute(password).equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
这是我的登录页面:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login page</title>
</head>
<body>
Enter username and password below.
<form method=get action="hej">
<input type="text" user="username" /> <input type="password"
user="password" /> <input type="submit" value="Login" />
</form>
</body>
</html>
有一个名为 secret.jsp
的文件也一样,但里面没什么有趣的。我不明白为什么它返回 404。当我删除 if 语句时它才起作用......只有这样,就没有太多功能了。
最佳答案
正如你所说,它可以在没有 IF-ELSE
的情况下工作那我猜你的web.xml
输入正确。
首先将其更改为
<input type="password" user="password" />
这个
<input type="password" name="password" />
input tag
没有任何user
属性,它是 name
.
下一个错误是,您正在使用 session.getAttribute
访问您尚未设置的参数。
你的代码应该是
if (username.equals(key)
&& password.equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
session.getAttribute
仅当您的代码中有 session.setAttribute
时才能使用
示例session.setAttribute("username","ole");session.setAttribute("password","ole");
.
那么只有你可以通过 session.getAttribute("username")
获得一个值或session.getAttribute("password")
。但现在它只返回 NULL。所以代码将无法工作。
您可以将此代码添加到现有代码中,它将起作用。
session.setAttribute(username,username);
session.setAttribute(password,password);
你的完整代码应该是
String username = request.getParameter("username");
String password = request.getParameter("password");
session.setAttribute(username,username);
session.setAttribute(password,password);
//response.sendRedirect("NewFile.jsp");
if (session.getAttribute(username).equals(key)
&& session.getAttribute(password).equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
关于java - Servlet 中的 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26916178/