Spring?MVC請(qǐng)求轉(zhuǎn)發(fā)與請(qǐng)求重定向的示例詳解
Spring MVC 請(qǐng)求轉(zhuǎn)發(fā)請(qǐng)求重定向

請(qǐng)求轉(zhuǎn)發(fā)
轉(zhuǎn)發(fā)( forward ),指服務(wù)器接收請(qǐng)求后,從一個(gè)資源跳轉(zhuǎn)到另一個(gè)資源中。請(qǐng)求轉(zhuǎn)發(fā)是一次請(qǐng)求,不會(huì)改變?yōu)g覽器的請(qǐng)求地址。
簡(jiǎn)單示例:
1.通過(guò) String 類(lèi)型的返回值實(shí)現(xiàn)轉(zhuǎn)發(fā)
package cn.edu.springmvcdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ForwardAndRedirectDemo {
@RequestMapping("/forwardTest1")
public String forwardTest1(){
return "ForwardAndRedirect";
}
}創(chuàng)建 ForwardAndRedirect.jsp
<%--
Created by IntelliJ IDEA.
User: dell
Date: 2023/7/28
Time: 22:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h3>請(qǐng)求轉(zhuǎn)發(fā)</h3>
</body>
</html>結(jié)果如圖:

2.通過(guò) ModelAndView 實(shí)現(xiàn)轉(zhuǎn)發(fā)
package cn.edu.springmvcdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ForwardAndRedirectDemo {
@RequestMapping("/forwardTest2")
public ModelAndView forwardTest2(){
ModelAndView mav = new ModelAndView();
mav.setViewName("ForwardAndRedirect");
return mav;
}
}結(jié)果如圖:

3.通過(guò) < mvc:view-controller > 標(biāo)簽實(shí)現(xiàn)轉(zhuǎn)發(fā)
在 Spring MVC 配置文件 springmvc.xml 中配置
<!-- 配置請(qǐng)求轉(zhuǎn)發(fā)實(shí)現(xiàn) --> <!-- 在通過(guò) mvc:view-controller 標(biāo)簽實(shí)現(xiàn)轉(zhuǎn)發(fā)中,添加該配置可以解決同時(shí)也通過(guò) Controller 類(lèi)方法訪問(wèn)出錯(cuò)的問(wèn)題 --> <mvc:annotation-driven /> <!-- path 映射地址;view-name 視圖名字 --> <mvc:view-controller path="/forwardTest3" view-name="ForwardAndRedirect" />
結(jié)果如圖:

注:< mvc:annotation-driven > 是 Spring MVC 框架中的一個(gè)標(biāo)簽,主要作用是自動(dòng)注冊(cè) Spring MVC 的處理器( Handler )和視圖解析器( ViewResolver ),以便在應(yīng)用程序中處理 HTTP 請(qǐng)求并生成相應(yīng)的響應(yīng)。具體來(lái)說(shuō),< mvc:annotation-driven > 標(biāo)簽可以完成以下任務(wù):
注冊(cè) RequestMappingHandlerMapping 處理器映射,用于將 Spring 控制器方法(帶有 @RequestMapping 注釋?zhuān)┯成涞?HTTP 請(qǐng)求注冊(cè) ExceptionHandlerExceptionResolver 異常處理器解析器,用于處理在控制器方法執(zhí)行期間發(fā)生的異常注冊(cè) MessageConverter 消息轉(zhuǎn)換器,用于將請(qǐng)求消息轉(zhuǎn)換為控制器方法參數(shù)的類(lèi)型,并將響應(yīng)消息轉(zhuǎn)換為視圖解析器所需的類(lèi)型注冊(cè) RequestResponseBodyAdvice advice,用于在請(qǐng)求和響應(yīng)之間進(jìn)行轉(zhuǎn)換和類(lèi)型轉(zhuǎn)換通過(guò)使用 < mvc:annotation-driven > 標(biāo)簽,開(kāi)發(fā)人員可以更加簡(jiǎn)潔地配置 MVC 模式中的控制器部分,而無(wú)需手動(dòng)注冊(cè)這些組件,可以使代碼更加清晰和易于維護(hù)。
請(qǐng)求重定向
重定向( redirect ),指服務(wù)器接收請(qǐng)求后,不能跳轉(zhuǎn)到當(dāng)前請(qǐng)求地址指向的資源中,但會(huì)指定新的資源地址返回給客戶(hù)端,客戶(hù)端再次請(qǐng)求訪問(wèn)指定資源。請(qǐng)求重定向是兩次請(qǐng)求,會(huì)改變?yōu)g覽器的請(qǐng)求地址。
簡(jiǎn)單示例:
1.通過(guò) String 類(lèi)型的返回值實(shí)現(xiàn)重定向
package cn.edu.springmvcdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ForwardAndRedirectDemo {
//新的資源地址
@RequestMapping("/redirectIndex")
public String redirect(){
return "ForwardAndRedirect";
}
//請(qǐng)求重定向
@RequestMapping("/redirectTest1")
public String redirectTest1(){
//指定新的資源地址
return "redirect:/redirectIndex";
}
}ForwardAndRedirect.jsp 內(nèi)容簡(jiǎn)單修改
<%--
Created by IntelliJ IDEA.
User: dell
Date: 2023/7/28
Time: 22:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h3>請(qǐng)求重定向</h3>
</body>
</html>結(jié)果如圖:輸入 redirectTest1 后自動(dòng)跳轉(zhuǎn)到 redirectIndex

