问题
工作中场景需要通过获取url地址内容,展示返回给客户端,但上线后发现不满足需求,原因是url地址进行302重定向,
进一步了解是因为方法不能获取重定向地址,需要使用()来设置打开重定;
理解302:
302 表示临时性重定向,访问一个Url时,被重定向到另一个url上;常用于页面跳转。
302与301的区别:
301是指永久性的移动,302是暂时性的,即以后还可能有变化;
其它重定向方式:
在响应头中加入Location参数。浏览器接受到带有location头的响应时,就会跳转到相应的地址。
Spring实现302的几种方式:
1、使用RedirectView实现重定向
@GetMapping("/redirect/v1")
public RedirectView redirectV1() {
//创建RedirectView对象并设置目标URL
RedirectView view = new RedirectView();
//("");
("/springboot/redirect/index");
Properties properties = new Properties();
("name", "make");
(properties);
return view;
}
2、HttpServletResponse重定向
通过HttpServletResponse往输出流中写数据的方式,来返回结果, 实现重定向
@ResponseBody
@GetMapping("/redirect/v2")
public void redirectV2(HttpServletResponse response) throws IOException {
("");
}
3、通过redirect关键词
常适用于返回视图的接口,在返回的字符串前面添加redirect:方式来告诉Spring框架,需要做302重定向处理;
@ResponseBody
@GetMapping("/redirect/v3")
public String redirectV3() throws IOException {
return "redirect:/redirect/index?base=r1";
}
完整测试:
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Controller
public class RedirectController {
/**
* 使用RedirectView实现重定向
*/
@GetMapping("/redirect/v1")
public RedirectView redirectV1() {
//创建RedirectView对象并设置目标URL
RedirectView view = new RedirectView();
//("");
("/springboot/redirect/index");
Properties properties = new Properties();
("name", "make");
(properties);
return view;
}
/**
* HttpServletResponse重定向
* 通过HttpServletResponse往输出流中写数据的方式,来返回结果, 实现重定向
*/
@ResponseBody
@GetMapping("/redirect/v2")
public void redirectV2(HttpServletResponse response) throws IOException {
("");
}
/**
* 返回redirect
* 常适用于返回视图的接口,在返回的字符串前面添加redirect:方式来告诉Spring框架,需要做302重定向处理;
*/
@ResponseBody
@GetMapping("/redirect/v3")
public String redirectV3() throws IOException {
return "redirect:/redirect/index?base=r1";
}
@ResponseBody
@GetMapping(path = "/redirect/index")
public String index(HttpServletRequest request) {
return "重定向访问! " + (());
}
}