Spring MVC中的注释
-
03-07-2019 - |
题
我想将此SimpleFormController转换为使用Spring MVC 2.5中引入的注释支持
<强>爪哇强>
public class PriceIncreaseFormController extends SimpleFormController {
ProductManager productManager = new ProductManager();
@Override
public ModelAndView onSubmit(Object command)
throws ServletException {
int increase = ((PriceIncrease) command).getPercentage();
productManager.increasePrice(increase);
return new ModelAndView(new RedirectView(getSuccessView()));
}
@Override
protected Object formBackingObject(HttpServletRequest request)
throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(20);
return priceIncrease;
}
}
Spring配置
<!-- Include basic annotation support -->
<context:annotation-config/>
<!-- Comma-separated list of packages to search for annotated controllers. Append '.*' to search all sub-packages -->
<context:component-scan base-package="springapp.web"/>
<!-- Enables use of annotations on controller methods to map URLs to methods and request params to method arguments -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<bean name="/priceincrease.htm" class="springapp.web.PriceIncreaseFormController">
<property name="sessionForm" value="true"/>
<property name="commandName" value="priceIncrease"/>
<property name="commandClass" value="springapp.service.PriceIncrease"/>
<property name="validator">
<bean class="springapp.service.PriceIncreaseValidator"/>
</property>
<property name="formView" value="priceincrease"/>
<property name="successView" value="hello.htm"/>
<property name="productManager" ref="productManager"/>
</bean>
基本上,我想用Java类中的注释替换 /priceincrease.htm
bean的所有XML配置。这是可能的,如果可以的话,我应该使用哪些相应的注释?
谢谢, 唐
解决方案
它看起来像下面这样,虽然它是否有效但取决于你的配置(查看解析器等)。我还应该注意到,有大约80亿个有效的方法来编写这个东西。请参阅Spring文档, 13.11。 4“支持的处理程序方法参数和返回类型”,以了解精神错乱的概述。另请注意,您可以自动装配验证器
@Controller
@RequestMapping("/priceincrease.htm")
public class PriceIncreaseFormController {
ProductManager productManager;
@Autowired
public PriceIncreaseFormController(ProductManager productManager) {
this.productManager = productManager;
}
// note: this method does not have to be called onSubmit
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(@ModelAttribute("priceIncrease") PriceIncrease priceIncrease, BindingResult result, SessionStatus status {
new PriceIncreaseValidator().validate(priceIncrease, result);
if (result.hasErrors()) {
return "priceincrease";
}
else {
int increase = priceIncrease.getPercentage();
productManager.increasePrice(increase);
status.setComplete();
return "redirect:hello.htm";
}
}
// note: this method does not have to be called setupForm
@RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model) {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(20);
model.addAttribute("priceIncrease", priceIncrease);
return "priceincrease";
}
}
其他提示
有人用最近的MVC完成了这个项目并且它在github上,所以你可以看到与Spring的教程相比如何更改所有类。
不隶属于 StackOverflow