Java SpringMVC自學(xué)自講
SpringMVC
參考博客
MVC
SpringMVC是基于MVC設(shè)計(jì)模式來實(shí)現(xiàn)的,而MVC對應(yīng)model,view,controller層
大家暑期寫項(xiàng)目的時(shí)候就是基于這個(gè)架構(gòu)來設(shè)計(jì)的,就我理解來看,我們的項(xiàng)目結(jié)構(gòu)應(yīng)該是更細(xì)化地分了一下model層,分成了dao,entity,filter,service,util層,然后再加上接收前端請求的controller層。view層由前端實(shí)現(xiàn)。
SpringMVC
概述
Spring MVC是Spring Framework的一部分,是基于Java實(shí)現(xiàn)MVC的輕量級(jí)Web框架。
可查看全英文官方文檔
SpringMVC優(yōu)點(diǎn)
1.輕量級(jí),簡單易學(xué)
2.高效 , 基于請求響應(yīng)的MVC框架
3.與Spring兼容性好,無縫結(jié)合
4.約定優(yōu)于配置
5.功能強(qiáng)大:RESTful、數(shù)據(jù)驗(yàn)證、格式化、本地化、主題等
6.簡潔靈活
7.用的人多 , 使用的公司多
創(chuàng)建maven工程
1.先建立如下的web項(xiàng)目結(jié)構(gòu),之前講maven的時(shí)候有講過兩種方法
2.添加依賴
<dependencies> <!-- SpringMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.1</version> </dependency> <!-- 日志 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <!-- ServletAPI --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- Spring5和Thymeleaf整合包 --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> </dependency> </dependencies>
配置web.xml
注冊SpringMVC的前端控制器DispatcherServlet。
1.默認(rèn)配置方式就是我們之前用的那種。
<servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
2.擴(kuò)展配置方式(用的多)
<!-- 配置SpringMVC的前端控制器,對瀏覽器發(fā)送的請求統(tǒng)一進(jìn)行處理 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 通過初始化參數(shù)指定SpringMVC配置文件的位置和名稱 --> <init-param> <!-- contextConfigLocation為固定值 --> <param-name>contextConfigLocation</param-name> <!-- 使用classpath:表示從類路徑查找配置文件,例如maven工程中的src/main/resources --> <param-value>classpath:springMVC.xml</param-value> </init-param> <!-- 作為框架的核心組件,在啟動(dòng)過程中有大量的初始化操作要做 而這些操作放在第一次請求時(shí)才執(zhí)行會(huì)嚴(yán)重影響訪問速度 因此需要通過此標(biāo)簽將啟動(dòng)控制DispatcherServlet的初始化時(shí)間提前到服務(wù)器啟動(dòng)時(shí) --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <!-- 設(shè)置springMVC的核心控制器所能處理的請求的請求路徑 /所匹配的請求可以是/login或.html或.js或.css方式的請求路徑 但是/不能匹配.jsp請求路徑的請求 --> <url-pattern>/</url-pattern> </servlet-mapping>
創(chuàng)建請求控制器
前端控制器對瀏覽器發(fā)送的請求進(jìn)行了統(tǒng)一的處理,但是具體的請求有不同的處理過程,因此需要?jiǎng)?chuàng)建處理具體請求的類,即請求控制器。
請求控制器中每一個(gè)處理請求的方法成為控制器方法。
因?yàn)镾pringMVC的控制器由一個(gè)POJO(普通的Java類)擔(dān)任,因此需要通過@Controller注解將其標(biāo)識(shí)為一個(gè)控制層組件,交給Spring的IOC容器管理,此時(shí)SpringMVC才能夠識(shí)別控制器的存在。
@Controller public class HelloController { }
創(chuàng)建springMVC的配置文件
<?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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 自動(dòng)掃描包 --> <context:component-scan base-package="com.blumson.mvc.controller"></context:component-scan> <!-- 配置Thymeleaf視圖解析器 --> <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="order" value="1"/> <property name="characterEncoding" value="UTF-8"/> <property name="templateEngine"> <bean class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver"> <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <!-- 視圖前綴 --> <property name="prefix" value="/WEB-INF/templates/"/> <!-- 視圖后綴 --> <property name="suffix" value=".jsp"/> <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8" /> </bean> </property> </bean> </property> </bean> <!-- 處理靜態(tài)資源,例如html、js、css、jpg 若只設(shè)置該標(biāo)簽,則只能訪問靜態(tài)資源,其他請求則無法訪問 此時(shí)必須設(shè)置<mvc:annotation-driven/>解決問題 --> <mvc:default-servlet-handler/> <!-- 開啟mvc注解驅(qū)動(dòng) --> <mvc:annotation-driven> <mvc:message-converters> <!-- 處理響應(yīng)中文內(nèi)容亂碼 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="defaultCharset" value="UTF-8" /> <property name="supportedMediaTypes"> <list> <value>text/html</value> <value>application/json</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> </beans>
測試HelloWorld
1.在請求控制器中創(chuàng)建處理請求的方法
// @RequestMapping注解:處理請求和控制器方法之間的映射關(guān)系 // @RequestMapping注解的value屬性可以通過請求地址匹配請求,/表示的當(dāng)前工程的上下文路徑 // localhost:8080/springMVC/ @RequestMapping("/") public String index() { //設(shè)置視圖名稱 return "index"; }
2.index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>first</h1> </body> </html>
3.再配置tomcat服務(wù)器,啟動(dòng)后如圖所示。
如果要跳轉(zhuǎn)別的接口(頁面)的話,可在index.java中添加超鏈接,鏈接到target.html。然后在請求控制器中創(chuàng)建處理請求的方法。
@RequestMapping("/target") public String target(){ return "target"; }
總結(jié)
瀏覽器發(fā)送請求,若請求地址符合前端控制器的url-pattern,該請求就會(huì)被前端控制器DispatcherServlet處理。前端控制器會(huì)讀取SpringMVC的核心配置文件,通過掃描組件找到控制器,將請求地址和控制器中@RequestMapping注解的value屬性值進(jìn)行匹配,若匹配成功,該注解所標(biāo)識(shí)的控制器方法就是處理請求的方法。
處理請求的方法需要返回一個(gè)字符串類型的視圖名稱,該視圖名稱會(huì)被視圖解析器解析,加上前綴和后綴組成視圖的路徑,通過Thymeleaf對視圖進(jìn)行渲染,最終轉(zhuǎn)發(fā)到視圖所對應(yīng)頁面。
@RequestMapping注解
作用就是將請求和處理請求的控制器方法關(guān)聯(lián)起來,建立映射關(guān)系。
SpringMVC 接收到指定的請求,就會(huì)來找到在映射關(guān)系中對應(yīng)的控制器方法來處理這個(gè)請求。
@RequestMapping標(biāo)識(shí)一個(gè)類:設(shè)置映射請求的請求路徑的初始信息
@RequestMapping標(biāo)識(shí)一個(gè)方法:設(shè)置映射請求的請求路徑的具體信息
比如/user/login接口,可在類外@RequestMapping("/user"),在具體某個(gè)對應(yīng)方法外@RequestMapping("/login")
@RequestMapping注解的value屬性是一個(gè)字符串類型的數(shù)組,表示該請求映射能夠匹配多個(gè)請求地址所對應(yīng)的請求
一個(gè)方法可處理多個(gè)接口的請求
@RequestMapping( value = {"/testRequestMapping", "/test"} ) public String testRequestMapping(){ return "success"; }
@RequestMapping注解的method屬性是一個(gè)RequestMethod類型的數(shù)組,表示該請求映射能夠匹配多種請求方式的請求
一個(gè)方法處理不同請求方式的接口
@RequestMapping( value = {"/testRequestMapping", "/test"}, method = {RequestMethod.GET, RequestMethod.POST} ) public String testRequestMapping(){ return "success"; }
@RequestMapping注解的params屬性(了解)
@RequestMapping注解的params屬性通過請求的請求參數(shù)匹配請求映射
@RequestMapping注解的params屬性是一個(gè)字符串類型的數(shù)組,可以通過四種表達(dá)式設(shè)置請求參數(shù)和請求映射的匹配關(guān)系
“param”:要求請求映射所匹配的請求必須攜帶param請求參數(shù)
“!param”:要求請求映射所匹配的請求必須不能攜帶param請求參數(shù)
“param=value”:要求請求映射所匹配的請求必須攜帶param請求參數(shù)且param=value
“param!=value”:要求請求映射所匹配的請求必須攜帶param請求參數(shù)但是param!=value
@RequestMapping( value = {"/testRequestMapping", "/test"} ,method = {RequestMethod.GET, RequestMethod.POST} ,params = {"username","password!=123456"} ) public String testRequestMapping(){ return "success"; }
@RequestMapping注解的headers屬性(了解)
@RequestMapping注解的headers屬性通過請求的請求頭信息匹配請求映射
@RequestMapping注解的headers屬性是一個(gè)字符串類型的數(shù)組,可以通過四種表達(dá)式設(shè)置請求頭信息和請求映射的匹配關(guān)系
“header”:要求請求映射所匹配的請求必須攜帶header請求頭信息
“!header”:要求請求映射所匹配的請求必須不能攜帶header請求頭信息
“header=value”:要求請求映射所匹配的請求必須攜帶header請求頭信息且header=value
“header!=value”:要求請求映射所匹配的請求必須攜帶header請求頭信息且header!=value
若當(dāng)前請求滿足@RequestMapping注解的value和method屬性,但是不滿足headers屬性,此時(shí)頁面顯示404錯(cuò)誤,即資源未找到
SpringMVC支持路徑中的占位符(重點(diǎn))
當(dāng)請求路徑中將某些數(shù)據(jù)通過路徑的方式傳輸?shù)椒?wù)器中,(比如get請求)就可以在相應(yīng)的@RequestMapping注解的value屬性中通過占位符{xxx}表示傳輸?shù)臄?shù)據(jù),在通過@PathVariable注解,將占位符所表示的數(shù)據(jù)賦值給控制器方法的形參
@RequestMapping("/testRest/{id}/{username}") public String testRest(@PathVariable("id") String id, @PathVariable("username") String username){ System.out.println("id:"+id+",username:"+username); return "success"; } //最終輸出的內(nèi)容為-->id:1,username:admin
@RequestParam
@RequestParam是將請求參數(shù)和控制器方法的形參創(chuàng)建映射關(guān)系
@RequestParam注解一共有三個(gè)屬性:
value:指定為形參賦值的請求參數(shù)的參數(shù)名
required:設(shè)置是否必須傳輸此請求參數(shù),默認(rèn)值為true
若設(shè)置為true時(shí),則當(dāng)前請求必須傳輸value所指定的請求參數(shù),若沒有傳輸該請求參數(shù),且沒有設(shè)置defaultValue屬性,則頁面報(bào)錯(cuò)400:Required String parameter ‘xxx' is not present;若設(shè)置為false,則當(dāng)前請求不是必須傳輸value所指定的請求參數(shù),若沒有傳輸,則注解所標(biāo)識(shí)的形參的值為null
defaultValue:不管required屬性值為true或false,當(dāng)value所指定的請求參數(shù)沒有傳輸或傳輸?shù)闹禐?"時(shí),則使用默認(rèn)值為形參賦值
@RequestHeader
@RequestHeader是將請求頭信息和控制器方法的形參創(chuàng)建映射關(guān)系
@RequestHeader注解一共有三個(gè)屬性:value、required、defaultValue,用法同@RequestParam
@CookieValue
@CookieValue是將cookie數(shù)據(jù)和控制器方法的形參創(chuàng)建映射關(guān)系
@CookieValue注解一共有三個(gè)屬性:value、required、defaultValue,用法同@RequestParam
@ResponseBody
@ResponseBody用于標(biāo)識(shí)一個(gè)控制器方法,可以將該方法的返回值直接作為響應(yīng)報(bào)文的響應(yīng)體響應(yīng)到瀏覽器
SpringMVC處理json
@ResponseBody處理json的步驟:
1.導(dǎo)入jackson的依賴
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version> </dependency>
2.在SpringMVC的核心配置文件中開啟mvc的注解驅(qū)動(dòng),此時(shí)在HandlerAdaptor中會(huì)自動(dòng)裝配一個(gè)消息轉(zhuǎn)換器:MappingJackson2HttpMessageConverter,可以將響應(yīng)到瀏覽器的Java對象轉(zhuǎn)換為Json格式的字符串
<mvc:annotation-driven />
3.在處理器方法上使用@ResponseBody注解進(jìn)行標(biāo)識(shí)
4.將Java對象直接作為控制器方法的返回值返回,就會(huì)自動(dòng)轉(zhuǎn)換為Json格式的字符串
@RequestMapping("/json") @ResponseBody public User testResponseUser(){ User user = new User(); user.setId(1001); user.setUsername("admin"); user.setPassword("123456"); user.setAge(23); user.setSex("男"); return user; }
運(yùn)行結(jié)果如圖
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
深入Spring Boot之ClassLoader的繼承關(guān)系和影響
這篇文章主要介紹了深入Spring Boot之ClassLoader的繼承關(guān)系和影響,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-06-06詳解如何使用IntelliJ IDEA新建一個(gè)Servlet項(xiàng)目
這篇文章主要介紹了詳解如何使用IntelliJ IDEA新建一個(gè)Servlet項(xiàng)目,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-11-11java實(shí)現(xiàn)Redisson的基本使用
Redisson是一個(gè)在Redis的基礎(chǔ)上實(shí)現(xiàn)的Java駐內(nèi)存數(shù)據(jù)網(wǎng)格客戶端,本文主要介紹了java實(shí)現(xiàn)Redisson的基本使用,具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12springboot連接redis并動(dòng)態(tài)切換database的實(shí)現(xiàn)方法
這篇文章主要介紹了springboot連接redis并動(dòng)態(tài)切換database,本文主為通過修改ConnectionFactory從而達(dá)到動(dòng)態(tài)切換database的效果,結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03Java?代碼本地設(shè)置Hadoop用戶名密碼的方法
在Hadoop環(huán)境中,通常使用Kerberos進(jìn)行身份驗(yàn)證,這篇文章主要介紹了Java?代碼本地設(shè)置Hadoop用戶名密碼的方法,需要的朋友可以參考下2024-08-08Springboot如何實(shí)現(xiàn)自定義異常數(shù)據(jù)
這篇文章主要介紹了Springboot如何實(shí)現(xiàn)自定義異常數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09SpringBoot+Shiro學(xué)習(xí)之密碼加密和登錄失敗次數(shù)限制示例
本篇文章主要介紹了SpringBoot+Shiro學(xué)習(xí)之密碼加密和登錄失敗次數(shù)限制示例,可以限制登陸次數(shù),有興趣的同學(xué)可以了解一下。2017-03-03