2.通過(guò) ModelAndView 實(shí)現(xiàn)重定向
package cn.edu.springmvcdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ForwardAndRedirectDemo {
@RequestMapping("/redirectIndex")
public String redirect(){
return "ForwardAndRedirect";
}
@RequestMapping("/redirectTest2")
public ModelAndView redirectTest2(){
ModelAndView mav = new ModelAndView();
mav.setViewName("redirect:/redirectIndex");
return mav;
}
}結(jié)果如圖:輸入 redirectTest2 后自動(dòng)跳轉(zhuǎn)到 redirectIndex

3.通過(guò) < mvc:view-controller > 標(biāo)簽實(shí)現(xiàn)重定向同理,只需在 springmvc.xml 中配置
<!-- 配置請(qǐng)求轉(zhuǎn)發(fā)重定向 --> <!-- path 映射地址;view-name 指定新的資源地址 --> <mvc:view-controller path="/redirectTest3" view-name="redirect:/redirectIndex" />
結(jié)果如圖:輸入 redirectTest3 后自動(dòng)跳轉(zhuǎn)到 redirectIndex

附
自定義視圖,指定義一個(gè)自定義的視圖對(duì)象,用于渲染模型數(shù)據(jù)并生成響應(yīng)。自定義視圖可以繼承 View 、AbstractExcelView 或 AbstractPdfView 來(lái)將內(nèi)容以某種格式( Excel 、Pdf 等)顯示。
簡(jiǎn)單示例:下載 Excel 文檔的需求實(shí)現(xiàn)
首先,在 pom.xml 中添加以下依賴(lài)
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
接著,創(chuàng)建自定義視圖類(lèi) ExcelViewDemo 繼承 AbstractXlsxView ,設(shè)置文檔的相關(guān)信息與數(shù)據(jù)寫(xiě)入
package cn.edu.springmvcdemo.web;
import cn.edu.springmvcdemo.model.DomainObject;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.servlet.view.document.AbstractXlsxView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
public class ExcelViewDemo extends AbstractXlsxView {
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
//設(shè)置文檔名字
String file = "ExcelTest.xlsx";
//設(shè)置字符編碼
response.setCharacterEncoding("UTF-8");
//設(shè)置內(nèi)容類(lèi)型,在 apache-tomcat-8.5.75/conf/web.xml 配置文件中查找 xlsx 可獲取對(duì)應(yīng)類(lèi)型寫(xiě)法
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//設(shè)置頭部信息(下載,下載文件名字)
response.setHeader("Content-Disposition","inline;file" + new String(file.getBytes(),"UTF-8"));
//獲取 model 數(shù)據(jù)( controller 類(lèi)處理方法中放進(jìn)的數(shù)據(jù))
List<DomainObject> domainObjects = (List<DomainObject>) model.get("domainObjects");
//獲取數(shù)據(jù)后轉(zhuǎn)換成 Excel 視圖返回
//1.創(chuàng)建 Excel 表(表中 sheet 的名字)
Sheet sheet = workbook.createSheet("數(shù)據(jù)表");
//2.創(chuàng)建第一行
Row headRow = sheet.createRow(0);
//3.創(chuàng)建第一行的1、2、3列
headRow.createCell(0).setCellValue("編號(hào)");
headRow.createCell(1).setCellValue("姓名");
headRow.createCell(2).setCellValue("年齡");
//遍歷獲取數(shù)據(jù)寫(xiě)入表中
int rowNum = 1; //從表的第二行開(kāi)始
for(DomainObject domainObject:domainObjects){
//創(chuàng)建新的一行
Row row = sheet.createRow(rowNum++);
//獲取對(duì)應(yīng)的數(shù)據(jù)
row.createCell(0).setCellValue(domainObject.getId());
row.createCell(1).setCellValue(domainObject.getName());
row.createCell(2).setCellValue(domainObject.getAge());
}
OutputStream outputStream = response.getOutputStream();
//將數(shù)據(jù)寫(xiě)入輸出流
workbook.write(outputStream);
//清空輸出流
outputStream.flush();
//關(guān)閉輸出流
outputStream.close();
}
}然后,創(chuàng)建 controller 類(lèi)的方法,獲取數(shù)據(jù)
package cn.edu.springmvcdemo.controller;
import cn.edu.springmvcdemo.model.DomainObject;
import cn.edu.springmvcdemo.web.ExcelViewDemo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class ExcelDemo {
@RequestMapping("/excelDownload")
public ModelAndView excelViewTest(){
Map<String,Object> map = new HashMap<>();
//模擬:數(shù)據(jù)庫(kù)中取出一個(gè) domainObjects 的 list 集合
DomainObject domainObject1 = new DomainObject();
domainObject1.setId(728);
domainObject1.setName("曹操");
domainObject1.setAge(24);
DomainObject domainObject2 = new DomainObject();
domainObject2.setId(729);
domainObject2.setName("劉備");
domainObject2.setAge(22);
DomainObject domainObject3 = new DomainObject();
domainObject3.setId(730);
domainObject3.setName("孫權(quán)");
domainObject3.setAge(18);
//先將數(shù)據(jù)放入 list 集合
List<DomainObject> list = new ArrayList<>();
list.add(domainObject1);
list.add(domainObject2);
list.add(domainObject3);
// list 集合再放入 map 集合中
// 鍵的名字與 (List<DomainObject>) model.get("domainObjects") 中的名字保持一致
map.put("domainObjects",list);
//(自定義視圖對(duì)象,數(shù)據(jù))
ModelAndView mav = new ModelAndView(new ExcelViewDemo(),map);
return mav;
}
}最后,重啟服務(wù)器,測(cè)試結(jié)果輸入地址,彈出下載窗口。結(jié)果如圖:

