SpringMVC:在尝试POST请求调用重定向时抛出415不支持的媒体类型(SpringMVC : Throws 415 Unsupported Media Type while attempting POST request call for redirection)
浏览器响应如下:
服务器拒绝此请求,因为请求实体的格式不受所请求方法所请求资源的支持。
而不是重定向到主页(home.jsp)
welcome.jsp文件:
<form method ="POST" action = "<c:url value='/login'/>" >
<input id="name" name="name" type="text">
<input id="password" name="password" type="password">
<input type="submit" id="loginNew" value="LoginNew">
</form>
控制器类:
@RequestMapping( value="/login" , method = RequestMethod.POST )
public ModelAndView authenticate ( @RequestBody User userObj ) throws Exception {
ModelAndView modelAndView = new ModelAndView ();
try {
user = userService.authenticateUser ( userObj );
} catch ( Exception e ) {
e.printStackTrace();
}
modelAndView.setViewName("/home");
return modelAndView;
}
Browser response like below:
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Instead of redirecting to the home page ( home.jsp )
welcome.jsp file:
<form method ="POST" action = "<c:url value='/login'/>" >
<input id="name" name="name" type="text">
<input id="password" name="password" type="password">
<input type="submit" id="loginNew" value="LoginNew">
</form>
Controller class:
@RequestMapping( value="/login" , method = RequestMethod.POST )
public ModelAndView authenticate ( @RequestBody User userObj ) throws Exception {
ModelAndView modelAndView = new ModelAndView ();
try {
user = userService.authenticateUser ( userObj );
} catch ( Exception e ) {
e.printStackTrace();
}
modelAndView.setViewName("/home");
return modelAndView;
}
更新时间:2022-09-23 21:09
最满意答案 ***********************************解决方案
通过在方法param中添加@ModelAttribute而不是@RequestBody解决了问题,然后按预期重定向到home.jsp页面。
@RequestMapping( value="/login" , method = RequestMethod.POST )
public ModelAndView authenticate ( @ModelAttribute User userObj ) throws Exception {
ModelAndView modelAndView = new ModelAndView ();
try {
user = userService.authenticateUser ( userObj );
} catch ( Exception e ) {
e.printStackTrace();
}
modelAndView.setViewName("/home");
return modelAndView;
}
By adding @ModelAttribute instead of @RequestBody in the method param solved the issue and then redirected to the home.jsp page as expected.
@RequestMapping( value="/login" , method = RequestMethod.POST )
public ModelAndView authenticate ( @ModelAttribute User userObj ) throws Exception {
ModelAndView modelAndView = new ModelAndView ();
try {
user = userService.authenticateUser ( userObj );
} catch ( Exception e ) {
e.printStackTrace();
}
modelAndView.setViewName("/home");
return modelAndView;
}