Java Spring MVC -01

SpringMVC 是一種基于 ?的實現 MVC 設計模式的請求驅動類型的輕量級 Web 框架,屬于 Spring FrameWork 的后續產品,已經融合在 Spring Web Flow 中。

First:SpringMVC-01-SpringMVC 概述

SpringMVC 是 Spring 框架的一個模塊,用于構建 Web 應用程序。它遵循 MVC (Model-View-Controller) 架構模式,將請求處理、業務邏輯和視圖展示分離,使代碼結構清晰,易于維護和測試。

SpringMVC 的主要特點:

-輕量級,非侵入式

-強大的請求映射機制

-支持多種視圖技術

-強大的異常處理機制

-支持文件上傳

-國際化和本地化支持

-支持 RESTful 風格的 URL

SpringMVC-02-SpringMVC 入門案例

下面是一個簡單的 SpringMVC 入門案例,展示了如何創建一個基本的 Web 應用。

1. 添加 Maven 依賴

這些依賴是構建 SpringMVC 應用的基礎:

xml:

<dependencies>

????<!-- Spring MVC核心庫 -->

????<dependency>

????????<groupId>org.springframework</groupId>

????????<artifactId>spring-webmvc</artifactId>

????????<version>5.3.18</version>

????</dependency>

????

????<!-- Servlet API (由容器提供,無需打包) -->

????<dependency>

????????<groupId>x.servlet</groupId>

????????<artifactId>x.servlet-api</artifactId>

????????<version>4.0.1</version>

????????<scope>provided</scope>

????</dependency>

????

????<!-- JSP支持 (用于視圖渲染) -->

????<dependency>

????????<groupId>x.servlet.jsp</groupId>

????????<artifactId>x.servlet.jsp-api</artifactId>

????????<version>2.3.3</version>

????????<scope>provided</scope>

</dependency>

</dependencies>

關鍵依賴說明:

spring-webmvc:SpringMVC 框架的核心庫

x.servlet-api:Servlet 容器接口

x.servlet.jsp-api:JSP 頁面支持

2. Servlet 初始化類(AppInitializer)

這個類替代了傳統的 web.xml 配置,用于注冊 DispatcherServlet

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

????@Override

????protected Class<?>[] getRootConfigClasses() {

????????return null; // 根應用上下文配置(通常包含服務層和數據訪問層)

????}

????@Override

????protected Class<?>[] getServletConfigClasses() {

????????return new Class<?>[] { WebConfig.class }; // Web層配置

????}

????@Override

????protected String[] getServletMappings() {

????????return new String[] { "/" }; // 映射所有請求到DispatcherServlet

}

}

核心作用:

自動注冊 Spring MVC 的前端控制器DispatcherServlet

指定配置類位置

映射請求路徑

3. Spring 配置類(WebConfig)

配置 SpringMVC 的核心組件:

@Configuration

@EnableWebMvc // 啟用Spring MVC注解支持

@ComponentScan(basePackages = "com.example.controller") // 掃描控制器

public class WebConfig {

????@Bean

????public ViewResolver viewResolver() {

????????InternalResourceViewResolver resolver = new InternalResourceViewResolver();

????????resolver.setPrefix("/WEB-INF/views/"); // JSP文件位置

????????resolver.setSuffix(".jsp"); // 文件后綴

????????return resolver;

}

}

關鍵配置項:

@EnableWebMvc:啟用 Spring MVC 注解驅動

ComponentScan:掃描@Controller注解的類

ViewResolver:配置視圖解析器,將邏輯視圖名映射到物理 JSP 文件

4. 控制器(HelloController)

處理 HTTP 請求并返回視圖:

@Controller

@RequestMapping("/hello")

public class HelloController {

????@RequestMapping(method = RequestMethod.GET)

????public String sayHello(Model model) {

????????model.addAttribute("message", "Hello Spring MVC!");

????????return "hello"; // 邏輯視圖名

}

}

