Spring MVC 獲取三個域(request請求域,session 會話域,application 應用域)對象的方式

来源:https://www.cnblogs.com/TheMagicalRainbowSea/p/18276658
-Advertisement-
Play Games

1. Spring MVC 獲取三個域(request請求域,session 會話域,application 應用域)對象的方式 @目錄1. Spring MVC 獲取三個域(request請求域,session 會話域,application 應用域)對象的方式2. Servlet中的三個域對象3 ...


1. Spring MVC 獲取三個域(request請求域,session 會話域,application 應用域)對象的方式

@

目錄


2. Servlet中的三個域對象

Servlet 中的三個域對象分別是:

請求域:request
會話域:session
應用域:application
三個域都有以下三個方法:

// 向域中存儲數據
void setAttribute(String name, Object obj);

// 從域中讀取數據
Object getAttribute(String name);

// 刪除域中的數據
void removeAttribute(String name);

主要是通過:setAttribute + getAttribute 方法來完成在域中數據的傳遞和共用。

request:

介面名:HttpServletRequest
簡稱:request
request對象代表了一次請求。一次請求一個request。

使用請求域的業務場景:

在A資源中通過轉發的方式跳轉到B資源,因為是轉發,因此從A到B是一次請求,如果想讓A資源和B資源共用同一個數據,可以將數據存儲到request域中。

session:

介面名:HttpSession
簡稱:session
session對象代表了一次會話。從打開瀏覽器開始訪問,到最終瀏覽器關閉,這是一次完整的會話。每個會話session對象都對應一個JSESSIONID,而JSESSIONID生成後以cookie的方式存儲在瀏覽器客戶端。瀏覽器關閉,JSESSIONID失效,會話結束。

使用會話域的業務場景:

  1. 在 A 資源中通過重定向(重定向是一次新的請求)的方式轉到 B 資源,因為是重定向,因此從 A到 B 是兩次請求,如果想讓 A 資源和 B 資源共用同一個數據,可以將數據存儲到 session域中
  2. 登錄成功後保存用戶的登錄狀態

application

介面名:ServletContext
簡稱:application
application對象代表了整個 web 應用,伺服器啟動的創建,伺服器關閉時銷毀,對於一個 web 應用來說,application 對象只有一個。

使用應用域的業務場景:記錄網站的線上人數。

3. 準備工作

3.1 創建模塊,添加依賴

在這裡插入圖片描述

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.rainbowsea</groupId>
    <artifactId>springmvc-004-blog</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <!--springmvc依賴-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>6.1.4</version>
        </dependency>
        <!--logback依賴-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.5.3</version>
        </dependency>
        <!--servlet依賴-->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.0.0</version>
            <scope>provided</scope>
        </dependency>
        <!--thymeleaf和spring6整合的依賴-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring6</artifactId>
            <version>3.1.2.RELEASE</version>
        </dependency>
    </dependencies>


</project>

3.2 添加 web 支持

先在 main 目錄下,添加名為 webapp 的目錄(文件夾),只能是這個 webapp 目錄名,不可以是其他的。

在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述


3.3 編寫 web.xml 文件

在這裡插入圖片描述

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
         version="5.0">

    <!--前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通過初始化參數來指定springmvc配置文件的路徑和名字。-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--在伺服器啟動的時候初始化DispatcherServlet,提高第一次訪問的效率-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
<!--        除了 jsp 其他的路徑都被獲取到-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

3.4 創建 IndexController 類

創建 IndexController 類作為 首頁來使用

在這裡插入圖片描述

package com.rainbowsea.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller // 交給 Spring IOC 容器管理
public class IndexController {


    @RequestMapping("/")
    public String index() {
        return "index";
    }
}

3.5 編寫 springmvc.xml

在 springmvc.xml 當中配置兩個信息:

  • 組件掃描
  • 視圖解析器

