网站服务器 优帮云,北京网站建设设计,可以做动漫网站的源码源码,装修公司哪家口碑好问题 工作中场景需要通过获取url地址内容#xff0c;展示返回给客户端#xff0c;但上线后发现不满足需求#xff0c;原因是url地址进行302重定向#xff0c; 进一步了解是因为HttpUtil.get方法不能获取重定向地址#xff0c;需要使用HttpUtil.createGet()来设置打开重定展示返回给客户端但上线后发现不满足需求原因是url地址进行302重定向 进一步了解是因为HttpUtil.get方法不能获取重定向地址需要使用HttpUtil.createGet()来设置打开重定 理解302 302 表示临时性重定向访问一个Url时被重定向到另一个url上常用于页面跳转。 302与301的区别 301是指永久性的移动302是暂时性的即以后还可能有变化 其它重定向方式 在响应头中加入Location参数。浏览器接受到带有location头的响应时就会跳转到相应的地址。 Spring实现302的几种方式
1、使用RedirectView实现重定向 GetMapping(/redirect/v1)public RedirectView redirectV1() {//创建RedirectView对象并设置目标URLRedirectView view new RedirectView();//view.setUrl(https://www.baidu.com);view.setUrl(/springboot/redirect/index);Properties properties new Properties();properties.setProperty(name, make);view.setAttributes(properties);return view;}2、HttpServletResponse重定向 通过HttpServletResponse往输出流中写数据的方式来返回结果, 实现重定向 ResponseBodyGetMapping(/redirect/v2)public void redirectV2(HttpServletResponse response) throws IOException {response.sendRedirect(https://www.sina.com.cn);}3、通过redirect关键词 常适用于返回视图的接口在返回的字符串前面添加redirect:方式来告诉Spring框架需要做302重定向处理; ResponseBodyGetMapping(/redirect/v3)public String redirectV3() throws IOException {return redirect:/redirect/index?baser1;}完整测试
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;Controller
public class RedirectController {/*** 使用RedirectView实现重定向*/GetMapping(/redirect/v1)public RedirectView redirectV1() {//创建RedirectView对象并设置目标URLRedirectView view new RedirectView();//view.setUrl(https://www.baidu.com);view.setUrl(/springboot/redirect/index);Properties properties new Properties();properties.setProperty(name, make);view.setAttributes(properties);return view;}/*** HttpServletResponse重定向* 通过HttpServletResponse往输出流中写数据的方式来返回结果, 实现重定向*/ResponseBodyGetMapping(/redirect/v2)public void redirectV2(HttpServletResponse response) throws IOException {response.sendRedirect(https://www.sina.com.cn);}/*** 返回redirect* 常适用于返回视图的接口在返回的字符串前面添加redirect:方式来告诉Spring框架需要做302重定向处理;*/ResponseBodyGetMapping(/redirect/v3)public String redirectV3() throws IOException {return redirect:/redirect/index?baser1;}ResponseBodyGetMapping(path /redirect/index)public String index(HttpServletRequest request) {return 重定向访问! JSON.toJSONString(request.getParameterMap());}
}