核心注解:

@Controller:聲明這是一個 Spring MVC 控制器

@RequestMapping:映射請求路徑和 HTTP 方法

Model:用于傳遞數據到視圖

5. JSP 視圖(hello.jsp)

渲染最終響應頁面:

jsp

<!DOCTYPE html>

<html>

<head>

????<title>Hello Spring MVC</title>

</head>

<body>

????<h1>${message}</h1> <!-- 接收控制器傳遞的數據 -->

</body>

</html>

關鍵技術點:

EL 表達式 (${message}):用于獲取模型數據

視圖位置:/WEB-INF/views/hello.jsp(由 ViewResolver 配置決定)

入門案例工作流程解析

當訪問http://localhost:8080/hello時:

請求到達DispatcherServlet(由 AppInitializer 注冊)

DispatcherServlet 通過 HandlerMapping 找到對應的HelloController

執行sayHello()方法,將數據存入 Model

返回邏輯視圖名 "hello"

ViewResolver 將 "hello" 解析為 / WEB-INF/views/hello.jsp

JSP 頁面渲染并返回響應

SpringMVC-03 - 入門案例工作流程解析

SpringMVC 的工作流程可以概括為以下幾個步驟:

客戶端發送請求到 DispatcherServlet

DispatcherServlet 接收請求并查詢 HandlerMapping?找到處理該請求的 Controller

DispatcherServlet 調用 HandlerAdapter 來執行 Controller

Controller 處理請求并返回一個 ModelAndView 對象給 HandlerAdapter

HandlerAdapter 將 ModelAndView 返回給 DispatcherServlet

DispatcherServlet 查詢 ViewResolver 找到與 ModelAndView 中邏輯視圖名對應的實際視圖

DispatcherServlet 將模型數據傳遞給視圖

視圖渲染結果返回給客戶端

SpringMVC-04-bean 加載控

在 SpringMVC 中,有兩種類型的 ApplicationContext:

root 上下文 (Root ApplicationContext):包含應用的業務邏輯、數據訪問等 Bean

Servlet 上下文 (Servlet ApplicationContext):包含控制器、視圖解析器等 Web 相關 Bean

可以通過配置來控制哪些 Bean 被加載到哪個上下文:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

????@Override

????protected Class<?>[] getRootConfigClasses() {

????????return new Class<?>[] { RootConfig.class };

????}

????@Override

????protected Class<?>[] getServletConfigClasses() {

????????return new Class<?>[] { WebConfig.class };

????}

????@Override

????protected String[] getServletMappings() {

????????return new String[] { "/" };

}

}

@Configuration

@ComponentScan(basePackages = "com.example.service, com.example.repository")

public class RootConfig {

// 根上下文配置

}

@Configuration

@EnableWebMvc

@ComponentScan(basePackages = "com.example.controller")

public class WebConfig {

// Servlet上下文配置

}

SpringMVC-05-PostMan 工具介紹

Postman 是一個用于測試 API 的工具,它可以發送各種 HTTP 請求 (GET、POST、PUT、DELETE 等),設置請求頭、請求參數、請求體等,并查看響應結果。

使用 Postman 測試 SpringMVC API 的步驟:

打開 Postman,創建一個新的請求

選擇請求方法 (GET、POST 等)

輸入請求 URL

設置請求頭 (如 Content-Type)

設置請求參數或請求體

點擊發送按鈕查看響應結果

SpringMVC-06 - 設置請求映射路徑

在 SpringMVC 中,可以使用 @RequestMapping 注解來設置請求映射路徑。該注解可以應用于類和方法上。

@Controller

@RequestMapping("/products")