在這裡插入圖片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--    組件掃描-->
    <context:component-scan base-package="com.rainbowsea.springmvc.controller"></context:component-scan>

    <!--    視圖解析器-->
    <bean id="thymeleafViewResolver" class="org.thymeleaf.spring6.view.ThymeleafViewResolver">
        <!--作用於視圖渲染的過程中,可以設置視圖渲染後輸出時採用的編碼字元集-->
        <property name="characterEncoding" value="UTF-8"/>
        <!--如果配置多個視圖解析器,它來決定優先使用哪個視圖解析器,它的值越小優先順序越高-->
        <property name="order" value="1"/>
        <!--當 ThymeleafViewResolver 渲染模板時,會使用該模板引擎來解析、編譯和渲染模板-->
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring6.SpringTemplateEngine">
                <!--用於指定 Thymeleaf 模板引擎使用的模板解析器。模板解析器負責根據模板位置、模板資源名稱、文件編碼等信息,載入模板並對其進行解析-->
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver">
                        <!--設置模板文件的位置(首碼)-->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!--設置模板文件尾碼(尾碼),Thymeleaf文件擴展名不一定是html,也可以是其他,例如txt,大部分都是html-->
                        <property name="suffix" value=".html"/>
                        <!--設置模板類型,例如:HTML,TEXT,JAVASCRIPT,CSS等-->
                        <property name="templateMode" value="HTML"/>
                        <!--用於模板文件在讀取和解析過程中採用的編碼字元集-->
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

</beans>

3.6 編寫 index.html 文件視圖

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試三個對象</title>
</head>
<body>
<h1>測試三個域對象</h1>
<hr>
<h2>測試 request 域對象</h2>
</body>
</html>

3.7 部署測試

在這裡插入圖片描述


4. Spring MVC 獲取 request 請求域對象的五種方式

在SpringMVC中,在request域中共用數據有以下五種方式:

  1. 使用原生Servlet API方式。
  2. 使用Model介面。
  3. 使用Map介面。
  4. 使用ModelMap類。
  5. 使用ModelAndView類。

4.1 第一種方式:使用原生Servlet API方式 獲取到 request 請求域,同時獲取到請求域當中對應的內容

第一種方式: 在Spring MVC 中使用原生的 Servlet API 可以完成 request 域數據共用
,在處理器方法上添加 HttpServletRequest 參數即可。

將 HttpServletRequest 作為參數,定義到方法上,Spring MVC 框架會自動從 Tomcat 伺服器當中獲取到這個 HttpServletRequest 對象的值,然後,傳遞給這個方法的 HttpServletRequest 參數值上,完成賦值。

創建一個 RequestScopeTestController 類,註意要交給 Spring IOC 容器管理起來

在這裡插入圖片描述

package com.rainbowsea.springmvc.controller;


import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller // 交給Spring IOC 容器管理
public class RequestScopeTestController {


    // request 請求域
    @RequestMapping("/testServletAPI")
    public String testServletAPI(HttpServletRequest request) {

        // 將共用的數據存儲到 request域當中
        // 跳轉視圖,在視圖頁面將request域中的數據取出,這樣就完成了,Controller和View在同一個請求當中兩個組件之間的數據共用

        // 將共用的數據存儲到request域當中
        request.setAttribute("testRequestScope", "在SpringMVC當中使用原生Servlet API 完成 request域的數據共用");
        System.out.println(request);
        System.out.println(request.getClass().getName());

        // 跳轉視圖,在視圖頁面將 request 域中的數據取出來,這樣就完成了,Controller 和 View 在同
        // 一個請求當中兩個組件之間數據的共用

        // 註意:這個是跳轉,預設情況下是,轉發的方式,(轉發 forward 是一次請求)
        // 這個返回的是一個邏輯視圖名稱,經過視圖解析器解析,變成物理視圖名稱,/WEB-INF/templates/ok.html
        return "ok";
    }

}

