Passing a new object in Spring MVC model.addAttribute() method

10,551

Spring's form tag library's <form:form> element requires a model attribute to bind to to create its paths.

<form:form modelAttribute="owner"

The modelAttribute attribute is pointing to the Owner model attribute you added. It obviously doesn't use it for its value (it's empty after all). However, it uses the empty object as a template (for example, field names) for generating the name attributes of the <input> elements.

Share:
10,551
underdog
Author by

underdog

programmer at HP #SOreadytohelp

Updated on June 05, 2022

Comments

  • underdog
    underdog almost 2 years

    I am implementing the Spring PetClinic Project from here

    http://docs.spring.io/docs/petclinic.html

    I have a small doubt, the user clicks the find owner page from the welcome page.

    Controller code which handles the request

    @RequestMapping(value = "/owners/search", method = RequestMethod.GET)
        public String setupForm(Model model) {
            model.addAttribute("owner", new Owner());
            return "owners/search";
        }
    

    Now the control is moved to the Search.jsp page, which also allows the user to add a new owner.

    My doubt is why in the model.addAttribute a new owner object is put?.

    model.addAttribute("owner", new Owner());
    

    What is the need for that?. Why doesn't the flow directly navigated to Search.jsp

    The Owner class has the properties of the owner like firstName, lastName. etc.

    Please advice if you need any more information in the code. I will put it here.

    Search.jsp

    <%@ include file="/WEB-INF/jsp/includes.jsp" %>
    <%@ include file="/WEB-INF/jsp/header.jsp" %>
    
    
    <h2>Find Owners:</h2>
    
    <spring:url value="/owners" var="formUrl"/>
    <form:form modelAttribute="owner" action="${fn:escapeXml(formUrl)}" method="get">
      <table>
        <tr>
          <th>
            Last Name: <form:errors path="*" cssClass="errors"/>
            <br/> 
            <form:input path="lastName" size="30" maxlength="80" />
          </th>
        </tr>
        <tr>
          <td><p class="submit"><input type="submit" value="Find Owners"/></p></td>
        </tr>
      </table>
    </form:form>
    
    <br/>
    <a href='<spring:url value="/owners/new" htmlEscape="true"/>'>Add Owner</a>
    
    <%@ include file="/WEB-INF/jsp/footer.jsp" %>
    

    Thanks. I would really appreciate the help.