public class ProductController {

????// 處理GET請求 /products

????@RequestMapping(method = RequestMethod.GET)

????public String listProducts(Model model) {

????????// 獲取產品列表

????????return "products/list";

????}

????// 處理GET請求 /products/{id}

????@RequestMapping(value = "/{id}", method = RequestMethod.GET)

//@GetMappeing (value = "{id}")

????public String getProduct(@PathVariable("id") Long id, Model model) {

????????// 獲取單個產品

????????return "products/detail";

????}

????// 處理POST請求 /products

????@RequestMapping(method = RequestMethod.POST)

????public String addProduct(@ModelAttribute Product product) {

????????// 添加產品

????????return "redirect:/products";

}

}

SpringMVC-07-get 請求與 post 請求發送普通參數

一、GET 請求參數處理

1. 請求結構與參數傳遞

GET 請求將參數附加在 URL 的查詢字符串中,格式為?參數名1=值1&參數名2=值2。例如:

http://localhost:8080/search?keyword=手機

瀏覽器發送的完整 HTTP 請求示例:

http:

GET /search?keyword=%E6%89%8B%E6%9C%BA HTTP/1.1

Host: localhost:8080User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)

Accept: text/html,application/xhtml+xml,application/xml

Accept-Language: zh-CN,zh;q=0.9,en;q=0.8

Connection: keep-alive

2. @RequestParam 注解詳解

@Controller

@RequestMapping("/search")

public class SearchController {

????// 基礎用法

????@GetMapping

????public String search(@RequestParam("keyword") String keyword, Model model) {

????????// 處理搜索邏輯

????????List<Product> results = productService.search(keyword);

????????model.addAttribute("results", results);

????????return "search/results";

????}

????// 可選參數與默認值

????@GetMapping("/advanced")

????public String advancedSearch(

????????@RequestParam(value = "keyword", required = false) String keyword, ?// 可選參數

????????@RequestParam(value = "category", defaultValue = "all") String category, ?// 默認值

????????@RequestParam(value = "page", defaultValue = "1") int page,

????????@RequestParam(value = "size", defaultValue = "10") int size

????) {

????????// 處理高級搜索

????????return "search/advanced";

????}

????// 綁定多個同名參數到List

????@GetMapping("/filter")

????public String filterProducts(@RequestParam("category") List<String> categories) {

????????// URL: /filter?category=手機&category=電腦

????????return "products/filter";

????}}

3. 前端表單示例(GET 請求)

html

預覽

<form action="/search" method="get">

????<input type="text" name="keyword" placeholder="搜索關鍵詞">

????<select name="category">

????????<option value="all">全部</option>

????????<option value="phone">手機</option>

????????<option value="computer">電腦</option>

????</select>

<button type="submit">搜索</button>

</form>

二、POST 請求參數處理

1. 請求結構與參數傳遞

POST 請求將參數封裝在請求體中,需要指定Content-Type頭。常見的Content-Type有:

application/x-www-form-urlencoded(默認)

multipart/form-data(文件上傳)

application/json(JSON 數據)

瀏覽器發送的完整 HTTP 請求示例:

http:

POST /user/register HTTP/1.1Host: localhost:8080

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)

Content-Type: application/x-www-form-urlencoded

Content-Length: 40

username=test&password=123456&email=test%40example.com

2. @RequestParam 處理簡單參數

@Controller

@RequestMapping("/user")

public class UserController {

????@PostMapping("/login")

????public String login(

????????@RequestParam("username") String username,

????????@RequestParam("password") String password,

????????Model model

????) {

????????User user = userService.validateUser(username, password);

????????if (user != null) {

????????????return?"redirect:/home";

????????} else {

????????????model.addAttribute("error", "用戶名或密碼錯誤");

????????????return "login";

????????}

}

}

3. @ModelAttribute 處理對象參數

// User類public class User {

????private String username;

????private String password;

????private String email;

????private Integer age;

// getters/setters

}

@Controller

@RequestMapping("/user")