index頁面超鏈接的編寫:

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試三個對象</title>
</head>
<body>
<h1>測試三個域對象</h1>
<hr>
<h2>測試 request 域對象</h2>


<a th:href="@{/testServletAPI}">測試在SpringMVC當中使用原生 Servlet API 完成 request 域的數據共用</a>
<br>

</body>
</html>

ok 頁面獲取 request 請求域的展示

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試三個對象</title>
</head>
<body>
<h1>測試三個域對象</h1>
<hr>
<h2>測試 request 域對象</h2>


<a th:href="@{/testServletAPI}">測試在SpringMVC當中使用原生 Servlet API 完成 request 域的數據共用</a>
<br>

</body>
</html>

測試結果:

在這裡插入圖片描述

這種方式當然可以,用 SpringMVC 框架,不建議使用原生 Servlet API

4.2 第二種方式:使用 Model 介面 獲取到 request 請求域,同時獲取到請求域當中對應的內容

在這裡插入圖片描述


import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller // 交給Spring IOC 容器管理
public class RequestScopeTestController {

    @RequestMapping(value = "/testModel")
    public String testModel(Model model) {
        // 向 request 域當中綁定數據
        model.addAttribute("testRequestScope", "在SpringMVC 當中使用 Model 介面完成 request 域數據共用");
        System.out.println(model);
        System.out.println(model.getClass().getName());
        // 轉發
        return "ok";
    }
}

index 頁面超鏈接的編寫:

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試三個對象</title>
</head>
<body>
<h1>測試三個域對象</h1>
<hr>
<h2>測試 request 域對象</h2>


<a th:href="@{/testServletAPI}">測試在SpringMVC當中使用原生 Servlet API 完成 request 域的數據共用</a>
<br>
<a th:href="@{/testModel}">測試在 Spring MVC 當中使用 Model 介面完成 request 域數據共用</a>
<br>
</body>
</html>

ok 頁面獲取 request 請求域的展示

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http//www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>OK</title>
</head>
<body>
<div th:text="${testRequestScope}"></div>
</body>
</html>

啟動 Tomcat 伺服器測試結果:

在這裡插入圖片描述

4.3 第三種方式:使用Map介面 獲取到 request 請求域,同時獲取到請求域當中對應的內容

在這裡插入圖片描述

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller // 交給Spring IOC 容器管理
public class RequestScopeTestController {
    @RequestMapping(value = "/testMap")
    public String testMap(Map<String, Object> map) {

        // 向 request 域當中的存儲數據
        map.put("testRequestScope", "在Spring MVC 當中使用 Map介面完成 request 域數據共用");
        System.out.println(map);
        System.out.println(map.getClass().getName());
        // 轉發
        return "ok";
    }
}

index 頁面超鏈接的編寫:

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試三個對象</title>
</head>
<body>
<h1>測試三個域對象</h1>
<hr>
<h2>測試 request 域對象</h2>


<a th:href="@{/testServletAPI}">測試在SpringMVC當中使用原生 Servlet API 完成 request 域的數據共用</a>
<br>
<a th:href="@{/testModel}">測試在 Spring MVC 當中使用 Model 介面完成 request 域數據共用</a>
<br>
<a th:href="@{/testMap}">測試在Spring MVC 當中使用 Map 介面完成 request 域數據共用</a>
<br>
</body>
</html>

ok 頁面獲取 request 請求域的展示 保持不變

啟動 Tomcat 伺服器測試結果:

在這裡插入圖片描述

4.4 第四種方式:使用 ModelMap 類 獲取到 request 請求域,同時獲取到請求域當中對應的內容

在這裡插入圖片描述



import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller // 交給Spring IOC 容器管理
public class RequestScopeTestController {

