Spring?MVC請求轉發(fā)與請求重定向的示例詳解
Spring MVC 請求轉發(fā)請求重定向
請求轉發(fā)
轉發(fā)( forward ),指服務器接收請求后,從一個資源跳轉到另一個資源中。請求轉發(fā)是一次請求,不會改變?yōu)g覽器的請求地址。
簡單示例:
1.通過 String 類型的返回值實現(xià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>請求轉發(fā)</h3> </body> </html>
結果如圖:
2.通過 ModelAndView 實現(xià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; } }
結果如圖:
3.通過 < mvc:view-controller > 標簽實現(xiàn)轉發(fā)
在 Spring MVC 配置文件 springmvc.xml 中配置
<!-- 配置請求轉發(fā)實現(xiàn) --> <!-- 在通過 mvc:view-controller 標簽實現(xiàn)轉發(fā)中,添加該配置可以解決同時也通過 Controller 類方法訪問出錯的問題 --> <mvc:annotation-driven /> <!-- path 映射地址;view-name 視圖名字 --> <mvc:view-controller path="/forwardTest3" view-name="ForwardAndRedirect" />
結果如圖:
注:< mvc:annotation-driven > 是 Spring MVC 框架中的一個標簽,主要作用是自動注冊 Spring MVC 的處理器( Handler )和視圖解析器( ViewResolver ),以便在應用程序中處理 HTTP 請求并生成相應的響應。具體來說,< mvc:annotation-driven > 標簽可以完成以下任務:
注冊 RequestMappingHandlerMapping 處理器映射,用于將 Spring 控制器方法(帶有 @RequestMapping 注釋)映射到 HTTP 請求注冊 ExceptionHandlerExceptionResolver 異常處理器解析器,用于處理在控制器方法執(zhí)行期間發(fā)生的異常注冊 MessageConverter 消息轉換器,用于將請求消息轉換為控制器方法參數(shù)的類型,并將響應消息轉換為視圖解析器所需的類型注冊 RequestResponseBodyAdvice advice,用于在請求和響應之間進行轉換和類型轉換通過使用 < mvc:annotation-driven > 標簽,開發(fā)人員可以更加簡潔地配置 MVC 模式中的控制器部分,而無需手動注冊這些組件,可以使代碼更加清晰和易于維護。
請求重定向
重定向( redirect ),指服務器接收請求后,不能跳轉到當前請求地址指向的資源中,但會指定新的資源地址返回給客戶端,客戶端再次請求訪問指定資源。請求重定向是兩次請求,會改變?yōu)g覽器的請求地址。
簡單示例:
1.通過 String 類型的返回值實現(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"; } //請求重定向 @RequestMapping("/redirectTest1") public String redirectTest1(){ //指定新的資源地址 return "redirect:/redirectIndex"; } }
ForwardAndRedirect.jsp 內(nèi)容簡單修改
<%-- 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>請求重定向</h3> </body> </html>
結果如圖:輸入 redirectTest1 后自動跳轉到 redirectIndex
2.通過 ModelAndView 實現(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; } }
結果如圖:輸入 redirectTest2 后自動跳轉到 redirectIndex
3.通過 < mvc:view-controller > 標簽實現(xiàn)重定向同理,只需在 springmvc.xml 中配置
<!-- 配置請求轉發(fā)重定向 --> <!-- path 映射地址;view-name 指定新的資源地址 --> <mvc:view-controller path="/redirectTest3" view-name="redirect:/redirectIndex" />
結果如圖:輸入 redirectTest3 后自動跳轉到 redirectIndex
附
自定義視圖,指定義一個自定義的視圖對象,用于渲染模型數(shù)據(jù)并生成響應。自定義視圖可以繼承 View 、AbstractExcelView 或 AbstractPdfView 來將內(nèi)容以某種格式( Excel 、Pdf 等)顯示。
簡單示例:下載 Excel 文檔的需求實現(xiàn)
首先,在 pom.xml 中添加以下依賴
<!-- 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)建自定義視圖類 ExcelViewDemo 繼承 AbstractXlsxView ,設置文檔的相關信息與數(shù)據(jù)寫入
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 { //設置文檔名字 String file = "ExcelTest.xlsx"; //設置字符編碼 response.setCharacterEncoding("UTF-8"); //設置內(nèi)容類型,在 apache-tomcat-8.5.75/conf/web.xml 配置文件中查找 xlsx 可獲取對應類型寫法 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); //設置頭部信息(下載,下載文件名字) response.setHeader("Content-Disposition","inline;file" + new String(file.getBytes(),"UTF-8")); //獲取 model 數(shù)據(jù)( controller 類處理方法中放進的數(shù)據(jù)) List<DomainObject> domainObjects = (List<DomainObject>) model.get("domainObjects"); //獲取數(shù)據(jù)后轉換成 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("編號"); headRow.createCell(1).setCellValue("姓名"); headRow.createCell(2).setCellValue("年齡"); //遍歷獲取數(shù)據(jù)寫入表中 int rowNum = 1; //從表的第二行開始 for(DomainObject domainObject:domainObjects){ //創(chuàng)建新的一行 Row row = sheet.createRow(rowNum++); //獲取對應的數(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ù)寫入輸出流 workbook.write(outputStream); //清空輸出流 outputStream.flush(); //關閉輸出流 outputStream.close(); } }
然后,創(chuàng)建 controller 類的方法,獲取數(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ù)庫中取出一個 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("孫權"); 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); //(自定義視圖對象,數(shù)據(jù)) ModelAndView mav = new ModelAndView(new ExcelViewDemo(),map); return mav; } }
最后,重啟服務器,測試結果輸入地址,彈出下載窗口。結果如圖:
Excel 表內(nèi)容如圖:
到此這篇關于Spring MVC請求轉發(fā)與請求重定向的文章就介紹到這了,更多相關Spring MVC請求轉發(fā)和重定向內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
spring boot使用WebClient調(diào)用HTTP服務代碼示例
這篇文章主要介紹了spring boot使用WebClient調(diào)用HTTP服務代碼示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12SpringBoot集成P6Spy實現(xiàn)SQL日志的記錄詳解
P6Spy是一個框架,它可以無縫地攔截和記錄數(shù)據(jù)庫活動,而無需更改現(xiàn)有應用程序的代碼。一般我們使用的比較多的是使用p6spy打印我們最后執(zhí)行的sql語句2022-11-11淺析打開eclipse出現(xiàn)Incompatible JVM的解決方法
本篇文章是對打開eclipse出現(xiàn)Incompatible JVM的解決方法進行了詳細的分析介紹,需要的朋友參考下2013-07-07淺談String類型等值比較引起的“==”、“equals()”和“hashCode”思考
這篇文章主要介紹了淺談String類型等值比較引起的“==”、“equals()”和“hashCode”思考。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09java使用listIterator逆序arraylist示例分享
對于列表而言,除了Iterator,還提供了一個功能更加強大的ListIterator。它可以實現(xiàn)逆序遍歷列表中的元素。本示例將使用其逆序遍歷ArrayList2014-02-02Windows下java、javaw、javaws以及jvm.dll等進程的區(qū)別
這篇文章主要介紹了Windows下java、javaw、javaws以及jvm.dll等進程的區(qū)別,本文分別講解了它們的作用并給出代碼實例,最后做出了區(qū)別總結,需要的朋友可以參考下2015-03-03