java - How to post generic objects to a Spring controller? -


i want create website displays form. fields of form depend on request parameter (and form backing bean). controller renders different forms:

@controller public class testcontroller {      @autowired     private mybeanregistry registry;      @requestmapping("/add/{name}")     public string showform(@pathvariable string name, model model) {         model.addattribute("name", name);         model.addattribute("bean", registry.lookup(name));          return "add";     }  } 

the corresponding view looks this:

<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> </head> <body>     <form method="post" th:action="@{|/add/${name}|}" th:object="${bean}">         <th:block th:replace="|${name}::fields|"></th:block>         <button type="submit">submit</button>     </form> </body> </html> 

following example fragment displays form fields:

<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> </head> <body>     <th:block th:fragment="fields">         <label for="firstname">first name</label><br />         <input type="text" id="firstname" th:field="*{firstname}" /><br />         <label for="lastname">last name</label><br />         <input type="text" id="lastname" th:field="*{lastname}" />     </th:block> </body> </html> 

the looked bean this:

public class myexamplebean {      private string firstname;      private string lastname;      // getters & setters  } 

the form rendered correctly, how can receive form in controller? , how can validate submitted bean? tried following method, can not work:

@requestmapping(value = "/add/{name}", method = requestmethod.post) public string processform(@pathvariable string name, @valid object bean) {     system.out.println(bean);      return "redirect:/add/" + name; } 

spring creates new instance of object submitted values lost. how can accomplish task?

if wanted deal limited number of beans, have 1 @requestmapping method each bean, delegating private method do job. can find example here.

if want able accept bean dynamically, have by hand spring automagically :

  • only use request , not model attribute
  • find bean in registry pathvariable name
  • do explicitely binding

but spring offers subclasses of webdatabinder helpers :

@requestmapping(value = "/add/{name}", method = requestmethod.post) public string processform(@pathvariable string name, webrequest request) {     //system.out.println(bean);      object mybean = registry.lookup(name);     webrequestdatabinder binder = new webrequestdatabinder(mybean);     // optionnaly configure binder     ...     // trigger actual binding of request parameters     binder.bind(request);     // optionally validate     binder.validate();     // process binding results     bindingresult result = binder.getbindingresult();     ...      return "redirect:/add/" + name; } 

Comments