public class UserController {

????@PostMapping("/register")

????public String register(@ModelAttribute User user) {//表單->User對象

????????// 自動將表單參數綁定到User對象

????????userService.register(user);

????????return "redirect:/user/login";

}

}

4. 前端表單示例(POST 請求)

html

<form action="/user/register" method="post">

????用戶名: <input type="text" name="username"><br>

????密碼: <input type="password" name="password"><br>

????郵箱: <input type="email" name="email"><br>

????年齡: <input type="number" name="age"><br>

<input type="submit" value="注冊">

</form>

SpringMVC-08-5 種類型參數傳遞

SpringMVC 支持多種方式的參數傳遞:

路徑變量 (Path Variable)

@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)

public String getUser(@PathVariable("id") Long id, Model model) {

// 處理邏輯

}

請求參數 (Request Parameter)

@RequestMapping(value = "/search", method = RequestMethod.GET)

public String search(@RequestParam("keyword") String keyword, Model model) {

// 處理邏輯

}

請求頭 (Request Header)

@RequestMapping(value = "/download", method = RequestMethod.GET)

public ResponseEntity<byte[]> download(@RequestHeader("User-Agent") String userAgent) {

// 處理邏輯

}

Cookie 值

@RequestMapping(value = "/profile", method = RequestMethod.GET)

