3

我正在尝试学习 Spring,并且正在学习 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;
    }
    
    

}
4

2 回答 2

2

通过使用 注释“createPriceIncrease”方法@ModelAttribute,您可以告诉 spring 如何最初填充“priceIncrease”模型值。

告诉 Spring在@SessionAttributes每次请求后自动将“priceIncrease”对象存储在会话中。

最后,@ModelAttribute“post”和“get”方法的方法参数告诉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) {
     ...
  }

}
于 2012-06-25T03:27:07.223 回答
1

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

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

于 2012-06-24T23:45:57.673 回答