我要求将commandbean或form bean对象放入控制器,而不使用ModelMap或HttpServletRequest中的@ModelAttribute
或其他任何东西。
我的代码是:
JSP:
<form:form commandName="user" method="POST"
action="${pageContext.request.contextPath}/user/createUser">
Name:<form:input path="name" />
Password:<form:input path="password" />
<input type="submit"/>
</form:form>
控制器:
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public String setupForm(ModelMap model) {
modelMap.addAttribute("user", new User());
return "userRegistration";
}
@RequestMapping(value = "/createUser", method = RequestMethod.POST)
public String createUser(ModelMap model,HttpServletRequest request) {
User user=(User)model.get("user");// Retruns null
//Tried using request object but user object is not available in it.
return "message";
}
}
我尝试了不同的方法,但没有成功。
答案 0 :(得分:1)
您可以实现HandlerMethodArgumentResolver手动创建bean,然后(例如)使用WebMvcConfigurerAdapter来声明它。参数解析器supportsParameter方法应该检查参数的预期类型。之后,您可以在Controller中添加所需类型的参数。
答案 1 :(得分:0)
你可以手动手绘,就像你不知道Spring的神奇之处一样:只需HttpServletRequest
并获取其参数来喂你的User
。它可能看起来像:
@RequestMapping(value = "/createUser", method = RequestMethod.POST)
public String createUser(ModelMap model,HttpServletRequest request) {
User user= new User();
String name = request.getParameter("name");
String password = request.getParameter("password");
if (name != null) {
user.setName(name);
}
if (password!= null) {
user.setPassword(password);
}
model.addAttribute("user", user);
//Tried using request object but user object is not available in it.
return "message";
}
或者以更简洁的方式:user.setName(request.getParameter("name");