public String profile(@CookieValue("JSESSIONID") String sessionId, Model model) {

????// 處理邏輯}

請求體 (用于 POST/PUT 請求)

@RequestMapping(value = "/users", method = RequestMethod.POST)

public ResponseEntity<User> createUser(@RequestBody User user) {

// 處理邏輯

}

SpringMVC-09-json 數據傳遞參數

在 RESTful API 中,通常使用 JSON 格式傳遞數據。可以使用 @RequestBody 和 @ResponseBody 注解來處理 JSON 數據。

首先需要添加 Jackson 依賴:

xml

<dependency>

????<groupId>com.fasterxml.jackson.core</groupId>

????<artifactId>jackson-databind</artifactId>

<version>2.13.3</version>

</dependency>

控制器示例:

@RestController

@RequestMapping("/api/users")

public class UserRestController {

????@PostMapping

????public User createUser(@RequestBody User user) {//JSON->對象

????????// 創建用戶

????????return userService.save(user);

????}

????@GetMapping("/{id}")

????public User getUser(@PathVariable Long id) {

????????// 獲取用戶

????????return userService.findById(id);

}

}

SpringMVC-10 - 日期型參數傳遞

SpringMVC 默認情況下可能無法正確解析日期參數,需要進行額外配置。

使用 @DateTimeFormat 注解:

@RequestMapping(value = "/events", method = RequestMethod.GET)

public String getEvents(@RequestParam("date")

@DateTimeFormat(pattern = "yyyy-MM-dd") //格式

LocalDate date, Model model) {

// 處理邏輯

}

全局日期格式化配置:

@Configuration

public class WebConfig implements WebMvcConfigurer {

????@Override

????public void addFormatters(FormatterRegistry registry) {

????????DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();

????????registrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

????????registrar.setDateTimeFormatter(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

????????registrar.registerFormatters(registry);

}

}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/82859.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/82859.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/82859.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Spring MessageSource 詳解:如何在國際化消息中傳遞參數

在開發多語言應用程序時,Spring 的 MessageSource 是處理國際化(i18n)文本的核心組件。它允許我們根據用戶的 Locale (區域設置) 顯示不同的消息。然而,很多時候我們的消息并不是靜態的,而是需要包含動態數據,比如用戶名、數量、文件名等。這時,我們就需要在獲取國際化消…

Datawhale 5月llm-universe 第1次筆記

課程地址&#xff1a;GitHub - datawhalechina/llm-universe: 本項目是一個面向小白開發者的大模型應用開發教程&#xff0c;在線閱讀地址&#xff1a;https://datawhalechina.github.io/llm-universe/ 難點&#xff1a;配置conda環境變量 我用的vscode github方法 目錄 重要…

基于Java的家政服務平臺設計與實現(代碼+數據庫+LW)

摘 要 現代經濟快節奏發展以及不斷完善升級的信息化技術&#xff0c;讓傳統數據信息的管理升級為軟件存儲&#xff0c;歸納&#xff0c;集中處理數據信息的管理方式。本家政服務平臺就是在這樣的大環境下誕生&#xff0c;其可以幫助管理者在短時間內處理完畢龐大的數據信息&a…

Android中LinearLayout線性布局使用詳解

Android中LinearLayout線性布局使用詳解 LinearLayout&#xff08;線性布局&#xff09;是Android中最基礎、最常用的布局之一&#xff0c;它按照水平或垂直方向依次排列子視圖。 基本特性 方向性&#xff1a;可以設置為水平(horizontal)或垂直(vertical)排列權重&#xff1…

LVS+keepalived實戰案例

目錄 部署LVS 安裝軟件 創建VIP 創建保存規則文件 給RS添加規則 驗證規則 部署RS端 安裝軟件 頁面內容 添加VIP 配置系統ARP 傳輸到rs-2 客戶端測試 查看規則文件 實現keepalived 編輯配置文件 傳輸文件給backup 修改backup的配置文件 開啟keepalived服務 …

(C語言)超市管理系統(測試版)(指針)(數據結構)(二進制文件讀寫)

目錄 前言&#xff1a; 源代碼&#xff1a; product.h product.c fileio.h fileio.c main.c 代碼解析&#xff1a; fileio模塊&#xff08;文件&#xff08;二進制&#xff09;&#xff09; 寫文件&#xff08;保存&#xff09; 函數功能 代碼逐行解析 關鍵知識點 讀文…

ubuntu----100,常用命令2

目錄 文件與目錄管理系統信息與管理用戶與權限管理網絡配置與管理軟件包管理打包與壓縮系統服務與任務調度硬件信息查看系統操作高級工具開發相關其他實用命令 在 Ubuntu 系統中&#xff0c;掌握常用命令可以大幅提升操作效率。以下是一些常用的命令&#xff0c;涵蓋了文件管理…

WiFi密碼查看器打開軟件自動獲取數據

相信有很大一部分人都不知道怎么看已經連過的WiFi密碼。 你還在手動查詢自己的電腦連接過得WiFi密碼嗎&#xff1f; —————【下 載 地 址】——————— 【本章單下載】&#xff1a;https://drive.uc.cn/s/dbbedf933dad4 【百款黑科技】&#xff1a;https://ucnygalh6…

開目新一代MOM:AI賦能高端制造的破局之道

導讀 INTRODUCTION 在高端制造業智能化轉型的深水區&#xff0c;企業正面臨著個性化定制、多工藝場景、動態生產需求的敏捷響應以及傳統MES柔性不足的考驗……在此背景下&#xff0c;武漢開目信息技術股份有限公司&#xff08;簡稱“開目軟件”&#xff09;正式發布新一代開目…

Android開發-視圖基礎

在Android應用開發中&#xff0c;視圖&#xff08;View&#xff09;是構建用戶界面的基本元素。無論是按鈕、文本框還是復雜的自定義控件&#xff0c;它們都是基于View類或其子類實現的。掌握視圖的基礎知識對于創建功能強大且美觀的應用至關重要。本文將深入探討Android中的視…

無人機信號線被電磁干擾導致停機

問題描述&#xff1a; 無人機飛控和電調之間使用PWM信號控制時候&#xff0c;無人機可以正常起飛&#xff0c;但是在空中懸停的時候會出現某一個電機停機&#xff0c;經排查電調沒有啟動過流過壓等保護&#xff0c;定位到電調和飛控之間的信號線被干擾問題。 信號線被干擾&am…

VSCode設置SSH免密登錄

引言 2025年05月13日20:21:14 原來一直用的PyCharn來完成代碼在遠程服務器上的運行&#xff0c;但是PyCharm時不時同步代碼會有問題。因此&#xff0c;嘗試用VSCode來完成代碼SSH遠程運行。由于VSCode每次進行SSH連接的時候都要手動輸入密碼&#xff0c;為了解決這個問題在本…

硬密封保溫 V 型球閥:恒溫工況下復雜介質控制的性價比之選-耀圣

硬密封保溫 V 型球閥&#xff1a;恒溫工況下復雜介質控制的性價比之選 在瀝青儲運、化學原料加工、食品油脂輸送等工業領域&#xff0c;帶顆粒高粘度介質與料漿的恒溫輸送一直是生產的關鍵環節。普通閥門在應對此類介質時&#xff0c;常因溫度流失導致介質凝結堵塞、密封失效&…

最終一致性和強一致性

最終一致性和強一致性是分布式系統中兩種不同的數據一致性模型&#xff0c;它們在數據同步的方式和適用場景上有顯著區別&#xff1a; 1. 強一致性&#xff08;Strong Consistency&#xff09; 定義&#xff1a;所有節點&#xff08;副本&#xff09;的數據在任何時刻都保持一…

基于單應性矩陣變換的圖像拼接融合

單應性矩陣變換 單應性矩陣是一個 3x3 的可逆矩陣&#xff0c;它描述了兩個平面之間的投影變換關系。在圖像領域&#xff0c;單應性矩陣可以將一幅圖像中的點映射到另一幅圖像中的對應點&#xff0c;前提是這兩幅圖像是從不同視角拍攝的同一平面場景。 常見的應用場景&#x…

如何同步虛擬機文件夾

以下是一些常見的同步虛擬機文件夾的方法&#xff1a; 使用共享文件夾&#xff08;以VMware和VirtualBox為例&#xff09; - VMware&#xff1a;打開虛擬機&#xff0c;選擇“虛擬機”->“設置”&#xff0c;在“選項”中選擇“共享文件夾”&#xff0c;點擊“添加”選擇…

前端流行框架Vue3教程:15. 組件事件

組件事件 在組件的模板表達式中&#xff0c;可以直接使用$emit方法觸發自定義事件 觸發自定義事件的目的是組件之間傳遞數據 我們來創建2個組件。父組件&#xff1a; ComponentEvent.vue,子組件&#xff1a;Child.vue Child.vue <script> export default {// 子組件通…

Python+1688 API 開發教程:實現商品實時數據采集的完整接入方案

在電商行業競爭日益激烈的當下&#xff0c;掌握商品實時數據是企業制定精準營銷策略、優化供應鏈管理的關鍵。1688 作為國內重要的 B2B 電商平臺&#xff0c;其開放平臺提供了豐富的 API 接口&#xff0c;借助 Python 強大的數據處理能力&#xff0c;我們能夠高效實現商品數據的…

聊一聊Electron中Chromium多進程架構

Chromium 多進程架構概述 Chromium 的多進程架構是其核心設計之一&#xff0c;旨在提高瀏覽器的穩定性、安全性和性能。Chromium 將不同的功能模塊分配到獨立的進程中&#xff0c;每個進程相互隔離&#xff0c;避免了單進程架構中一個模塊的崩潰導致整個瀏覽器崩潰的問題。 在…

CodeBuddy 中國版 Cursor 實戰:Redis+MySQL雙引擎驅動〈王者榮耀〉戰區排行榜

文章目錄 一、引言二、系統架構設計2.1、整體架構概覽2.2、數據庫設計2.3、后端服務設計 三、實戰&#xff1a;從零構建排行榜3.1、開發環境準備3.2、用戶與戰區 數據管理3.2.1、MySQL 數據庫表創建3.2.2、實現用戶和戰區數據的 CURD 操作 3.3、實時分數更新3.4、排行榜查詢3.5…