常用:

ModelAndView
i: return new ModelAndView("redirect:/toList");

    或者

ii:return "redirect:/toList";

或者

iii:response.sendRedirect("index.html");

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

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

(1)我在后台一个controller跳转到另一个controller,为什么有这种需求呢,是这样的。我有一个列表页面,然后我会进行新增操作,新增在后台完成之后我要跳转到列表页面,不需要传递参数,列表页面默认查询所有的。
        方式一:使用ModelAndView
        return new ModelAndView("redirect:/toList");

    或者

return "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

往下看:

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

1.请求转发:

(1)返回ModelAndView :

@RequestMapping(value="/model",method=RequestMethod.GET)
public ModelAndView testForward(ModelAndView    model,@RequestParam(value="id",defaultValue="1",required=false)Long id){
     User u = getBaseService().get(User.class, id);
     model.addObject("user", u);
     model.setViewName("forward:index.jsp");
     return model;
}

如上代码,如果返回modelAndView 则可以如红色标注,添加forward即可,若想重定向,可把forward替换成redirect便可达到目的。

(2)返回字符串

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

return "forward:/index.action";
    }

如上代码红色部分。

2.请求重定向

对于请求转发可以分为:1.带参数 2.不带参数

(1)带参数:

Java代码  
  1. @RequestMapping(value="/redirect",method=RequestMethod.GET)
  2. public String testRedirect(RedirectAttributes attr){
  3. attr.addAttribute("a", "a");
  4. attr.addFlashAttribute("b", "b");
  5. return "redirect:/index.action";
  6. }
 

带参数可使用RedirectAttributes参数进行传递:

注意:1.使用RedirectAttributes的addAttribute方法传递参数会跟随在URL后面,如上代码即为http:/index.action?a=a

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

另外,如果使用了RedirectAttributes作为参数,但是没有进行redirect呢?这种情况下不会将RedirectAttributes参数传递过去,默认传forward对应的model,官方的建议是:

p:ignoreDefaultModelOnRedirect="true" />

设置下RequestMappingHandlerAdapter 的ignoreDefaultModelOnRedirect属性,这样可以提高效率,避免不必要的检索。

(2)无参数

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

return "redirect:/index.action";
}

 
转自:http://blog.csdn.net/jackpk/article/details/19121777

spring mvc 重定向加传参的更多相关文章

  1. spring mvc 文件上传 ajax 异步上传

    异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ...

  2. spring mvc 图片上传,图片压缩、跨域解决、 按天生成文件夹 ,删除,限制为图片代码等相关配置

    spring mvc 图片上传,跨域解决 按天生成文件夹 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ ...

  3. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  4. Spring mvc 文件上传到文件夹(转载+心得)

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  5. Spring MVC 笔记 —— Spring MVC 文件上传

    文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...

  6. spring mvc重定向

    spring mvc重定向有三种方法. 1.return new ModelAndView("redirect:/toUrl"); 其中/toUrlt是你要重定向的url. 2.r ...

  7. Spring MVC文件上传教程 commons-io/commons-uploadfile

    Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...

  8. 【Java Web开发学习】Spring MVC文件上传

    [Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...

  9. Spring mvc文件上传实现

    Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...

随机推荐

  1. OC-改错题

    1,类方法中不能访问成员变量 2,id后不能加*(因为id相当于NSObject *) 3,id类型的变量不能用点语法 4,类对象只能调用类方法,不能调用对象方法 .description #impo ...

  2. Entity Framework数据库初始化四种策略

    策略一:数据库不存在时重新创建数据库 程序代码 Database.SetInitializer<testContext>(new CreateDatabaseIfNotExists< ...

  3. SCP 命令(转)

    \ svn 删除所有的 .svn文件 find . -name .svn -type d -exec rm -fr {} \; linux之cp/scp命令+scp命令详解   名称:cp 使用权限: ...

  4. 该不该用inline-block取代float? inline和float的区别?

    该不该用inline-block取代float? 请看这篇文章引用: jtyjty99999的博客 让块级元素 水平排列的通常方式是float, 但是float可能会带来很多意外的问题 可以考虑用in ...

  5. mongodb在WEB开发中的应用与实践

    一.mongodb是什么? 一套高性能.易开发的文档型数据库.他使用键值对形式存放数据,能够存放包括字符串.数组.数据序列.图片.视频等在内的大多数数据文档.MongoDB完善的设计,搞笑的可编程性使 ...

  6. 全屏背景:15个jQuery插件实现全屏背景图像或媒体

    动态网站通常利用背景图像或预加载屏幕,以保证所有资源都加载到页面上,在浏览器中充分呈现.现在很多网站都炫耀自己的图像作为背景图像全屏背景,追溯到旧的Flash网站却用自己的方式在HTML资源重布局. ...

  7. Form表单中method为get和post的区别

    序,form表单中的方法分为get和post,但你都知道他们之间的区别吗? Form表单中method为get和post的区别: 例子如下,有个Form表单. <form action=&quo ...

  8. 使用xp光盘修复系统的方法步骤

    对于使用Windows XP系统的朋友来说,当系统出现崩溃或者系统使用时出现一些莫名其妙的错误时,你采用什么方法解决呢?一般都是采用重装系统或者使用Ghost恢复等. 但是使用这些方法各有缺陷,比如重 ...

  9. Junit基础整理

    项目引进Junit包 对待测试类新建testcase testcase类分为:@RunWith() -----@RunWith(suite.class)测试套件类打包测试 -----@RunWith( ...

  10. JS的构造函数

    //构造函数  //使自己的对象多次复制,同时实例根据设置的访问等级可以访问其内部的属性和方法  //当对象被实例化后,构造函数会立即执行它所包含的任何代码  function myObject(ms ...