嘿伙计们,我正在努力学习Spring,我正在学习春季2.5中编写的教程.我的研究表明,SimpleFormController已被折旧,有利于注释@Controller.我试图将这个类转换为一个控制器类,有人可以告诉我这是怎么做的,在我的课下.我不确定课堂上的方法,但是那些也会改变,或者我只是在课堂上添加注释?
package springapp.web;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import springapp.service.ProductManager;
import springapp.service.PriceIncrease;
public class PriceIncreaseFormController extends SimpleFormController {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private ProductManager productManager;
public ModelAndView onSubmit(Object command)
throws ServletException {
int increase = ((PriceIncrease) command).getPercentage();
logger.info("Increasing prices by " + increase + "%.");
productManager.increasePrice(increase);
logger.info("returning from PriceIncreaseForm view to " + getSuccessView());
return new ModelAndView(new RedirectView(getSuccessView()));
}
protected Object formBackingObject(HttpServletRequest request) throws ServletException {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(20);
return priceIncrease;
}
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
public ProductManager getProductManager() {
return productManager;
}
}
最佳答案
通过使用@ModelAttribute注释“createPriceIncrease”方法,您将告诉spring如何最初填充“priceIncrease”模型值.
@SessionAttributes告诉Spring在每次请求后自动在会话中存储“priceIncrease”对象.
最后,“post”和“get”方法的方法参数的@ModelAttribute告诉spring找到名为“priceIncrease”的模型属性.
它会知道它是一个会话属性,如果它可以找到它,否则,它将使用“createPriceIncrease”方法创建它.
@Controller
@SessionAttributes({"priceIncrease"})
@RequestMapping("/priceIncrease")
public class MyController {
@ModelAttribute("priceIncrease")
public PriceIncrease createPriceIncrease() {
PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(20);
return priceIncrease;
}
@RequestMapping(method={RequestMethod.POST})
public ModelAndView post(@ModelAttribute("priceIncrease") PriceIncrease priceIncrease,
HttpServletRequest request,
HttpServletResponse response) {
...
}
@RequestMapping(method={RequestMethod.GET})
public ModelAndView get(@ModelAttribute("priceIncrease") PriceIncrease priceIncrease,
HttpServletRequest request,
HttpServletResponse response) {
...
}
}