2023-06-27
spring Java 鄭州 濟(jì)南
在Spring MVC框架中,請(qǐng)求轉(zhuǎn)發(fā)和重定向是常用的頁(yè)面跳轉(zhuǎn)方式。它們可以實(shí)現(xiàn)不同的功能和效果。
1. 請(qǐng)求轉(zhuǎn)發(fā)(Forward):
請(qǐng)求轉(zhuǎn)發(fā)是指將請(qǐng)求從當(dāng)前處理器轉(zhuǎn)發(fā)到另一個(gè)處理器或頁(yè)面,由另一個(gè)處理器或頁(yè)面繼續(xù)處理請(qǐng)求。在Spring MVC中,使用`forward:`前綴來(lái)實(shí)現(xiàn)請(qǐng)求轉(zhuǎn)發(fā)。具體的方法有:
- 控制器方法返回字符串類型的視圖名稱,前綴為`forward:`,例如:
@RequestMapping("/forward")
public String forward() {
return "forward:/anotherMapping";
}
- 使用`RequestDispatcher`對(duì)象進(jìn)行請(qǐng)求轉(zhuǎn)發(fā),例如:
@RequestMapping("/forward")
public void forward(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("/anotherMapping");
dispatcher.forward(request, response);
}
2. 重定向(Redirect):
重定向是指將請(qǐng)求從當(dāng)前處理器重定向到另一個(gè)URL,瀏覽器會(huì)發(fā)起一個(gè)新的請(qǐng)求去訪問(wèn)該URL。在Spring MVC中,使用`redirect:`前綴來(lái)實(shí)現(xiàn)重定向。具體的方法有:
- 控制器方法返回字符串類型的重定向URL,前綴為`redirect:`,例如:
@RequestMapping("/redirect")
public String redirect() {
return "redirect:/anotherMapping";
}
- 使用`RedirectView`對(duì)象進(jìn)行重定向,例如:
@RequestMapping("/redirect")
public ModelAndView redirect() {
RedirectView redirectView = new RedirectView("/anotherMapping");
return new ModelAndView(redirectView);
}
需要注意的是,請(qǐng)求轉(zhuǎn)發(fā)是服務(wù)器內(nèi)部的操作,對(duì)客戶端是透明的,而重定向是客戶端行為,會(huì)導(dǎo)致瀏覽器發(fā)起新的請(qǐng)求。
在使用請(qǐng)求轉(zhuǎn)發(fā)和重定向時(shí),可以攜帶參數(shù),例如:
@RequestMapping("/forwardWithParam")
public String forwardWithParam(HttpServletRequest request) {
request.setAttribute("param", "value");
return "forward:/anotherMapping";
}
@RequestMapping("/redirectWithParam")
public String redirectWithParam(HttpServletRequest request, RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute("param", "value");
return "redirect:/anotherMapping";
}
這樣在目標(biāo)處理器或頁(yè)面中可以通過(guò)`request`對(duì)象或`RedirectAttributes`對(duì)象獲取參數(shù)值。
通過(guò)請(qǐng)求轉(zhuǎn)發(fā)和重定向,可以實(shí)現(xiàn)不同的業(yè)務(wù)需求,選擇合適的方式取決于具體的場(chǎng)景和功能要求。
開(kāi)班時(shí)間:2021-04-12(深圳)
開(kāi)班盛況開(kāi)班時(shí)間:2021-05-17(北京)
開(kāi)班盛況開(kāi)班時(shí)間:2021-03-22(杭州)
開(kāi)班盛況開(kāi)班時(shí)間:2021-04-26(北京)
開(kāi)班盛況開(kāi)班時(shí)間:2021-05-10(北京)
開(kāi)班盛況開(kāi)班時(shí)間:2021-02-22(北京)
開(kāi)班盛況開(kāi)班時(shí)間:2021-07-12(北京)
預(yù)約報(bào)名開(kāi)班時(shí)間:2020-09-21(上海)
開(kāi)班盛況開(kāi)班時(shí)間:2021-07-12(北京)
預(yù)約報(bào)名開(kāi)班時(shí)間:2019-07-22(北京)
開(kāi)班盛況
Copyright 2011-2023 北京千鋒互聯(lián)科技有限公司 .All Right
京ICP備12003911號(hào)-5
京公網(wǎng)安備 11010802035720號(hào)