spring mvc controller间跳转(重定向,传参)+struts2 转发和重定向

url:http://zghbwjl.blog.163.com/blog/static/12033667220137795252845/

1. 需求背景
需求:spring MVC框架controller间跳转,需重定向。有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示。

本来以为挺简单的一件事情,并且个人认为比较常用的一种方式,一百度全都有了,这些根本不是问题,但是一百度居然出乎我的意料,一堆都不是我想要的结果。无奈啊,自己写一篇比较全都供以后大家一百度吧,哈哈哈。。。是这些写的不是很全都人们给了我写这篇博客的动力。
2. 解决办法
需求有了肯定是解决办法了,一一解决,说明下spring的跳转方式很多很多,我这里只是说一些自我认为好用的,常用的,spring分装的一些类和方法。

(1)我在后台一个controller跳转到另一个controller,为什么有这种需求呢,是这样的。我有一个列表页面,然后我会进行新增操作,新增在后台完成之后我要跳转到列表页面,不需要传递参数,列表页面默认查询所有的。
方式一:使用ModelAndView
return new ModelAndView("redirect:/toList");
这样可以重定向到toList这个方法
方式二:返回String
return "redirect:/ toList ";
其它方式:其它方式还有很多,这里不再做介绍了,比如说response等等。这是不带参数的重定向。

(2)第二种情况,列表页面有查询条件,跳转后我的查询条件不能丢掉,这样就需要带参数的了,带参数可以拼接url

方式一:自己手动拼接url

new ModelAndView("redirect:/toList?param1="+value1+"&param2="+value2);
这样有个弊端,就是传中文可能会有乱码问题。

方式二:用RedirectAttributes,这个是发现的一个比较好用的一个类
这里用它的addAttribute方法,这个实际上重定向过去以后你看url,是它自动给你拼了你的url。
使用方法:

attr.addAttribute("param", value);
return "redirect:/namespace/toController";
这样在toController这个方法中就可以通过获得参数的方式获得这个参数,再传递到页面。过去的url还是和方式一一样的。

(3)带参数不拼接url页面也能拿到值(重点是这个)
一般我估计重定向到都想用这种方式:

@RequestMapping("/save")
public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
throws Exception {


String code = service.save(form);
if(code.equals("000")){
attr.addFlashAttribute("name", form.getName());
attr.addFlashAttribute("success", "添加成功!");
return "redirect:/index";
}else{
attr.addAttribute("projectName", form.getProjectName());
attr.addAttribute("enviroment", form.getEnviroment());
attr.addFlashAttribute("msg", "添加出错!错误码为:"+rsp.getCode().getCode()+",错误为:"+rsp.getCode().getName());
return "redirect:/maintenance/toAddConfigCenter";
}
}


@RequestMapping("/index")

public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
throws Exception {
return "redirect:/main/list";
}
页面取值不用我说了吧,直接用el表达式就能获得到,这里的原理是放到session中,session在跳到页面后马上移除对象。所以你刷新一下后这个值就会丢掉
3. 总结
最底层还是两种跳转,只是spring又进行了封装而已,所以说跳转的方式其实有很多很多种,你自己也可以封一个,也可以用最原始的response来,也没有问题。好了,就到这儿。

其实也没有什么,但是知道了这个就很简单了,之前没搞懂,现在搞懂了,和大家分享。有问题的给我留言。

spring mvc3中的addFlashAttribute方法

url: http://www.software8.co/wzjs/java/2943.html
记得在spring mvc2中,当保存POJO到数据库后,要返回成功页面,如果这个时候要带点信息,
则要这样:
Java代码:
  1. //第三个参数(UserModel user)默认为绑定对象
  2. @RequestMapping(value = "/user/save", method = RequestMethod.POST)
  3. public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response,UserModel user) throws Exception {
  4. ModelAndView mv = new ModelAndView("/user/save/result");//默认为forward模式
  5. // ModelAndView mv = new ModelAndView("redirect:/user/save/result");//redirect模式
  6. mv.addObject("message","保存用户成功!");
  7. return mv;
  8. }
