java web 3.0改成2.5_java – 从Spring 2.5 MVC到Spring 3.0 MVC

嘿伙计们,我正在努力学习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) {

...

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值