`

Spring 重定向简易使用

阅读更多
直接上代码,调试firefox,F12,如装了firebug先禁用:
package com.up360.wechat.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能或描述:
 *
 * @Author: DR.YangLong
 * @Date: 14-7-16
 * @Time: 下午01:18
 * @Email: 410357434@163.com
 * @Version: 1.0
 * @Module: 修正:            日期:
 */
@Controller
@RequestMapping(value = "/redirect")
public class RedirectController {
    //不带参数
    @RequestMapping("/test1")
    public ModelAndView redirect1(){
        ModelAndView mv=new ModelAndView("redirect:/redirect/result.action");
        //使用/开头将使用重定向,不用将变为forward
        return mv;
    }
    //RedirectView构造参数(地址,不使用相对路径,兼容http1.0,暴露请求参数)对应默认值(url,false,true,true)。
    //public RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)
   @RequestMapping("/test2")
    public RedirectView redirect2(){
        RedirectView redirectView=new RedirectView("/redirect/result.action");
       return redirectView;
    }

    /**
     * 乱码设置Tomcat server.xml的Connector添加 useBodyEncodingForURI="true"
     * 参数将会拼接到链接后面
     * @return
     */
    @RequestMapping("/test3")
    public ModelAndView redirect3(){
        ModelAndView modelAndView=new ModelAndView("redirect:/redirect/result0.action");
        modelAndView.addObject("msg","ModelAndView第一种方式带参!");
        return modelAndView;
    }

    @RequestMapping("/test4")
    public ModelAndView redirct4(RedirectAttributes redirectAttributes){
       //这个会将数据返回客户端,客户端再携带过来,参数会拼接到链接后面
        /*redirectAttributes.addAttribute("msg","ModelAndView第二种方式带参");*/
        //数据放到session中,下一个控制器接收到后从session清除,参数不会拼接到链接后面,非跨域建议此方式
        redirectAttributes.addFlashAttribute("msg", "ModelAndView第二种方式带参");
        ModelAndView modelAndView=new ModelAndView("redirect:/redirect/result.action");
        return modelAndView;
    }

    @RequestMapping("/result0")
    public @ResponseBody String result(String msg,HttpServletRequest request){
        //如果是对象,可直接用对象绑定,不用使用ModelMap
        return "返回结果1直接绑定数据模型:"+msg;
    }

    @RequestMapping("/result")
    public @ResponseBody String result(ModelMap map,HttpServletRequest request){
        //如果是对象,可直接用对象绑定,不用使用ModelMap
        String msg=(String)map.get("msg");
        return "返回结果2直接绑定数据模型:"+msg;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics