Я относительно новичок в весеннем mvc и изучал некоторую форму submit. Однако в настоящее время у меня есть ошибка HTTP 405, которая будет означать, что я не могу опубликовать сообщение.
Ошибка заключается в том, что HTTP-сообщение не поддерживается. Я googled и проверял, что мне нужно будет переопределить и реализовать метод doPost в моем коде, но я не уверен, как использовать сервлет.
Переопределяя метод doPost, как я могу обеспечить применение нового метода doPost?
Это мой класс контроллера:
package com.**.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.**.dao.*;
import com.**.model.User;
@Controller
public class MainController {
@Autowired
private UserDAO UserDAO;
@RequestMapping(value = {"/hello", "/welcome**" }, method = RequestMethod.GET)
public ModelAndView defaultPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Login Form - Database Authentication");
model.addObject("message", "This is default page!");
model.setViewName("hello");
return model;
}
@RequestMapping(value = "/admin**", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Login Form - Database Authentication");
model.addObject("message", "This page is for ROLE_ADMIN only!");
model.setViewName("admin");
return model;
}
@RequestMapping(value = {"/h", "/login"}, method = RequestMethod.GET)
public ModelAndView login(@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
//for 403 access denied page
@RequestMapping(value = "/402", method = RequestMethod.GET)
public ModelAndView accesssDenied() {
ModelAndView model = new ModelAndView();
//check if user is login
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
UserDetails userDetail = (UserDetails) auth.getPrincipal();
System.out.println(userDetail);
model.addObject("username", userDetail.getUsername());
}
model.setViewName("402");
return model;
}
@RequestMapping(value = "/Account/userManagement", method = RequestMethod.GET)
public ModelAndView accountPage() {
ModelAndView model = new ModelAndView();
model.setViewName("Account/userManagement");
return model;
}
@RequestMapping(value = "Notification/notification", method = RequestMethod.GET)
public ModelAndView NotificationPage() {
ModelAndView model = new ModelAndView();
model.setViewName("Notification/notification");
return model;
}
@RequestMapping(value = "test", method = RequestMethod.POST)
public ModelAndView register(@ModelAttribute("user-entity") User user, BindingResult result)
{
ModelAndView model = new ModelAndView();
UserDAO.create(user);
model.setViewName("hello");
return model;
}
@RequestMapping(value = {"/","/Account/registration"}, method = RequestMethod.GET)
public ModelAndView registerPage()
{
ModelAndView model = new ModelAndView("/Account/registration", "user-entity", new User());
return model;
}
}
это мой код формы
<form:form action="test" method="POST" modelAttribute = "user-entity">
<td> <td><form:label path="Username">Name:</form:label></td>
<td>
<form:input path="Username"></form:input>
</td>
</tr>
<tr>
<td>Password: </td>
<td><form:input type = "password" path = "Password" ></form:input></td>
</tr>
</form:form>
исключение
Aug 03, 2014 6:12:53 PM org.springframework.web.servlet.PageNotFound handleHttpRequestMethodNotSupported ПРЕДУПРЕЖДЕНИЕ: метод запроса "POST" не поддерживается
Это ссылка на мой предыдущий вопрос
Я изменил свое действие формы на
<form:form action="/<packagename>/Account/test" method="POST" modelAttribute = "user-entity">
URL-адрес по умолчанию страницы регистрации
http://localhost:8080/<package name>/
и я обновил свой соответствующий код контроллера для
@RequestMapping(value = "/<package name>/Account/test", method = RequestMethod.POST)
public ModelAndView register(@ModelAttribute("user-entity") User user, BindingResult result)
{
ModelAndView model = new ModelAndView();
UserDAO.create(user);
model.setViewName("/Account/test");
return model;
}
URL-адрес, который я пытаюсь получить, это /Account/test
Проблема заключается в том, что ваш URL-адрес не поддерживает метод POST. Просмотрев все ваши запросы GET, все они начинаются с относительного пути, а затем реального URL, например:
/Notification/notification
/Account/userManagement
/h <-- this seems ridiculous...
/admin
/hello
И в вашей форме вы отправляете сообщение "test":
<form:form action="test" method="POST" modelAttribute = "user-entity">
<!-- rest of your html code ... -->
</form:form>
Это означает, что любое сообщение будет отправлено в /<whatever_goes_here>/test
ie (так как вы не укажете, какой из них является вашим текущим представлением):
/Notification/test
/Account/test
/test <-- this may work as expected
/test <-- this may work as expected
/test <-- this may work as expected
И у вас нет двух первых сопоставлений.
Решение. Исправьте свои URL-адреса или перейдите к реальному URL-адресу, используя HttpServletRequest#getContextPath
. Примечание: избегайте использования сценариев, вместо этого используйте язык выражений в вашем JSP: ${request.contextPath}
.
<form:form action="${request.contextPath}/test" method="POST" modelAttribute = "user-entity">
doPost
если вы используете Spring. Просто предоставьте соответствующий метод обработчика в вашем@Controller
.