【发布时间】:2018-06-05 08:08:36
【问题描述】:
在Servlet 中,您可以包含在doGet 或doPost 之前调用的@Override service 方法,有没有办法在Spring @Controller 中实现相同的功能?
或者更准确地说,在控制器中的每个方法中,我需要确保实体(在本例中为产品)存在并在其他情况下重定向,就像这样,那么如何在 Spring 中实现呢?请注意,我还需要每个方法中可用的产品。
@Controller
@RequestMapping("/product/{prod_id}/attribute")
public class AttributeController {
@Autowired
private AttributeService attributeService;
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String add(Model model, @PathVariable Long prod_id) {
Product product = attributeService.getProduct(prod_id);
if (product == null) {
return "products/products";
}
model.addAttribute("product", product);
model.addAttribute("attribute", new Attribute());
return "products/attribute_add";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String save(Model model, @PathVariable Long prod_id, @Valid Attribute attribute, BindingResult result) {
Product product = attributeService.getProduct(prod_id);
if (product == null) {
return "products/products";
}
// ...
}
// ...
}
【问题讨论】:
标签: spring spring-mvc