• Spring MVC如何进行重定向呢?


    转自:

    Spring MVC如何进行重定向呢?

    下文笔者将讲述Spring MVC进行重定向的三种方法简介说明,如下所示:

    方式1:redirect重定向流程

    response.sendRedirect重定向跳转

    @RequestMapping(value="/testredirect",method = { RequestMethod.POST, RequestMethod.GET })  
    public ModelAndView testredirect(HttpServletResponse response){  
        response.sendRedirect("/index");
        return null; 
    }
    

    方式2:ViewResolver直接跳转

    @RequestMapping(value="/testredirect",method = { RequestMethod.POST, RequestMethod.GET })  
    public  String testredirect(HttpServletResponse response){  
        return "redirect:/index";  
    } 
    

    带参数重定向

    @RequestMapping("/testredirect")
    public String testredirect(Model model, RedirectAttributes attr) {
    	attr.addAttribute("test", "java265");//跳转地址带上test参数 
    	return "redirect:/user/users";
    }
    
    1. 使用RedirectAttributes的addAttribute方法传递参数会跟随在URL后面,如上代码即为http:/index.action?test=java265
    2. 使用addFlashAttribute不会跟随在URL后面,会把该参数值暂时保存于session,待重定向url获取该参数后从session中移除,这里的redirect必须是方法映射路径
      你会发现redirect后的jsp页面中b只会出现一次,刷新后b再也不会出现了,这验证了上面说的,b被访问后就会从session中移除
      对于重复提交可以使用此来完成
    3. Spring mvc设置下RequestMappingHandlerAdapter 的ignoreDefaultModelOnRedirect=true,这样可以提高效率,避免不必要的检索

    ModelAndView重定向

    @RequestMapping(value="/restredirect",method = { RequestMethod.POST, RequestMethod.GET })  
    public  ModelAndView restredirect(String userName){  
        ModelAndView  model = new ModelAndView("redirect:/main/index");    
        return model;  
    }
    
    带参数
    
    @RequestMapping(value="/toredirect",method = { RequestMethod.POST, RequestMethod.GET })  
    public  ModelAndView toredirect(String userName){  
        ModelAndView  model = new ModelAndView("/main/index");   
        model.addObject("userName", userName);  //把userName参数带入到controller的RedirectAttributes
        return model;  
    }
  • 相关阅读:
    主线程结束子线程不再执行
    [游戏开发][Unity]读取Assetbundle报错Decompressing this format (49)
    Java2-3年面试题
    JUC系列(九) CAS 与锁的理解
    spark安装
    Java设计模式8,校验、审批流程改善神器,责任链模式
    [笔记] 深度学习的部分专业名词
    Android 双向滑动
    路径规划 | 蚁群算法图解与分析(附ROS C++/Python/Matlab仿真)
    浅谈Lua协程和函数的尾调用
  • 原文地址:https://blog.csdn.net/qq_25073223/article/details/127830002