    @RequestMapping(value = "/testModelMap")
    public String testModelMap(ModelMap modelMap) {
        // 向 request 域當中存儲數據
        modelMap.addAttribute("testRequestScope", "在Spring MVC 當中 ModelMap類完成request 域數據共用");
        System.out.println(modelMap);
        System.out.println(modelMap.getClass().getName());
        return "ok";
    }
}

index 頁面超鏈接的編寫:

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試三個對象</title>
</head>
<body>
<h1>測試三個域對象</h1>
<hr>
<h2>測試 request 域對象</h2>


<a th:href="@{/testServletAPI}">測試在SpringMVC當中使用原生 Servlet API 完成 request 域的數據共用</a>
<br>
<a th:href="@{/testModel}">測試在 Spring MVC 當中使用 Model 介面完成 request 域數據共用</a>
<br>
<a th:href="@{/testMap}">測試在Spring MVC 當中使用 Map 介面完成 request 域數據共用</a>
<br>
<a th:href="@{/testModelMap}">測試在Spring MVC當中使用 ModelMap 類完成 request 域數據共用</a>
<br>
</body>
</html>

ok 頁面獲取 request 請求域的展示 保持不變

啟動 Tomcat 伺服器測試結果:

在這裡插入圖片描述

4.5 補充:Model、Map、ModelMap的關係

可以在以上Model、Map、ModelMap的測試程式中將其輸出,看看輸出什麼:

在這裡插入圖片描述

看不出來什麼區別,從輸出結果上可以看到都是一樣的。
可以將其運行時類名輸出:

在這裡插入圖片描述

在這裡插入圖片描述

通過輸出結果可以看出,無論是Model、Map還是ModelMap,底層實例化的對象都是:BindingAwareModelMap。

可以查看 BindingAwareModelMap的繼承結構:

在這裡插入圖片描述

通過繼承結構可以看出:BindingAwareModelMap繼承了ModelMap,而ModelMap又實現了Map介面。
另外,請看以下源碼:

在這裡插入圖片描述

可以看出ModelMap又實現了Model介面。因此錶面上是採用了不同方式,底層本質上是相同的。
SpringMVC之所以提供了這些方式,目的就是方便程式員的使用,提供了多樣化的方式,可見它的重要性。

4.6 第五種方式:使用 ModelAndView 類獲取到 request 請求域,同時獲取到請求域當中對應的內容

在 Spring MVC 框架中為了更好的體現 MVC 架構模式,提供了一個類:ModelAndView。

這個類的實例封裝了 Model 和 View 。也就是說 這個類封裝業務處理之後的數據,也體現了跳轉到哪個視圖。使用它也可以完成 request 域數據共用。

使用這種方式的註意事項:

  1. 方法的返回值類型不是 String 了,而是 ModelAndView 對象
  2. ModelAndView 不是出現在方法的參數位置上了,而是在方法體中 new 出來的
  3. 需要調用 addObject() 向域中存儲數據
  4. 需要調用 setViewName() 設置視圖的名字
  5. 最後需要將 ModelAndView 作為參數,返回。

在這裡插入圖片描述


import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Controller // 交給Spring IOC 容器管理
public class RequestScopeTestController {



    @RequestMapping(value = "/testModelAndView")
    public ModelAndView testModelAndView() {
        // 創建模型視圖對象
        ModelAndView modelAndView = new ModelAndView();
        // 給模型視圖對象綁定數據
        modelAndView.addObject("testRequestScope", "在SpringMVC當中使用 ModelAndView 類完成 request 域數據共用");

        // 給模型視圖對象 綁定視圖(綁定邏輯視圖名稱)
        modelAndView.setViewName("ok");

        // 返回模型視圖對象
        return modelAndView;
    }
}

index頁面超鏈接的編寫:

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試三個對象</title>
</head>
<body>
<h1>測試三個域對象</h1>
<hr>
<h2>測試 request 域對象</h2>


