Search code examples
javajspspring-mvccontrollers

How to send java object from jsp to Spring MVC 3 Controller


Hello All I am new to Spring environment.

I am doing this in jsp page.

<form action="add">
             Name : <input type="text" name="name"/>
             Contact : <input type="text" name="contact"/>
             Age : <input type="text" name="age"/>
             <input type="submit" name="Submit"/> </form>

I want send this data into controller method as Employee object not as individual fields.

I am doing something like that in controller

 @RequestMapping(value="/add" Method=RequestMethod,POST)    
 public String addEmployee(@ModelAttribute("employee") Employee 
 employee, Model model) {  
 ...
 ... 
  }

I think know how to handle object in controller method but don't know how to send object to controller from jsp. Please guide.


Solution

  • Try This: First Change your code to below,

    @RequestMapping(value="/add", method=RequestMethod.POST)    
    public String addEmployee(@ModelAttribute("employee") Employee 
       employee, Model model) {  
    //instead of Method=RequestMethod.POST your code were
    //Method=RequestMethod,POST
     .. 
     }
    

    After that, say If you have an Employe class with setters and getters, then the name attribute in your form's input tag must have the same name as your employee class's property(filed) name.

    If you will do the above step, Spring will do implicit DataBinding for you which you can utilize by using @ModelAttribute annotation