0

I am new to spring mvc but I would like to know how I can access the data that the user inputs in a form.

these are some code snippets:

My controller

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        return new A();
    }

where A is the class containing the 'model' that the form should return.

My view

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<form:form>
        <table>
            <tr>
                <td><form:label path="amount">Amount:</form:label></td>
                <td><form:input path="amount"/></td>
                <td><form:errors path="amount"/></td>
            </tr>
            ... some more fields
            <tr>
                <td><form:label path="message">Message:</form:label></td>
                <td><form:input path="message"/></td>
                <td><form:errors path="message"/></td>
            </tr>
            <tr>
               <td colspan=3 align=right>
                   <button type="submit">Transfer</button>
               </td>
            </tr>
       </table>
</form:form>

Q: How and where can I access the amount and message field in my controller to perform some action with the data? (perhaps after validating).

voluminat0
  • 866
  • 2
  • 11
  • 21
  • You can check this [thread][1]. There are many this kind of questions already. [1]: http://stackoverflow.com/questions/10198335/basic-spring-mvc-data-binding – Mavlarn Nov 13 '14 at 09:04

2 Answers2

0

Appearently, the model was available in the onSubmit method:

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,
        Object command, BindException errors) throws Exception {

        ModelAndView mv = super.onSubmit(request,response,command,errors);

        //TODO: SOME VALIDATING

        A smth = (A)command;
        //Do something with your object

        return mv;
}
voluminat0
  • 866
  • 2
  • 11
  • 21
0

I assume class A has attributes amount and message with appropriate getters and setters.

Your controller method should then look like :

@RequestMapping("/url/for/the/form/action")
public String formBackingObject(@ModelAttribute A a, BindingResult error) {
    // Spring automagically creates a A object and loads it with form parameters
    // do you stuff, call services methods
    return "viewname";
}

viewname is the name of the view, or can be "redirect:/other/url" if you use the post-redirect-get pattern.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252