Announcement Announcement Module
No announcement yet.
Best Practice - Passing objects to form Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Best Practice - Passing objects to form

    Let's say you have a bean which maps closely to its underlying entry in a table:
    public class CustomerBean {
    	private int id;
    	private String name;
    And you implement Controllers and JSPs for CRUD operations.
    Typically the edit operation would have 2 methods: 1 for GET to populate the form, 1 for POST to process the form:
        @RequestMapping(value="/editCustomer.htm", method = RequestMethod.GET)
        public String editCustomer(@RequestParam("id") Integer id, ModelMap model)
        	CustomerBean cust = customerManager.get(id);
        	model.addAttribute("CUSTOMER_INFO", cust); 
        @RequestMapping(value="/editCustomer", method=RequestMethod.POST)
        public ModelAndView processEditCustomer(
        		@ModelAttribute("CUSTOMER_INFO") CustomerBean CUSTOMER_INFO)
        	return new ModelAndView("redirect:showCustomer.htm", "id", CUSTOMER_INFO.getId());
    My "best-practice" question is regarding the jsp form fields. Since it's an update, you don't want the user to be able to change the value of the "id" field which maps to the underlying table's primary key. Is the best practice to then pass the ID in the form as "hidden", as follows:
     <form:form method="post" action="editCustomer.htm" commandName="CUSTOMER_INFO">
        <tr><td><form:label path="name">Name<form:errors path="name" cssClass="error" /></form:label></td><td><form:input path="name"/></td></tr>
    <form:input path="id" type="hidden"/>
    This way ID is populated in the form by the GET method of the controller and when the POST method is invoked the reconstructed bean has the original ID which the user did not modify. Do you consider this an elegant way to go about it?

  • #2
    I would store the beanin the session (SessionAttributes) between variables next to that I would configure the binder (see init binder methods in the reference guide) to exclude the id (and version field) from binding. You also might want to take a look at HDIV which adds data integrity checks etc. to your web application.


    • #3
      Very cool Marten, thanks a lot!