<a th:href="@{/testServletAPI}">測試在SpringMVC當中使用原生 Servlet API 完成 request 域的數據共用</a>
<br>
<a th:href="@{/testModel}">測試在 Spring MVC 當中使用 Model 介面完成 request 域數據共用</a>
<br>
<a th:href="@{/testMap}">測試在Spring MVC 當中使用 Map 介面完成 request 域數據共用</a>
<br>
<a th:href="@{/testModelMap}">測試在Spring MVC當中使用 ModelMap 類完成 request 域數據共用</a>
<br>
<a th:href="@{/testModelAndView}">測試在Spring MVC當中使用 ModelAndView 類完成 request 域數據共用</a>
<br>

</body>
</html>

ok 頁面獲取 request 請求域的展示的編寫:

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http//www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>OK</title>
</head>
<body>
<div th:text="${testRequestScope}"></div>
</body>
</html>

啟動 Tomcat 伺服器測試結果:

在這裡插入圖片描述

4.7 補充:ModelAndView 源碼分析

以上我們通過了五種方式完成了request域數據共用,包括:原生 Servlet API,Model、Map、ModelMap、ModelAndView
其中後四種:Model、Map、ModelMap、ModelAndView。

這四種方式在底層DispatcherServlet調用我們的Controller之後,返回的對象都是ModelAndView,

這個可以通過源碼進行分析。

在以上四種方式中,拿Model舉例,添加斷點進行調試:

在這裡插入圖片描述

啟動伺服器,發送請求,走到斷點:

在這裡插入圖片描述

查看VM Stack信息:

在這裡插入圖片描述

查看 DispatcherServlet 的1089行,源碼如下:
在這裡插入圖片描述

可以看到這裡,無論你使用哪種方式,最終都要返回一個ModelAndView對象。

對於 mv = ha.handle(processedRequest, response, mappedHandler.getHandler()); 處理器方法來說,不管你使用的參數是 Model介面,還是Map介面,還是ModelMap類,還是ModelAndView類,最終處理器方法執行結束之前
返回的都是 ModelAndView對象,這個返回的ModelAndView對象給DispatcherServlet類了
當請求路徑不是JSP的時候,都會走前端控制器 DispatcherServlet
DispatcherServlet 中有一個核心方法 doDispatch(),這個方法用來通過請求路徑找到對應的處理器方法
然後調用處理器方法,處理器方法返回一個邏輯視圖名稱(可能也會直接返回一個ModelAndView對象)
,返回給DispatcherServlet

提醒:大家可以通過以下斷點調試方式,採用一級一級返回,最終可以看到都會返回ModelAndView對象。

在這裡插入圖片描述

5. Spring MVC 獲取 session 會話域對象的二種方式

在SpringMVC中使用session域共用數據,實現方式有多種,其中比較常見的兩種方式:

  1. 使用原生Servlet API
  2. 使用SessionAttributes註解

5.1 第一種方式:使用原生Servlet API 獲取到 session 會話域,同時獲取到 session 會話域當中的信息

使用原生Servlet API ,就是將 HttpSession 作為方法的參數形式,Spring MVC 會自動獲取到 Tomcat 伺服器當中的 HttpSession 對象,賦值到這個方法的對應的 HttpSession 參數上。

創建:SessionScopeTestController 類

在這裡插入圖片描述


import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;



@Controller // 交給 Spring IOC 容器管理
public class SessionScopeTestController {


    @RequestMapping("/testSessionServletAPI")
    public String testServletAPI(HttpSession session) {
        // 處理核心業務...
        //將數據存儲到 Session中
        session.setAttribute("testSessionScope","在Spring MVC 當中使用原生 Servlet API 完成 session 域數據共用");
        // 返回邏輯視圖(這是一個轉發的行為)
        return "ok";
    }
}

index 頁面超鏈接的編寫:
在這裡插入圖片描述

ok 頁面獲取 request 請求域的展示的編寫

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http//www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>OK</title>
</head>
<body>
<div th:text="${session.testSessionScope}"></div>
</body>
</html>

