SpringBoot請求轉發(fā)的方式小結
概論
想要使用SpringBoot進行請求的轉發(fā),我們一共是有兩大類(四種方法),一種是controller控制器轉發(fā)一種是使用HttpServletRequest進行轉發(fā),這里每個方式都有兩種轉發(fā)方式一種內部轉發(fā)一種外部轉發(fā)
controller控制器轉發(fā)
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";
}
}切記轉發(fā)不能使用RestController要不然不會被view解析會直接返回對應的字符串到頁面
HttpServleRequest轉發(fā)
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 "收到轉發(fā)的請求";
}
@RequestMapping("/ghr2")
public String ghr2(){
return "ghr2收到轉發(fā)完畢";
}
}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 "轉發(fā)完畢";
}
@RequestMapping("/thr2")
public String r2(HttpServletResponse httpServletResponse) throws IOException {
httpServletResponse.sendRedirect("/ghr2");
return "轉發(fā)完畢!";
}
}注意到底是HttpServleRequest還是HttpServleResponse,并且注意外部轉發(fā)和內部轉發(fā)的優(yōu)缺點。
到此這篇關于SpringBoot請求轉發(fā)的方式小結的文章就介紹到這了,更多相關SpringBoot請求轉發(fā)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決RestTemplate 的getForEntity調用接口亂碼的問題
這篇文章主要介紹了解決RestTemplate 的getForEntity調用接口亂碼的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

