如何获取@PathVariableValue并将其添加到@ModelAttribute String值?

时间:2014-04-07 08:55:31

标签: java spring-mvc

我有:

@RequestMapping
public String someMethod(final RedirectAttributes redirectAttributes) {

   redirectAttributes.addFlashAttribute("customer_id" + someId, customerWithThatId);
   return "redirect:showcustomer.html";    
}

如何通过customer_id_{certain_id_value}中的certain_id_value来查询@PathVariable

@RequestMapping
public String showCustomer(@ModelAttribute("customer_id_{howToTakeTheIdFromPathVariable?}") Customer customer, @PathVariable("customerId") String customerId) {
    // ...
}

2 个答案:

答案 0 :(得分:0)

通常,您无需填充@ModelAttribute中的@PathVariable。您需要从那里获取id,然后从数据库中获取模型。如下所示:

@Autowired
private CustomerRepository customerRepository;

@RequestMapping("/show/customer/customer_id_{customerId}")
public String showCustomer(@PathVariable("customerId") long customerId) {
    Customer customer = customerRepository.get(customerId);
    ......
}

答案 1 :(得分:0)

从Spring 3.1开始,用@PathVariable注释的参数会自动暴露给模型,因此不需要特殊处理。

https://jira.spring.io/browse/SPR-7543

RedirectAttributes闪存范围属性也是如此。

http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html

  

重定向后,flash属性会自动添加到为目标URL提供服务的控制器模型中。