啟動 Tomcat 伺服器測試結果:
在這裡插入圖片描述

5.2 第二種方式:使用 @SessionAttributes 註解 獲取到 session 會話域,同時獲取到 session 會話域當中的信息

使用 @SessionAttributes 註解標註 Controller:

在這裡插入圖片描述

@SessionAttributes(value = {"x","y","testSessionScope"}) // 標註 x 和 y 都是存放到 session 域中,而不是 request域

**註意:@SessionAttributes 註解使用在Controller類上。標註了當 key是 x 或者 y 時,該(x 或 y)的數據將被存儲到會話 session域當中中。而如果沒有 SessionAttributes註解,預設存儲到 request域中。 **
在這裡插入圖片描述


import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;


@SessionAttributes(value = {"x","y","testSessionScope"}) // 標註 x 和 y 都是存放到 session 域中,而不是 request域
@Controller // 交給 Spring IOC 容器管理
public class SessionScopeTestController {



    @RequestMapping(value = "/testSessionAttributes")
    public String testSessionAttributes(ModelMap modelMap) {
        // 處理業務
        // 將數據存儲到 Session域當中
        modelMap.addAttribute("testSessionScope","在Spring MVC 當中使用@SessionAttributes 註解完成 session 域數據共用");
        modelMap.addAttribute("x","李華");
        modelMap.addAttribute("y","小紅");
        return "ok";
    }
}

index 頁面超鏈接的編寫:

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試三個對象</title>
</head>
<body>
<h1>測試三個域對象</h1>
<hr>



<h2>測試Session域對象</h2>
<a th:href="@{/testSessionAttributes}">測試在Spring MVC 當中使用 @SessionAttributes 註解完成 session域數據共用</a>
<br>

</body>
</html>

ok 頁面獲取 request 請求域的展示的編寫:

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http//www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>OK</title>
</head>
<body>
<div th:text="${session.testSessionScope}"></div>
<div th:text="${session.x}"></div>
<div th:text="${session.y}"></div>
</body>
</html>

啟動 Tomcat 伺服器測試結果:

在這裡插入圖片描述

6. Spring MVC 獲取 application 應用域對象的方式

在SpringMVC實現application域數據共用,最常見的方案就是直接使用Servlet API了:

這個 application 域使用較少,如果使用的話,一般是採用 ServletAPI的方式使用

創建:ApplicationScopeTestController 類

將 HttpServletRequest 作為參數,定義到方法上,Spring MVC 框架會自動從 Tomcat 伺服器當中獲取到這個 HttpServletRequest 對象的值,然後,傳遞給這個方法的 HttpServletRequest 參數值上,完成賦值。
在這裡插入圖片描述

package com.rainbowsea.springmvc.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller // 交給 Spring IOC 容器管理
public class ApplicationScopeTestController {


    @RequestMapping("/testApplicationScope")
    public String testApplicationScope(HttpServletRequest request) {
        // 將數據存儲到application域當中
        // 獲取application對象,其實就是獲取 ServletContext對象
        // 怎麼獲取 ServletContext對象/通過 request,通過 session都可以用
        ServletContext application = request.getServletContext();
        application.setAttribute("testApplicationScope", "在Spring MVC 中使用 Servlet API中實現application域共用");
        return "ok";
    }
}

index 頁面超鏈接的編寫:

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>測試三個對象</title>
</head>
<body>
<h1>測試三個域對象</h1>
<hr>



<h2>測試Application應用域對象</h2>
<a th:href="@{/testApplicationScope}">測試在Spring MVC 當中使用 Servlet API 實現application域數據共用</a>
<br>

</body>
</html>

ok 頁面獲取 request 請求域的展示的編寫

在這裡插入圖片描述

啟動 Tomcat 伺服器測試結果:
在這裡插入圖片描述