Excel 表內(nèi)容如圖:

到此這篇關(guān)于Spring MVC請(qǐng)求轉(zhuǎn)發(fā)與請(qǐng)求重定向的文章就介紹到這了,更多相關(guān)Spring MVC請(qǐng)求轉(zhuǎn)發(fā)和重定向內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Spring框架之基于Restful風(fēng)格實(shí)現(xiàn)的SpringMVC
這篇文章主要介紹了詳解Spring框架之基于Restful風(fēng)格實(shí)現(xiàn)的SpringMVC,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
IDEA項(xiàng)目如何實(shí)現(xiàn)打jar包
這篇文章主要介紹了IDEA項(xiàng)目如何實(shí)現(xiàn)打jar包問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
springboot 整合 sa-token簡(jiǎn)介及入門(mén)教程
Sa-Token 是一個(gè)輕量級(jí) Java 權(quán)限認(rèn)證框架,主要解決:登錄認(rèn)證、權(quán)限認(rèn)證、Session會(huì)話、單點(diǎn)登錄、OAuth2.0、微服務(wù)網(wǎng)關(guān)鑒權(quán) 等一系列權(quán)限相關(guān)問(wèn)題,這篇文章主要介紹了springboot 整合 sa-token簡(jiǎn)介及入門(mén)教程,需要的朋友可以參考下2023-05-05
Java實(shí)現(xiàn)上傳和下載功能(支持多個(gè)文件同時(shí)上傳)
這篇文章主要介紹了Java實(shí)現(xiàn)上傳和下載功能,支持多個(gè)文件同時(shí)上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12
Mybatis-plus的selectPage()分頁(yè)查詢(xún)不生效問(wèn)題解決
本文主要介紹了Mybatis-plus的selectPage()分頁(yè)查詢(xún)不生效問(wèn)題解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
Java中的模板模式說(shuō)明與實(shí)現(xiàn)
這篇文章主要介紹了Java中的模板模式說(shuō)明與實(shí)現(xiàn),模板方法模式,又叫模板模式,在一個(gè)抽象類(lèi)公開(kāi)定義了執(zhí)行它的方法的模板,它的子類(lèi)可以更需要重寫(xiě)方法實(shí)現(xiàn),但可以成為典型類(lèi)中定義的方式進(jìn)行,需要的朋友可以參考下2023-10-10
Spring Cloud Feign文件傳輸?shù)氖纠a
微服務(wù)中通常使用 Feign 作為服務(wù)消費(fèi)者,那么如何使用 Feign 接口傳輸文件呢?這篇文章主要介紹了Spring Cloud Feign文件傳輸?shù)氖纠a,感興趣的小伙伴們可以參考一下2018-06-06
org.slf4j.Logger中info()方法的使用詳解
這篇文章主要介紹了org.slf4j.Logger中info()方法的使用詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
ActiveMQ基于zookeeper的主從(levelDB Master/Slave)搭建
這篇文章主要介紹了ActiveMQ基于zookeeper的主從levelDB Master/Slave搭建,以及Spring-boot下的使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08

