Romi
Romi

Reputation: 4921

How to get a form value in a controller

I am using Spring MVC. How can I get text box value of the following snippet in my controller method?

<form name="forgotpassord" action="forgotpassword" method="POST" >
    <ul>
        <li><label>User:</label> <input type='text' name='j_username' /></li>
        <li><label>&nbsp;</label> <input type="submit" value="OK" class="btn"></li>
    </ul>
</form>

Upvotes: 25

Views: 56225

Answers (3)

Gaurav
Gaurav

Reputation: 657

You can get single value by @RequestParam and total form values by @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 @ModelAttribute with spring form tag.

Upvotes: 1

Jaanus
Jaanus

Reputation: 16531

You can use @RequestParam like this:

@RequestMapping(value="/forgotpassword", method=RequestMethod.POST)
public String recoverPass(@RequestParam("j_username") String username) {
    //do smthin
}

Upvotes: 37

Madgr
Madgr

Reputation: 7

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>&nbsp;</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;
    }

Upvotes: -2

Related Questions