而在spring mvc 3.1后,可以这样
Java代码:
  1. @RequestMapping(value = "/user/save", method = RequestMethod.POST)
  2. public ModelAndView saveUser(UserModel user, RedirectAttributes redirectAttributes) throws Exception {
  3. redirectAttributes.addFlashAttribute("message", "保存用户成功!");//使用addFlashAttribute,参数不会出现在url地址栏中
  4. return "redirect:/user/save/result";
  5. }
来个稍微完整点的例子,首先是一个表单,在其中填入一些信息:
Java代码:
  1. <form:form id="myform" action="saveUserDetails.action" method="POST" commandName="user">
  2. <form:input type="text" name="firstName" path="firstName"/>
  3. <form:input type="text" name="lastName" path="lastName"/>
  4. <form:input type="text" name="email" path="email"/>
  5. <input type="submit" value="submit">
  6. </form:form>
则在controller中,可以这样:
Java代码:
  1. @RequestMapping(value="/saveUserDetails.action", method=RequestMethod.POST)
  2. public String greetingsAction(@Validated User user,RedirectAttributesredirectAttributes){
  3. someUserdetailsService.save(user);
  4. redirectAttributes.addFlashAttribute("firstName", user.getFirstName());
  5. redirectAttributes.addFlashAttribute("lastName", user.getLastName())
  6. return "redirect:success.html";
  7. }
  8. success.html:
  9. <div>
  10. <h1>Hello ${firstName} ${lastName}. Your details stored in our database.</h1>
  11. </div><br>
