2012-06-24 213 views
4

嘿傢伙我想學習Spring並且我正在學習Spring 2.5寫的教程。我的研究已經表明,SimpleFormController已經被折舊了,以支持註解@Controller。我試圖將這個類轉換爲控制器類,有人可以告訴我這是如何完成的,下面是我的類。我不確定課堂中的方法,但是這些方法是否也會改變,或者我是否只爲課堂添加註釋?從春天2.5 MVC到春天3.0 MVC

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

通過註釋「createPriceIncrease」方法@ModelAttribute,您告訴春天如何初始填充「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) { 
    ... 
    } 

}