有人可以告诉我为什么我会出错:HTTP状态405 –不允许的方法吗?我正在尝试完成方法doPost()之后,将用户重定向到“ / logout”控制器,其中是无效会话。这很有趣,因为方法被调用了,做所有应该做的事(更新数据库中的用户),但是在发送给用户错误405之后。另一个我使用doPost()的地方(例如:LoginController)运行良好,但是当我尝试强制查找时错误,我没有看到任何:<
<div class="container">
<div class="col-md-8 col-md-offset-2">
<form method="post" action="account">
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" class="form-control" id="email"
value="${sessionScope.loggedUser.email}" required aria-describedby="emailHelp"
placeholder="Enter email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input name="password" type="password" minlength="5" maxlength="40" required class="form-control"
id="password" placeholder="Password">
</div>
<div class="form-group">
<label for="repeatPassword">Repeat Password</label>
<input name="repeatPassword" type="password" minlength="5" maxlength="40" required class="form-control"
id="repeatPassword" placeholder="Password">
</div>
<input class="btn btn-lg btn-primary btn-block" type="submit" value="Save changes"/>
</form>
</div>
</div>
@WebServlet("/account")
public class AccountController extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
String repeatPassword = req.getParameter("repeatPassword");
if (email == null || password == null || repeatPassword == null) {
doGet(req, resp);
return;
}
if (password.equals(repeatPassword)) {
HttpSession session = req.getSession();
User user = (User) session.getAttribute("loggedUser");
user.setEmail(email);
String sha1hexPassword = DigestUtils.sha1Hex(password);
user.setPassword(sha1hexPassword);
UserService service = new UserService();
try {
service.update(user);
} catch (UpdateObjectException e) {
e.printStackTrace();
}
req.getRequestDispatcher("/logout").forward(req, resp);
} else {
req.setAttribute("errorMessage", "Passwords not the same");
req.setAttribute("fragment", "account");
req.getRequestDispatcher("WEB-INF/index.jsp").forward(req, resp);
}
}
}
感谢任何提示。
您的doGet()方法调用位于服务器doPost()代码内部。您应该重定向响应,doGet用于接收GET请求和任何查询字符串。
问题已解决。在这里:
req.getRequestDispatcher("/logout").forward(req, resp);
我应该做
resp.sendRedirect(req.getContextPath()+"/logout");
因为在“ / logout”中,我只有doGet()方法,如果我使用“ getRequestDispatcher()”,则它会尝试找到doPost()方法。