但如果F5的时候,会发现参数丢失,因为flash scope其实只支持redirect的,所以可以判断下:
Java代码:
  1. @RequestMapping(value="/success.html", method=RequestMethod.GET)
  2. public String successView(HttpServletRequest request){
  3. Map<String,?> map = RequestContextUtils.getInputFlashMap(request);
  4. if (map!=null)
  5. return "success";
  6. else return "redirect:someOtherView"; //給出其他提示信息

spring mvc 如何请求转发和重定向呢?

url: http://blog.sina.com.cn/s/blog_9cd9dc7101016abw.html

往下看:

由于这部分内容简单,一带而过了。

<wbr></wbr>

1.请求转发:

<wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px">(1)返回<span style="background-color:rgb(250,250,250)">ModelAndView</span><span style="background-color:rgb(250,250,250)"><wbr>:</wbr></span></span></wbr></wbr>

@RequestMapping(value="/model",method=RequestMethod.GET)
public ModelAndView testForward(ModelAndView
<wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> model,@RequestParam(value="id",defaultValue="1",required=false)Long id){<br></span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px">User u = getBaseService().get(User.class, id);<br></span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px">model.addObject("user", u);<br><span style="color:#ff00"><wbr><wbr><wbr>model.setViewName("forward:index.jsp");</wbr></wbr></wbr></span><br></span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px">return model;<br> }</span></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr><span style="font-family:Microsoft YaHei; font-size:14px">如上代码,如果返回modelAndView 则可以如红色标注,添加forward即可,若想重定向,可把forward替换成redirect便可达到目的。</span></wbr>

<wbr></wbr>

(2)返回字符串

<wbr></wbr>

@RequestMapping(value="/forward",method=RequestMethod.GET)
<wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> public String testForward(){<br><br><span style="color:#ff00"><wbr><wbr><wbr><wbr> return "forward:/index.action";</wbr></wbr></wbr></wbr></span><br></span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> }</span></wbr></wbr></wbr></wbr>

<wbr><span style="font-family:Microsoft YaHei; font-size:14px">如上代码红色部分。</span></wbr>

<wbr></wbr>

2.请求重定向

<wbr><span style="font-family:Microsoft YaHei; font-size:14px">对于请求转发可以分为:1.带参数 2.不带参数</span></wbr>

<wbr></wbr>

(1)带参数:

<wbr></wbr>

Java代码<wbr><span style="font-family:Microsoft YaHei; font-size:14px"></span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"><a target="_blank" title="收藏这段代码" href="http://blog.csdn.net/jackpk/article/details/19121777"><img title="spring&lt;wbr&gt;MVC&lt;wbr&gt;3.1&lt;wbr&gt;forword/redirect" alt="收藏代码" src="http://yjflfliulei.iteye.com/images/icon_star.png"></a></span></wbr></wbr>
  1. @RequestMapping(value="/redirect",method=RequestMethod.GET)<wbr><wbr></wbr></wbr>
  2. public<wbr>String<wbr>testRedirect(RedirectAttributes<wbr>attr){<wbr><wbr></wbr></wbr></wbr></wbr></wbr>
  3. <wbr><wbr><wbr><wbr><wbr>attr.addAttribute(<span style="color:blue">"a"</span>,<wbr><span style="color:blue">"a"</span>);<wbr><wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>
  4. <wbr><wbr><wbr><wbr><wbr>attr.addFlashAttribute(<span style="color:blue">"b"</span>,<wbr><span style="color:blue">"b"</span>);<wbr><wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>
  5. <wbr><wbr><wbr><wbr><wbr><span style="color:#7f055"><strong>return</strong></span><wbr><span style="color:blue">"redirect:/index.action"</span>;<wbr><wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>
  6. }<wbr><wbr></wbr></wbr>
<wbr></wbr>

<wbr></wbr>

<wbr><span style="font-family:Microsoft YaHei; font-size:14px">带参数可使用RedirectAttributes参数进行传递:</span></wbr>

<wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"></span><wbr><span style="font-family:Microsoft YaHei; font-size:14px; color:#ff00"><wbr> 注意</wbr></span><span style="font-family:Microsoft YaHei; font-size:14px">:<span style="background-color:rgb(255,255,153)">1.使用RedirectAttributes的addAttribute方法传递参数会跟随在URL后面,如上代码即为http:/index.action?a=a</span></span></wbr></wbr></wbr>

<wbr><wbr><wbr><wbr><wbr><wbr><wbr> 2.使用addFlashAttribute不会跟随在URL后面,会把该参数值暂时保存于session,待重定向url获取该参数后从session中移除,这里的redirect必须是方法映射路径,jsp无效。你会发现redirect后的jsp页面中b只会出现一次,刷新后b再也不会出现了,这验证了上面说的,b被访问后就会从session中移除。对于重复提交可以使用此来完成.</wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr></wbr>

<wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> </span><wbr><span style="font-family:Microsoft YaHei; font-size:14px"> 另外,如果使用了RedirectAttributes作为参数,但是没有进行redirect呢?这种情况下不会将RedirectAttributes参数传递过去,默认传forward对应的model,官方的建议是:</span></wbr></wbr></wbr>


p:ignoreDefaultModelOnRedi
<wbr><span style="font-family:Microsoft YaHei; font-size:14px">rect="true" /&gt;</span></wbr>

<wbr><span style="font-family:Microsoft YaHei; font-size:14px">设置下<span style="background-color:rgb(250,250,250)">RequestMappingHandlerAda<wbr>pter 的</wbr></span><span style="background-color:rgb(250,250,250)">ignoreDefaultModelOnRedi<wbr>rect属性,这样可以提高效率,避免不必要的检索。</wbr></span></span></wbr>

<wbr></wbr>

(2)无参数

<wbr></wbr>

@RequestMapping(value="/redirect",method=RequestMethod.GET)
public String testRedirect(){

return "redirect:/index.action";
}

Struts2理解——转发和重定向

转发和重定向设置:
<actionname="deptAction"class="com.syaccp.erp.action.DeptAction">
<resultname="success">/WEB-INF/jsp/basic/dept_list.jsp</result>
<resultname="editView">/WEB-INF/jsp/basic/dept_edit.jsp</result>
</action>
上例action中,success对应的视图是通过默认的转发(dispatch)跳转的。editView作为增删改的一部分,应该通过重定向来跳转页面,这样必须显式声明type=redirect,来达到重定向的效果。这时editView的内容改为action中一个方法更合适。如:
<actionname="deptAction"class="com.syaccp.erp.action.DeptAction">
<resultname="success">/WEB-INF/jsp/basic/dept_list.jsp</result>
<resultname="editView"type="redirect">deptAction!select.action</result>
</action>
这里在执行edit方法后返回editView字符串,将会再执行select方法,跟DeptEditServlet里response.sendRedirect("DeptListServlet")类似
上例只是重定向同一个Action类中的其他方法,开发中可能还需要重定向到其他Action类中,这时就需要用到type属性的另一个值:redirectAction:
<actionname="deptAction"class="com.syaccp.erp.action.DeptAction">
<resultname="success">/WEB-INF/jsp/basic/dept_list.jsp</result>
<resultname="editView"type="redirect">deptAction!select.action</result>
<resultname="index"type="redirectAction">indexAction.action</result>
</action>
上例中,如果deptAction中某个方法返回字符串为index,则将跳转到indexAction去,执行indexAction的execute方法。
如果indexAction在其他包里面,则前面应加上包名,例:index/indexAction

注:
结果类型中redirect和redirectAction的区别
redirect是在处理完当前Action之后,重定向到另外一个实际的物理资源
redirectAction也是重定向,但它重定向到的是另外一个Action
只要是重定向,那么之前凡是保存在request里面的东西就全都消失了
因为重定向实际是发送第二个请求,故请求中的东西也就不会出现在第二个请求里面了
也就是说重定向是不共享request的东西,重定向后的页面中无法接收request里的东西
另外dispatcher结果类型的default属性为TRUE故<result-type/>缺省为dispatcher
所以如果没有设置type属性的话,那么默认的是请求转发,即浏览器显示的是*.action
但是在设置type="redirect"属性后,就可以重定向了,即浏览器显示的是/login2.jsp

----“请求转发”和“重定向”之间的区别

让浏览器获得另外一个URL所指向的资源可以使用请求转发(RequestDispatcher.forward)或则是重定向技术(HttpServletResponse.sendRedirect),但是两者的内部机制有很大的区别:

1 请求转发只能将请求转发给同一个WEB应用中的组件,而重定向还可以重新定向到同一站点不同应用程序中的资源,甚至可以重定向到一绝对的URL。

2 重定向可以看见目标页面的URL,转发只能看见第一次访问的页面URL,以后的工作都是有服务器来做的。

3 请求响应调用者和被调用者之间共享相同的request对象和response对象,重定向调用者和被调用者属于两个独立访问请求和响应过程。

4 重定向跳转后必须加上return,要不然页面虽然跳转了,但是还会执行跳转后面的语句,转发是执行了跳转页面,下面的代码就不会在执行了。

	@RequestMapping(value="/uriTemplate", method=RequestMethod.GET)
	public String uriTemplate(RedirectAttributes redirectAttrs) {
		redirectAttrs.addAttribute("account", "a123");  // Used as URI template variable
		redirectAttrs.addAttribute("date", new LocalDate(2011, 12, 31));  // Appended as a query parameter
		return "redirect:/redirect/{account}";
	}

	@RequestMapping(value="/uriComponentsBuilder", method=RequestMethod.GET)
	public String uriComponentsBuilder() {
		String date = this.conversionService.convert(new LocalDate(2011, 12, 31), String.class);
		UriComponents redirectUri = UriComponentsBuilder.fromPath("/redirect/{account}").queryParam("date", date)
				.build().expand("a123").encode();
		return "redirect:" + redirectUri.toUriString();
	}

	@RequestMapping(value="/{account}", method=RequestMethod.GET)
	public String show(@PathVariable String account, @RequestParam(required=false) LocalDate date) {
		return "redirect/redirectResults";
	}
	
	// http://127.0.0.1:8010/redirect/forward
	@RequestMapping(value="/forward", method=RequestMethod.GET)
	public String forward() {
		return "forward:/welcome";
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值