从Spring 2.5 MVC到Spring 3.0 MVC

时间:2012-06-24 23:37:56

标签: java spring spring-mvc controller annotations

嘿伙计们我正在努力学习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;
    }



}

2 个答案:

答案 0 :(得分:2)

通过使用@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) {
     ...
  }

}

答案 1 :(得分:1)

控制器不需要扩展任何类;只是适当地注释它。

我认为"Bare Bones Spring"是一个很好的3.0教程。