Search code examples
springmodelattribute

Sending a parameter from List to a method which is annotated with @ModelAttribute


I have a list page as shown below and when I click on Edit button, I want to send the patientId to the getObject() so that I can load the object from DB if the patientId exists. I tried in many ways, but its taking null as the patiendId in getObject(). Any suggestions would be appreciated.

Following is my List page ::

       <c:forEach var="pat" items="${patients}" varStatus="status">
            <tr>                            
            <c:url var="editUrl" value="/patient/${pat.patientId}"/>

                    <td>${pat.firstName}</td>
                    <td>${pat.mobileNumber1}</td>
                    <td>${pat.emailId1}</td>

               <td><a href='<c:out value="${editUrl}"/>'>Edit</a></td>

        </tr>
    </c:forEach>

Controller code::

@Controller
@RequestMapping(value="/patient")
public class PatientController {

  @ModelAttribute
  public Patient getObject(@RequestParam(required=false) String patientId){

    System.out.println("Model Attribute method :: "+patientId);
    //Here I want to load the object using patientId.
    return(patientId != null ? patientDAO.findPatientById(patientId) : new    Patient());

}

@RequestMapping(value="/{patientId}", method=RequestMethod.GET)
public String editPatient(@PathVariable("patientId")String  patientId){
    System.out.println("Editing Id : "+patientId);
    //Able to get the Id here.
    return "editPage";

}


Solution

  • I got the answer. Below is my working code. Hope it will help someone.Thanks to all.

    <tr>                                                        
        <c:url var="deleteUrl" value="/patient/delete/${pat.patientId}"/>
    
                <td>${pat.firstName}</td>
                <td>${pat.mobileNumber1}</td>
                <td>${pat.emailId1}</td>
    
            <td><a href="newPatient?patientId=${pat.patientId}">Edit</a></td>
            <td><a href='<c:out value="${deleteUrl}"/>'>Delete</a></td>
    
    </tr>
    </c:forEach>
    

    Controller code::

    @ModelAttribute
    public Patient getObject(@RequestParam(value="patientId", required=false) String patientId){
        System.out.println("Model Attribute method :: "+patientId);
    
        return (patientId != null ? patientDAO.findPatientById(patientId) : new Patient());     
    }
    
    @RequestMapping(value="/newPatient", method=RequestMethod.GET)
    public String demo(ModelMap model){
    
        System.out.println("Demo of Patient");  
    
        return "newPatient";
    }