7. 總結:

  1. 三個域:request 請求域,session 會話域,application 應用域

  2. 三者域的使用,從最小範圍的域,來判斷使用,可以用範圍更小的域,就用範圍更小的域來解決問題,傳數據資源。如果域的範圍不夠,就一點的擴大。

  3. 在SpringMVC中,在request域中共用數據有以下五種方式:

    1. 使用原生Servlet API方式。
    2. 使用Model介面。
    3. 使用Map介面。
    4. 使用ModelMap類。
    5. 使用ModelAndView類。
  4. 在SpringMVC中使用session域共用數據,實現方式有多種,其中比較常見的兩種方式:

    1. 使用原生Servlet API
    2. 使用SessionAttributes註解
  5. Spring MVC 獲取 application 應用域對象的方式

8. 最後:

“在這個最後的篇章中,我要表達我對每一位讀者的感激之情。你們的關註和回覆是我創作的動力源泉,我從你們身上吸取了無盡的靈感與勇氣。我會將你們的鼓勵留在心底,繼續在其他的領域奮鬥。感謝你們,我們總會在某個時刻再次相遇。”

在這裡插入圖片描述


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 正文 昨天睡了一天覺,今天看了一天《三體》電視劇。真是墮落到沒邊了呢(笑。本來想寫代碼完成年度計劃,或者多寫幾篇文章,但實在不想寫,也不想動筆。 感覺這個周末什麼都沒做呢,休息倒是休息好了。 今天 30 號,也不知道靈平安到學校沒有。 本有一些想寫的東西,但懶得動筆了。 成功日記: 《西游記》看到了 ...
  • 前言 之前做了微信登錄,所以總結一下微信授權登錄並獲取用戶信息這個功能的開發流程。 配置 1.首先得在微信公眾平臺申請一下微信小程式賬號並獲取到小程式的AppID和AppSecret https://mp.weixin.qq.com/cgi-bin/loginpage?url=%2Fwxamp%2F ...
  • 本文揭秘了Java Chassis 3流式響應的使用場景和技術背景,它基於伺服器事件推送和響應式流(reactive streams)標準,提供了非常簡潔的流式響應開發能力,簡化人工智慧應用開發體驗。 ...
  • 大家好,我是碼農先森。 說到 HTTP 請求工具想必對我們做 Web 開發的程式員都不陌生,只要涉及到網路請求都必須使用。對於我們 PHP 程式員來說,最熟悉不過的就是 CURL 擴展,只要安裝的這個擴展便可隨意發起 HTTP 請求。 但在 PHP 語言中還有一個很好用的 Composer 包「gu ...
  • 主題介紹 WaterDrop 是 水滴 的意思,其實並沒有什麼特殊含義,只是因為每一次項目取名都絞盡腦汁,太麻煩了,於是就想著效法一些大佬,乾脆取名隨性一點。例如,Java 語言因作者經常在辦公室喝 Java 咖啡而得名,MySQL和MariaDB的作者是同一人,命名分別是他兩個女兒的名字(看樣子作 ...
  • 集合工廠 List<String> friends = Arrays.asList("Raphael", "Olivia"); friends.set(0, "Richard"); friends.add("Thibaut"); ← 拋出一個UnsupportedModificationExcept ...
  • 1、概述 Spring MVC是Spring Framework的Web開發部分,是基於Java實現MVC的輕量級Web框架。 官方文檔:https://docs.spring.io/spring-framework/docs/4.3.24.RELEASE/spring-framework-refe ...
  • 後兩次PTA總結 首先來看看第七次: 第七次相比於之前,添加了互斥開關元器件而且引入了並聯互串等等接法,按照我之前的設計,作出改動不算太難,我之前的遞歸已經可以按照順序儲存所以的元器件到一起去了,主要還是歸功於將串並聯電路繼承自元器件的方式十分有效,這樣就能夠將串並聯電路當作元器件一起處理,再按照遞 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...