SpringMVC 參數(shù)綁定之視圖傳參到控制器的實(shí)現(xiàn)代碼
?? 基本類(lèi)型做形式參數(shù)(零散參數(shù)的數(shù)據(jù)接收)
1、基本數(shù)據(jù)類(lèi)型
要求前臺(tái)頁(yè)面的表單輸入框的name屬性值與對(duì)應(yīng)控制器方法中的形式參數(shù)名稱(chēng)與類(lèi)型一致,控制器方法就能接收到來(lái)自前臺(tái)表單傳過(guò)來(lái)的參數(shù),即請(qǐng)求參數(shù)與方法形參要完全相同,這些參數(shù)由系統(tǒng)在調(diào)用時(shí)直接賦值,程序員可在方法內(nèi)直接使用。
項(xiàng)目案例: 輸入學(xué)生姓名、年齡和分?jǐn)?shù),提交成功則跳轉(zhuǎn)到提交成功的界面并展示數(shù)據(jù)。
關(guān)鍵步驟:
【1】在 Controller 層新建一個(gè) TestController1 類(lèi),并添加一個(gè)方法,代碼如下:
package cn.hh.test02.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("testc1") public class TestController1 { @RequestMapping("login") public ModelAndView login(String sName,int sAge, double sScore ){ ModelAndView mv = new ModelAndView(); mv.setViewName("test1/show"); mv.addObject("currentShow",sName+"年齡:"+sAge+",分?jǐn)?shù):"+sScore); return mv; } }
【2】在 webapp 目錄下,新建一個(gè)目錄 test1,在 test1 中新建 test1.jsp 文件,代碼如下:
<%-- Created by IntelliJ IDEA. User: hhzb100 Date: 2023/2/28 Time: 10:23 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="../testc1/login"> 姓名:<input type="text" name="sName"> 年齡:<input type="text" name="sAge"> 分?jǐn)?shù):<input type="text" name="sScore"> <input type="submit" value="提交數(shù)據(jù)"> </form> </body> </html>
【3】再在上面的目錄里新建 show.jsp 文件,代碼如下:
<%-- Created by IntelliJ IDEA. User: hhzb100 Date: 2023/2/26 Time: 11:29 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>提交成功!${currentShow}</h1> </body> </html>
【4】在瀏覽器中輸入 http://localhost:8080/testspringmvc02/test1/test1.jsp,如下圖:
添加數(shù)據(jù)并提交,展示效果如下:
1.1 表單 name 屬性值與方法參數(shù)名稱(chēng)不一致解決方案
當(dāng)表單的 name 屬性值與方法參數(shù)的名稱(chēng)不同時(shí),會(huì)出現(xiàn)如下圖所示的500錯(cuò)誤:
表單的 name 屬性值內(nèi)容修改如下:
<form action="../testc1/login"> 姓名:<input type="text" name="stuName"> 年齡:<input type="text" name="stuAge"> 分?jǐn)?shù):<input type="text" name="stuScore"> <input type="submit" value="提交數(shù)據(jù)"> </form>
而 TestController1 處理器中的方法參數(shù)分別為:sName、sAge、sScore;
則在接受方法的形參前面加個(gè) @RequestParam(“表單 name 屬性值”), TestController1 類(lèi)代碼修改如下:
//1、表單 name 屬性值與方法參數(shù)名稱(chēng)不一致解決方案 @RequestMapping("login") public ModelAndView login(@RequestParam("stuName") String sName, @RequestParam("stuAge")int sAge, @RequestParam("stuScore")double sScore ){ ModelAndView mv = new ModelAndView(); mv.setViewName("test1/show"); mv.addObject("currentShow",sName+"年齡:"+sAge+",分?jǐn)?shù):"+sScore); return mv; }
1.2 表單 name 屬性值為空時(shí)解決方案
當(dāng)表單某個(gè) name 屬性值為空時(shí),運(yùn)行效果如下:
解決辦法: 設(shè)置基本參數(shù)類(lèi)型的默認(rèn)值 @RequestParam(defaultValue = “xx”);修改 TestController1 類(lèi)代碼如下:
package cn.hh.test02.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("testc1") public class TestController1 { @RequestMapping("login") public ModelAndView login(@RequestParam(defaultValue = "張三") String sName, @RequestParam(defaultValue = "20") int sAge, @RequestParam(defaultValue = "88.8") double sScore ){ ModelAndView mv = new ModelAndView(); mv.setViewName("test1/show"); mv.addObject("currentShow",sName+"年齡:"+sAge+",分?jǐn)?shù):"+sScore); return mv; } }
修改后的運(yùn)行效果如下:
2、包裝數(shù)據(jù)類(lèi)型(推薦使用)
使用基本類(lèi)型的包裝類(lèi),實(shí)現(xiàn)參數(shù)接收,避免使用基本類(lèi)型接收參數(shù)時(shí),將null值賦予基本類(lèi)型變量拋出異常的問(wèn)題。之前基本數(shù)據(jù)類(lèi)型會(huì)報(bào)500錯(cuò)誤,包裝數(shù)據(jù)類(lèi)型不會(huì)報(bào)錯(cuò)。
@RequestMapping("login") public ModelAndView login(String sName, Integer sAge, Double sScore ){ ModelAndView mv = new ModelAndView(); mv.setViewName("test1/show"); mv.addObject("currentShow",sName+"年齡:"+sAge+",分?jǐn)?shù):"+sScore); return mv; }
當(dāng)不賦值時(shí)的運(yùn)行效果如下,不會(huì)報(bào)500錯(cuò)誤。
3、@RequestParam() 屬性
@RequestParam()有三個(gè)屬性:
- value:指定請(qǐng)求參數(shù)的名稱(chēng)。
- required:指定該注解所修飾的參數(shù)是否是必須的,boolean 類(lèi)型。若為 true,則表示請(qǐng)求中所攜帶的參數(shù)中必須包含當(dāng)前參數(shù)。若為false,則表示有沒(méi)有均可。
- defaultValue:指定當(dāng)前參數(shù)的默認(rèn)值。若請(qǐng)求 URI 中沒(méi)有給出當(dāng)前參數(shù),則當(dāng)前方法參數(shù)將取該默認(rèn)值。即使required為true,且URI中沒(méi)有給出當(dāng)前參數(shù),該處理器方法參數(shù)會(huì)自動(dòng)取該默認(rèn)值,而不會(huì)報(bào)錯(cuò)。
?? 數(shù)組類(lèi)型做形式參數(shù)
接收數(shù)組參數(shù)的關(guān)鍵點(diǎn)有兩個(gè):
- 前臺(tái)表單有多個(gè)表單域的name屬性相同;
- 控制器方法用這個(gè)name值命名的數(shù)組作為參數(shù)。
項(xiàng)目案例: 頁(yè)面有多個(gè)興趣愛(ài)好供選擇,選擇好后,控制臺(tái)能顯示出來(lái)。
關(guān)鍵步驟:
【1】在 cn.hh.test02.controller 目錄下添加 TestController2 類(lèi),代碼如下:
package cn.hh.test02.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("testc2") public class TestController2 { @RequestMapping("interest") public String interest(String[] myInterest){ System.out.println("我的興趣愛(ài)好有:"); for (String s : myInterest) { System.out.println("interest = " + s); } return "test1/interest"; } }
【2】在 src/main/webapp/test1 目錄下新建 interest.jsp,代碼如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> 我的興趣愛(ài)好<br/> <form action="../testc2/interest"> 攝影:<input type="checkbox" name="myInterest" value="攝影"/><br/> 跳舞:<input type="checkbox" name="myInterest" value="跳舞"/><br/> 旅游:<input type="checkbox" name="myInterest" value="旅游"/><br/> 閱讀:<input type="checkbox" name="myInterest" value="閱讀"/><br/> <input type="submit" value="確定"/> </form> <br/>觀測(cè)控制臺(tái)的輸出 </body> </html>
【3】運(yùn)行測(cè)試:
確定興趣愛(ài)好,觀察控制臺(tái),控制臺(tái)打印如下:
?? 實(shí)體 Bean 做形式參數(shù)
方法 Delete5(User user) 可只用一個(gè)實(shí)體類(lèi)作形式參數(shù),前提是這個(gè)實(shí)體類(lèi)的各個(gè)屬性要與前臺(tái)表單穿過(guò)來(lái)的各個(gè) name 屬性值相同。
關(guān)鍵步驟:
【1】創(chuàng)建實(shí)體類(lèi) User 類(lèi),代碼如下:
package cn.kgc.springmvc02.entity; import lombok.Data; @Data public class User { private String uName; private Integer uAge; }
【2】在 cn/kgc/springmvc02/controller 目錄下,新建 ParamController 類(lèi),代碼如下:
package cn.kgc.springmvc02.controller; import cn.kgc.springmvc02.entity.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("param") public class ParamController { @RequestMapping("delete") public String Delete5(User user) { System.out.println("user = " + user); return "show"; } }
【3】在 src/main/webapp 目錄下創(chuàng)建 show.jsp,代碼如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>刪除成功!</h1> </body> </html>
【4】頁(yè)面展示效果
【5】控制臺(tái)打印效果
?? RESTful 風(fēng)格編程
什么是REST風(fēng)格:把請(qǐng)求參數(shù)變?yōu)檎?qǐng)求路徑的一種編程風(fēng)格。 通過(guò)路徑變量的使用,可以實(shí)現(xiàn)REST風(fēng)格的編程。
傳統(tǒng)的編程風(fēng)格中,某項(xiàng)事物列表Web頁(yè)面,要想一個(gè)個(gè)編輯,需要每一項(xiàng)中有類(lèi)似這種超鏈接:
/restfuls?id=1
其中每一項(xiàng)的id不同。而采用RESTful風(fēng)格后,超鏈接將變成:
/ restfuls/1 或者 1/restfuls 意義一樣。
restful風(fēng)格 | 請(qǐng)求方式 | 說(shuō)明 |
---|---|---|
/users | get | 查詢(xún)?nèi)苛斜頂?shù)據(jù) |
/users/1 | get | 根據(jù) id 查詢(xún)一條數(shù)據(jù) |
/users/1 | delete | 根據(jù) id 刪除一條數(shù)據(jù) |
/users | post | 添加數(shù)據(jù),參數(shù)以json格式進(jìn)行傳遞 |
/users | put | 修改數(shù)據(jù) |
@PathVariable 映射 URL 綁定的占位符:
通過(guò) @PathVariable 可以將 URL 中占位符參數(shù)綁定到控制器處理方法的入?yún)⒅?URL 中的 {xxx} 占位符可以通過(guò)
@PathVariable(“xxx”) 綁定到操作方法的入?yún)⒅小?/p>
一般與 @RequestMapping(“xxx”) 一起使用
項(xiàng)目代碼:
package cn.kgc.springmvc02.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("restfuls") public class RestfulController { //1、列表查詢(xún) @GetMapping public String getList(){ System.out.println("列表數(shù)據(jù)展示"); return "show"; } //2、查詢(xún)一個(gè) @GetMapping("{id}") public String getDataById(@PathVariable Integer id){ System.out.println("查詢(xún)id = " + id); return "show"; } //3、根據(jù) id 刪除一條數(shù)據(jù) @DeleteMapping("{id}") public String deleteById(@PathVariable Integer id){ System.out.println("刪除id = " + id); return "show"; } //4、添加數(shù)據(jù) @PostMapping public String addData(){ return "show"; } //5、修改數(shù)據(jù) @PutMapping("{id}") public String updateData(@PathVariable Integer id){ System.out.println("修改id = " + id); return "show"; } }
運(yùn)行測(cè)試:
【1】列表查詢(xún)(請(qǐng)求地址:/restfuls;請(qǐng)求方式:GET)
控制臺(tái)打?。?/p>
【2】查詢(xún)一個(gè)(請(qǐng)求地址:/restfuls/1;請(qǐng)求方式:GET)
控制臺(tái)打?。?/p>
【3】根據(jù) id 刪除一條數(shù)據(jù)(請(qǐng)求地址:/restfuls/1;請(qǐng)求方式:DELETE)
控制臺(tái)打?。?/p>
【4】添加數(shù)據(jù)(請(qǐng)求地址:/restfuls;請(qǐng)求方式:POST)
控制臺(tái)打?。?/p>
【5】修改數(shù)據(jù)(請(qǐng)求地址:/restfuls/1;請(qǐng)求方式:PUT)
控制臺(tái)打印:
?? 常見(jiàn)報(bào)錯(cuò)
1、中文亂碼問(wèn)題
對(duì)于上面案例所請(qǐng)求的參數(shù),若含有中文,可能會(huì)出現(xiàn)中文亂碼問(wèn)題,SpringMVC 對(duì)于請(qǐng)求參數(shù)中的中文亂碼問(wèn)題,提供了專(zhuān)門(mén)的字符集過(guò)濾器,只需要在web.xml配置文件中注冊(cè)字符串過(guò)濾器即可解決中文亂碼問(wèn)題。上面項(xiàng)目若要解決亂碼問(wèn)題,只需在 web.xml 中添加如下配置即即可:
<!--注冊(cè)字符集過(guò)濾器--> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <!--指定字符集--> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <!--強(qiáng)制使用指定字符集--> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2、使用 ModelAndView,頁(yè)面卻獲取不到值
有時(shí)候我們使用 ModelAndView 添加模型數(shù)據(jù)的時(shí)候,頁(yè)面用${ } 獲取不到相應(yīng)的值,也面效果如下:
造成這個(gè)問(wèn)題的原因是項(xiàng)目中的 web.xml 文件內(nèi)容有問(wèn)題,先看看未修改前的頭部?jī)?nèi)容:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name>
修改后的web.xml內(nèi)容:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Archetype Created Web Application</display-name>
修改之后,便可以解決這個(gè)問(wèn)題!
到此這篇關(guān)于SpringMVC 參數(shù)綁定(視圖傳參到控制器)的文章就介紹到這了,更多相關(guān)SpringMVC 參數(shù)綁定內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot配置MongoDB多數(shù)據(jù)源的方法步驟
這篇文章主要介紹了SpringBoot配置MongoDB多數(shù)據(jù)源的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10Spring Data JPA調(diào)用存儲(chǔ)過(guò)程實(shí)例代碼
本篇文章主要介紹了Spring Data JPA調(diào)用存儲(chǔ)過(guò)程實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-04-04解決java.sql.SQLException:索引中丟失 IN或OUT 參數(shù)::x問(wèn)題
這篇文章主要介紹了解決java.sql.SQLException:索引中丟失 IN或OUT 參數(shù)::x問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12Spring+Vue整合UEditor富文本實(shí)現(xiàn)圖片附件上傳的方法
這篇文章主要介紹了Spring+Vue整合UEditor富文本實(shí)現(xiàn)圖片附件上傳的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07JAVA構(gòu)造函數(shù)不能使用void關(guān)鍵字問(wèn)題
這篇文章主要介紹了JAVA構(gòu)造函數(shù)不能使用void關(guān)鍵字問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03SpringBoot配置文件application.properties的使用
這篇文章主要介紹了SpringBoot配置文件application.properties的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05Spring中的@ControllerAdvice和@ExceptionHandler注解處理全局異常
這篇文章主要介紹了Spring中的@ControllerAdvice和@ExceptionHandler注解處理全局異常,@ControllerAdvice ,@ControllerAdvice是一個(gè)非常有用的注解,顧名思義,這是一個(gè)增強(qiáng)的 Controller,一般配合@ExceptionHandler使用來(lái)處理全局異常,需要的朋友可以參考下2024-01-01