Spring MVC controller简单处理301跳转

一、 SpringMVC301,302跳转

spring mvc项目是spring的一个子项目用于处理视图层的请求。
302跳转很简单:

@RequestMapping(value = "blog.html")
public String rindex() {
 return "redirect:/blog";
}

按照不重复造轮子的理念,其实301跳转也很简单:

@RequestMapping(value = "blog.html")
public RedirectView rindex(HttpServletRequest request) {
    RedirectView redirectView = new RedirectView("/blog");
    redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
    return redirectView;    
}

spring mvc 提供了一个专门用于处理各种重定向的view视图。
跳转结果如下图:

其它各种实现如:

response.setStatus(301);
response.setHeader("Location", "https://www.xxxx");

二、 Redorect跳转传参

 Redorect传参3种方式

第一种:手动拼接url

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

第二种:RedirectAttributes attributes

这里用它的addAttribute方法,这个实际上重定向过去以后你看url,是它自动给你拼了你的url。
使用方法:
public String test(RedirectAttributes attributes)
{
attributes.addAttribute("test", "hello");
return "redirect:/test/test2";
}

第三种:ModelAndView在model加上属性

ModelAndView  model = new ModelAndView("redirect:/main/index");   
model.addObject("userName", userName);  //把userName参数带入到controller的RedirectAttributes
return model;

评论

暂无评论