0


SpringBoot请求转发的方式

概论

想要使用SpringBoot进行请求的转发,我们一共是有两大类(四种方法),一种是controller控制器转发一种是使用HttpServletRequest进行转发,这里每个方式都有两种转发方式一种内部转发一种外部转发

controller控制器转发

packagecom.example.requestplay.demos.web.RequestPlay1;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;/**
 * @author:DUOLUONIANDAI
 * @DATA:2023/07/26 11:24
 * @Title:
 */@RestControllerpublicclassGetPlay{@RequestMapping("/r1")publicStringr1(){return"收到请求rt1";}@RequestMapping("/r2")publicStringr2(){return"收到请求rt2";}}
packagecom.example.requestplay.demos.web.RequestPlay1;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;/**
 * @author:DUOLUONIANDAI
 * @DATA:2023/07/26 11:24
 * @Title:
 */@ControllerpublicclassToGetPlay{@RequestMapping("/tr1")publicStringr1(){return"forward:/r1";}@RequestMapping("/tr2")publicStringr2(){return"redirect:/r2";}}

切记转发不能使用RestController要不然不会被view解析会直接返回对应的字符串到页面

HttpServleRequest转发

packagecom.example.requestplay.demos.web.RequestPlay2;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;/**
 * @author:DUOLUONIANDAI
 * @DATA:2023/07/26 11:40
 * @Title:
 */@RestControllerpublicclassGetRequest{@RequestMapping("/ghr1")publicStringghr1(){return"收到转发的请求";}@RequestMapping("/ghr2")publicStringghr2(){return"ghr2收到转发完毕";}}
packagecom.example.requestplay.demos.web.RequestPlay2;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/**
 * @author:DUOLUONIANDAI
 * @DATA:2023/07/26 11:39
 * @Title:
 */@RestControllerpublicclassToRequest{@RequestMapping("/thr1")publicStringr1(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse)throwsServletException,IOException{RequestDispatcher requestDispatcher = httpServletRequest.getRequestDispatcher("/ghr1");
        requestDispatcher.forward(httpServletRequest,httpServletResponse);return"转发完毕";}@RequestMapping("/thr2")publicStringr2(HttpServletResponse httpServletResponse)throwsIOException{
        httpServletResponse.sendRedirect("/ghr2");return"转发完毕!";}}

注意到底是HttpServleRequest还是HttpServleResponse,并且注意外部转发和内部转发的优缺点。

标签: spring boot 后端 java

本文转载自: https://blog.csdn.net/qq_45153375/article/details/131935804
版权归原作者 堕落年代 所有, 如有侵权,请联系我们删除。

“SpringBoot请求转发的方式”的评论:

还没有评论