springmvc请求重定向

请求重定向的作用是将请求,重定向至另外一个处理程序。它的特点是两次请求,浏览器地址会改变,用户可以感知

转发操作,可以使用ModelAndView对象

return new ModelAndView("redirect:viewName",modelMap);

也可以直接返回字符串视图名

return "redirect:viewName";

当重定向需要携带参数时可以使用RedirectAttributes

package com.example.redirect.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class HelloController {

    @RequestMapping("hello/{name}")
    public String hello(@PathVariable String name, RedirectAttributes redirectAttributes){
        System.out.println("hello,"+name);
        redirectAttributes.addFlashAttribute("name",name);
        return "redirect:/welcome/{name}";
    }
}

另一个控制器

package com.example.redirect.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class WelcomController {

    @RequestMapping("welcome/{name}")
    @ResponseBody
    public String welcome(@PathVariable String name){
        System.out.println("welcome,"+name);
        return "welcome,"+name;
    }
}

使用addFlashAttribute方法把需要的参数添加进去
在转发的控制器依然可以拿到路径参数

addFlashAttributeaddAttribute的区别是,前者实际是把信息存在用户的session里,然后在下次请求前删除参数,路径中看不到参数;后者是把参数添加在请求中,再进行重定向——参数会被添加在url里

例如:
原请求

http://localhost:8080/hello?name=123

重定向后

http://localhost:8080/welcome?name=123

在使用路径参数时不能从路径中看出差别

不使用路径参数时addFlashAttribute添加的参数,在控制器中使用@ModelAttribute注解得到

 @RequestMapping("hello")
    public String hello(String name, RedirectAttributes redirectAttributes){
        System.out.println("hello,"+name);
        redirectAttributes.addFlashAttribute("name",name);
//        redirectAttributes.addAttribute("name",name);
        return "redirect:/welcome";
    }
 @RequestMapping("welcome")
    @ResponseBody
    public String welcome(@ModelAttribute("name") String name){
        System.out.println("welcome,"+name);
        return "welcome,"+name;
    }

使用addAttribute添加的参数,依然使用@RequestParam获取

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值