【问题标题】:How do we pass an object from view to controller in spring mvc?我们如何在spring mvc中将对象从视图传递到控制器?
【发布时间】:2016-07-21 20:09:18
【问题描述】:

控制器 1:

@RequestMapping(value = "/allEmployees", method = RequestMethod.GET)
public String getAllEmployees(@ModelAttribute("employeeListForm") EmployeeListForm employeeListForm, HttpServletRequest request, HttpServletResponse response, Model model, BindingResult errors) throws Exception {
    List<Employee> subList = null;
    allEmployees = empService.getAllEmployees(categoryId);      
    employeeListForm.setAllEmployees("allEmployees");           
    employeeListForm.setCategory("IT");         
    model.addAttribute("etcSearchForm", etcSearchForm); 
    return ALL_EMP_VIEW;
}

控制器 2:

@RequestMapping(value = "/EmployeeDetail", method = RequestMethod.GET)
public String getEmpDetail((@ModelAttribute("empDetailForm") EmployeeDetailForm empDetailForm, HttpServletRequest request, HttpServletResponse response, Model model, BindingResult errors) throws Exception {

/*there is no direct approach to get the employee by id how                    should I get the 
  employee object from list page to deatil page 
*/
    empDetailForm.setSalary(emp.getSalary());
    empDetailForm.setTitle(emp.getTitle());
    empDetailForm.setName(emp.getName());
    model.addAttribute("empDetailForm", empDetailForm); 
    return ALL_EMP_Detail_Form;
}

查看:

<div th:if="${allEmplListForm.aAllEmployees.size() > 0}" th:each="emp : ${allEmplListForm.aAllEmployees}" th:object="${emp}" >                           
    <a th:href="@{/EmployeeDetail)}" class="link">
        <div><p class="name" th:text="*{name}"></p></div>
        <div><p th:text="*{date}"></p> <p th:text="*{title}"></p></div>
        <div><p class="salary" th:text="*{salary}"></p></div>
    </a>
</div>

我在一页中显示员工列表,当我单击员工时,它必须将我带到详细信息页面(控制器 2),其中没有直接的服务方法可以通过 id 或 name 或其他方式获取员工。

我应该如何将我的员工对象从视图发送到控制器。单击应转到详细信息页面的链接。

【问题讨论】:

  • 你如何列出它们;你能展示一下代码吗?
  • 我认为您需要添加更多信息..但是如果您需要将某些内容从视图传递到控制器而不是 AJAX 调用。
  • 你为什么不写一个服务方法,然后在列表页面上点击员工行,你可以通过 ID 或姓名获取员工详细信息。例如 /emp/(id) 获取请求。
  • 我们的 dao 中没有直接的方法来通过 emp id 查找员工,

标签: spring spring-mvc model-view-controller thymeleaf


【解决方案1】:

您的问题类似于thisthis one。我认为除了制作 &lt;form&gt; 元素并将 Employee 对象发布到控制器之外别无选择。

【讨论】:

  • 我认为第二个更接近我的,但我不想使用 POST(我只需要 GET 和员工对象)才能进入详细信息页面。
  • 您可以使用 GET 方法发送&lt;form&gt;Here an example
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 2021-02-19
  • 2015-11-11
  • 2013-12-13
  • 2013-08-30
  • 2021-01-04
相关资源
最近更新 更多