由于项目需要用到向导式的跳转页面效果,本项目又是用spring mvc实现的,刚开始想到用spring 的webflow,不过webflow太过笨重,对于我们不是很复杂的跳转来说好像有种“杀鸡焉用牛刀”的感觉,于是就网上搜索看有没有类似的解决方案,网上的答案一般都是叫你继承AbstractWizardFormContoller这个类来实现,但对于spring mvc3.0.x这个类将不再使用,转而推荐使用注解的方式来实现,于是参考官方文档,用注解方式实现了向导式页面。
下面是代码示例:
- @Controller
- @RequestMapping("/wizard.htm")
- //需要保存在session中的变量
- @SessionAttributes("bean")
- public class TestWizardController{
- @Resource(name = "beanService")
- private BeanService beanService;
- @RequestMapping
- public String step1(final ModelMap modelMap){
- modelMap.addAttribute("bean", new Bean());
- return "step1";
- }
- @RequestMapping(params = "_step=2")
- public String step2(final @ModelAttribute("bean") Bean bean,
- final Errors errors){
- return "step2";
- }
- @RequestMapping(params = "_step=3")
- public String step3(final @ModelAttribute("bean") Bean bean,
- final Errors errors){
- return "step3";
- }
- @RequestMapping(params = "_finish")
- public String processFinish(@ModelAttribute("bean")Bean bean,
- final Errors errors,
- final ModelMap modelMap,
- final SessionStatus status){
- beanService.add(bean);
- status.setComplete();
- return "success";
- }
- @RequestMapping(params = "_cancel")
- public String processCancel(final HttpServletRequest request,
- final HttpServletResponse response,
- final SessionStatus status){
- status.setComplete();
- return "cancel";
- }
- }
@Controller
@RequestMapping("/wizard.htm")
//需要保存在session中的变量
@SessionAttributes("bean")
public class TestWizardController{
@Resource(name = "beanService")
private BeanService beanService;
@RequestMapping
public String step1(final ModelMap modelMap){
modelMap.addAttribute("bean", new Bean());
return "step1";
}
@RequestMapping(params = "_step=2")
public String step2(final @ModelAttribute("bean") Bean bean,
final Errors errors){
return "step2";
}
@RequestMapping(params = "_step=3")
public String step3(final @ModelAttribute("bean") Bean bean,
final Errors errors){
return "step3";
}
@RequestMapping(params = "_finish")
public String processFinish(@ModelAttribute("bean")Bean bean,
final Errors errors,
final ModelMap modelMap,
final SessionStatus status){
beanService.add(bean);
status.setComplete();
return "success";
}
@RequestMapping(params = "_cancel")
public String processCancel(final HttpServletRequest request,
final HttpServletResponse response,
final SessionStatus status){
status.setComplete();
return "cancel";
}
}
其中起到最大作用的就是@SessionAttributes这个注解,它定义了一个在session范围内的变量,这个变量可以在不同的页面跳转时保持状态。
第一次访问http:/www./example.com/wizard.htm时进入step1方法,其后提交的表单action后面都要加上相应的参数,如:
step1页面 <form action="http:/www./example.com/wizard.htm?_step=2">
step2页面 <form action="http:/www./example.com/wizard.htm?_step=3">
step3页面 <form action="http:/www./example.com/wizard.htm?_finish">