在项目中做form表单功能提交时,防止用户客户端后退或者刷新时重复提交问题,需要在服务端进行重定向跳转,具体跳转方式有以下几种方式:
公用代码:
Java代码
@RequestMapping(value="/index",method = { RequestMethod.POST, RequestMethod.GET })
publicModelAndView index(HttpServletResponse response){
ModelAndView model = newModelAndView("/home/index");
returnmodel;
}
一、使用HttpServletResponse 进行重定向跳转
Java代码
@RequestMapping(value="/toIndex",method = { RequestMethod.POST, RequestMethod.GET })
ublic ModelAndView toIndex(HttpServletResponse response){
try{
response.sendRedirect("/index");
} catch(IOException e1) {
}
returnnull;
二、依赖spring mvc的 ViewResolver直接跳转
Java代码
@RequestMapping(value="/toIndex",method = { RequestMethod.POST, RequestMethod.GET })
publicString toIndex(HttpServletResponse response){
return"redirect:/index";
}
注:当需要传递简单参数时可以使用以上两种方式通过get方式将参数拼接到url路劲后面。
三、依赖Spring
mvc的RedirectAttributes
Java代码
@RequestMapping(value="/toIndex",method = { RequestMethod.POST, RequestMethod.GET })
publicString toIndex(HttpServletResponse response,RedirectAttributes model){
model.addFlashAttribute("userName",'TimerBin');
model.addFlashAttribute("userPass",'ApeVm23U3wxEGocX');
return"redirect:/index";
}
在/home/index
可以直接使用${userName},${userPass}来获取重定向跳转的参数信息,这种方式可以处理复杂的参数传值问题,还可以使用此种方式来隐藏或缩短原有请求URL信息。
在controller中获取放在RedirectAttributes中的userName信息的方式:
Java代码
@RequestMapping(value="/index",method = { RequestMethod.POST, RequestMethod.GET })
publicModelAndView index(@ModelAttribute("userName") String userName){
ModelAndView model = newModelAndView("/main/index");
model.addObject("userName", userName);
returnmodel;
}
注:在项目中使用RedirectAttributes,因为该对象就是把参数信息放到项目中的session中,再多台服务器中使用该对象存储参数时已经要保证sesion设置是粘性的,不然在集群服务器中不支持该对象的使用!
在springMVC中,通过@RequestMapping发送请求地址,转发到目标页面,但是,有时候想直接访问页面,
不想通过xxx.jsp直接访问页面,可以通过springmvc.xml配置文件中的mvc:view-controller标签做到页面的直接访问。
在上面的实例中修改spirngmvc.xml配置文件如下:
分享:
喜欢
0
赠金笔
加载中,请稍候......
评论加载中,请稍候...
发评论
登录名: 密码: 找回密码 注册记住登录状态
昵 称:
评论并转载此博文
发评论
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。