spring 如何在控制器中获取表单值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7524629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a form value in a controller
提问by Romi
I am using Spring MVC. How can I get text box value of the following snippet in my controller method?
我正在使用 Spring MVC。如何在我的控制器方法中获取以下代码段的文本框值?
<form name="forgotpassord" action="forgotpassword" method="POST" >
<ul>
<li><label>User:</label> <input type='text' name='j_username' /></li>
<li><label> </label> <input type="submit" value="OK" class="btn"></li>
</ul>
</form>
回答by Jaanus
You can use @RequestParamlike this:
你可以这样使用@RequestParam:
@RequestMapping(value="/forgotpassword", method=RequestMethod.POST)
public String recoverPass(@RequestParam("j_username") String username) {
//do smthin
}
回答by Gaurav
You can get single value by @RequestParamand total form values by @ModelAttribute.
您可以通过@RequestParam获得单个值, 通过@ModelAttribute获得总表单值。
Here is code for single field-
这是单个字段的代码-
@RequestMapping(value="/forgotpassword", method=RequestMethod.POST)
public String getPassword(@RequestParam("j_username") String username) {
//your code...
}
And if you have more values in form and want to get all as a single object- Use @ModelAttributewith spring form tag.
如果您在表单中有更多值并希望将所有值作为单个对象获取 - 将@ModelAttribute与 spring 表单标记一起使用。
回答by Madgr
1. Use Form tag library
Just add
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<form:form name="forgotpassord" action="forgotpassword" method="POST">
<ul>
<li><label>User:</label> <input type='text' name='j_username' /></li>
<li><label> </label> <input type="submit" value="OK" class="btn"></li>
</ul>
</form:form>
2. Now in controller
@RequestMapping(value="/forgotpassword", method = RequestMethod.POST)
public ModelAndView forgotpassword(@ModelAttribute("FormJSP_Name") User user,BindingResult result) {
String user = user.getjUsername(); //use it further
ModelAndView model1 = new ModelAndView("NextJSP_Name");
return model1;
}

