将参数从 List 发送到用 @ModelAttribute 注释的方法

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

我有一个如下所示的列表页面,当我单击“编辑”按钮时,我想将 patientId 发送到 getObject() 以便在 patientId 存在时从 DB 加载对象。我尝试了很多方法,但它在 getObject() 中将 null 作为 patiendId。 任何建议,将不胜感激。

以下是我的列表页面::

       <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
@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";

}

您在一个地方使用 @PathVariable,在另一个地方使用 @RequestParam,并且正在发送路径变量(/patients/123 而不是请求参数 /patients?patientId=123):使用其中之一。

如下更新应该有效:

  @ModelAttribute
  public Patient getObject(@PathVariable(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());

}}

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-methods

我得到了答案。下面是我的工作代码。希望对大家有帮助someone.Thanks。

<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>

控制器代码::

@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";
}