概论
想要使用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解析会直接返回对应的字符串到页面文章来源:https://uudwc.com/A/gVV9O
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,并且注意外部转发和内部转发的优缺点。文章来源地址https://uudwc.com/A/gVV9O