SpringBoot请求转发的方式小结
作者:堕落年代
本文主要介绍了SpringBoot请求转发的方式,一共有两大类,一种是controller控制器转发一种是使用HttpServletRequest进行转发,本文就详细的介绍一下,感兴趣的可以了解一下
概论
想要使用SpringBoot进行请求的转发,我们一共是有两大类(四种方法),一种是controller控制器转发一种是使用HttpServletRequest进行转发,这里每个方式都有两种转发方式一种内部转发一种外部转发
controller控制器转发
package com.example.requestplay.demos.web.RequestPlay1; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author:DUOLUONIANDAI * @DATA:2023/07/26 11:24 * @Title: */ @RestController public class GetPlay { @RequestMapping("/r1") public String r1(){ return "收到请求rt1"; } @RequestMapping("/r2") public String r2(){ return "收到请求rt2"; } }
package com.example.requestplay.demos.web.RequestPlay1; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author:DUOLUONIANDAI * @DATA:2023/07/26 11:24 * @Title: */ @Controller public class ToGetPlay { @RequestMapping("/tr1") public String r1(){ return "forward:/r1"; } @RequestMapping("/tr2") public String r2(){ return "redirect:/r2"; } }
切记转发不能使用RestController要不然不会被view解析会直接返回对应的字符串到页面
HttpServleRequest转发
package com.example.requestplay.demos.web.RequestPlay2; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author:DUOLUONIANDAI * @DATA:2023/07/26 11:40 * @Title: */ @RestController public class GetRequest { @RequestMapping("/ghr1") public String ghr1(){ return "收到转发的请求"; } @RequestMapping("/ghr2") public String ghr2(){ return "ghr2收到转发完毕"; } }
package com.example.requestplay.demos.web.RequestPlay2; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author:DUOLUONIANDAI * @DATA:2023/07/26 11:39 * @Title: */ @RestController public class ToRequest { @RequestMapping("/thr1") public String r1(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { RequestDispatcher requestDispatcher = httpServletRequest.getRequestDispatcher("/ghr1"); requestDispatcher.forward(httpServletRequest,httpServletResponse); return "转发完毕"; } @RequestMapping("/thr2") public String r2(HttpServletResponse httpServletResponse) throws IOException { httpServletResponse.sendRedirect("/ghr2"); return "转发完毕!"; } }
注意到底是HttpServleRequest还是HttpServleResponse,并且注意外部转发和内部转发的优缺点。
到此这篇关于SpringBoot请求转发的方式小结的文章就介绍到这了,更多相关SpringBoot请求转发内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!