SpringMVC 參數(shù)綁定之視圖傳參到控制器的實現(xiàn)代碼
?? 基本類型做形式參數(shù)(零散參數(shù)的數(shù)據(jù)接收)
1、基本數(shù)據(jù)類型
要求前臺頁面的表單輸入框的name屬性值與對應(yīng)控制器方法中的形式參數(shù)名稱與類型一致,控制器方法就能接收到來自前臺表單傳過來的參數(shù),即請求參數(shù)與方法形參要完全相同,這些參數(shù)由系統(tǒng)在調(diào)用時直接賦值,程序員可在方法內(nèi)直接使用。
項目案例: 輸入學生姓名、年齡和分數(shù),提交成功則跳轉(zhuǎn)到提交成功的界面并展示數(shù)據(jù)。
關(guān)鍵步驟:
【1】在 Controller 層新建一個 TestController1 類,并添加一個方法,代碼如下:
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+",分數(shù):"+sScore); return mv; } }
【2】在 webapp 目錄下,新建一個目錄 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"> 分數(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ù)名稱不一致解決方案
當表單的 name 屬性值與方法參數(shù)的名稱不同時,會出現(xiàn)如下圖所示的500錯誤:
表單的 name 屬性值內(nèi)容修改如下:
<form action="../testc1/login"> 姓名:<input type="text" name="stuName"> 年齡:<input type="text" name="stuAge"> 分數(shù):<input type="text" name="stuScore"> <input type="submit" value="提交數(shù)據(jù)"> </form>
而 TestController1 處理器中的方法參數(shù)分別為:sName、sAge、sScore;
則在接受方法的形參前面加個 @RequestParam(“表單 name 屬性值”), TestController1 類代碼修改如下:
//1、表單 name 屬性值與方法參數(shù)名稱不一致解決方案 @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+",分數(shù):"+sScore); return mv; }
1.2 表單 name 屬性值為空時解決方案
當表單某個 name 屬性值為空時,運行效果如下:
解決辦法: 設(shè)置基本參數(shù)類型的默認值 @RequestParam(defaultValue = “xx”);修改 TestController1 類代碼如下:
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+",分數(shù):"+sScore); return mv; } }
修改后的運行效果如下:
2、包裝數(shù)據(jù)類型(推薦使用)
使用基本類型的包裝類,實現(xiàn)參數(shù)接收,避免使用基本類型接收參數(shù)時,將null值賦予基本類型變量拋出異常的問題。之前基本數(shù)據(jù)類型會報500錯誤,包裝數(shù)據(jù)類型不會報錯。
@RequestMapping("login") public ModelAndView login(String sName, Integer sAge, Double sScore ){ ModelAndView mv = new ModelAndView(); mv.setViewName("test1/show"); mv.addObject("currentShow",sName+"年齡:"+sAge+",分數(shù):"+sScore); return mv; }
當不賦值時的運行效果如下,不會報500錯誤。
3、@RequestParam() 屬性
@RequestParam()有三個屬性:
- value:指定請求參數(shù)的名稱。
- required:指定該注解所修飾的參數(shù)是否是必須的,boolean 類型。若為 true,則表示請求中所攜帶的參數(shù)中必須包含當前參數(shù)。若為false,則表示有沒有均可。
- defaultValue:指定當前參數(shù)的默認值。若請求 URI 中沒有給出當前參數(shù),則當前方法參數(shù)將取該默認值。即使required為true,且URI中沒有給出當前參數(shù),該處理器方法參數(shù)會自動取該默認值,而不會報錯。
?? 數(shù)組類型做形式參數(shù)
接收數(shù)組參數(shù)的關(guān)鍵點有兩個:
- 前臺表單有多個表單域的name屬性相同;
- 控制器方法用這個name值命名的數(shù)組作為參數(shù)。
項目案例: 頁面有多個興趣愛好供選擇,選擇好后,控制臺能顯示出來。
關(guān)鍵步驟:
【1】在 cn.hh.test02.controller 目錄下添加 TestController2 類,代碼如下:
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("我的興趣愛好有:"); 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> 我的興趣愛好<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/>觀測控制臺的輸出 </body> </html>
【3】運行測試:
確定興趣愛好,觀察控制臺,控制臺打印如下:
?? 實體 Bean 做形式參數(shù)
方法 Delete5(User user) 可只用一個實體類作形式參數(shù),前提是這個實體類的各個屬性要與前臺表單穿過來的各個 name 屬性值相同。
關(guān)鍵步驟:
【1】創(chuàng)建實體類 User 類,代碼如下:
package cn.kgc.springmvc02.entity; import lombok.Data; @Data public class User { private String uName; private Integer uAge; }
【2】在 cn/kgc/springmvc02/controller 目錄下,新建 ParamController 類,代碼如下:
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】頁面展示效果
【5】控制臺打印效果
?? RESTful 風格編程
什么是REST風格:把請求參數(shù)變?yōu)檎埱舐窂降囊环N編程風格。 通過路徑變量的使用,可以實現(xiàn)REST風格的編程。
傳統(tǒng)的編程風格中,某項事物列表Web頁面,要想一個個編輯,需要每一項中有類似這種超鏈接:
/restfuls?id=1
其中每一項的id不同。而采用RESTful風格后,超鏈接將變成:
/ restfuls/1 或者 1/restfuls 意義一樣。
restful風格 | 請求方式 | 說明 |
---|---|---|
/users | get | 查詢?nèi)苛斜頂?shù)據(jù) |
/users/1 | get | 根據(jù) id 查詢一條數(shù)據(jù) |
/users/1 | delete | 根據(jù) id 刪除一條數(shù)據(jù) |
/users | post | 添加數(shù)據(jù),參數(shù)以json格式進行傳遞 |
/users | put | 修改數(shù)據(jù) |
@PathVariable 映射 URL 綁定的占位符:
通過 @PathVariable 可以將 URL 中占位符參數(shù)綁定到控制器處理方法的入?yún)⒅?URL 中的 {xxx} 占位符可以通過
@PathVariable(“xxx”) 綁定到操作方法的入?yún)⒅小?/p>
一般與 @RequestMapping(“xxx”) 一起使用
項目代碼:
package cn.kgc.springmvc02.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("restfuls") public class RestfulController { //1、列表查詢 @GetMapping public String getList(){ System.out.println("列表數(shù)據(jù)展示"); return "show"; } //2、查詢一個 @GetMapping("{id}") public String getDataById(@PathVariable Integer id){ System.out.println("查詢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"; } }
運行測試:
【1】列表查詢(請求地址:/restfuls;請求方式:GET)
控制臺打?。?/p>
【2】查詢一個(請求地址:/restfuls/1;請求方式:GET)
控制臺打?。?/p>
【3】根據(jù) id 刪除一條數(shù)據(jù)(請求地址:/restfuls/1;請求方式:DELETE)
控制臺打印:
【4】添加數(shù)據(jù)(請求地址:/restfuls;請求方式:POST)
控制臺打印:
【5】修改數(shù)據(jù)(請求地址:/restfuls/1;請求方式:PUT)
控制臺打?。?/p>
?? 常見報錯
1、中文亂碼問題
對于上面案例所請求的參數(shù),若含有中文,可能會出現(xiàn)中文亂碼問題,SpringMVC 對于請求參數(shù)中的中文亂碼問題,提供了專門的字符集過濾器,只需要在web.xml配置文件中注冊字符串過濾器即可解決中文亂碼問題。上面項目若要解決亂碼問題,只需在 web.xml 中添加如下配置即即可:
<!--注冊字符集過濾器--> <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> <!--強制使用指定字符集--> <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,頁面卻獲取不到值
有時候我們使用 ModelAndView 添加模型數(shù)據(jù)的時候,頁面用${ } 獲取不到相應(yīng)的值,也面效果如下:
造成這個問題的原因是項目中的 web.xml 文件內(nèi)容有問題,先看看未修改前的頭部內(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>
修改之后,便可以解決這個問題!
到此這篇關(guān)于SpringMVC 參數(shù)綁定(視圖傳參到控制器)的文章就介紹到這了,更多相關(guān)SpringMVC 參數(shù)綁定內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot配置MongoDB多數(shù)據(jù)源的方法步驟
這篇文章主要介紹了SpringBoot配置MongoDB多數(shù)據(jù)源的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10Spring Data JPA調(diào)用存儲過程實例代碼
本篇文章主要介紹了Spring Data JPA調(diào)用存儲過程實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-04-04解決java.sql.SQLException:索引中丟失 IN或OUT 參數(shù)::x問題
這篇文章主要介紹了解決java.sql.SQLException:索引中丟失 IN或OUT 參數(shù)::x問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12Spring+Vue整合UEditor富文本實現(xiàn)圖片附件上傳的方法
這篇文章主要介紹了Spring+Vue整合UEditor富文本實現(xiàn)圖片附件上傳的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07JAVA構(gòu)造函數(shù)不能使用void關(guān)鍵字問題
這篇文章主要介紹了JAVA構(gòu)造函數(shù)不能使用void關(guān)鍵字問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03SpringBoot配置文件application.properties的使用
這篇文章主要介紹了SpringBoot配置文件application.properties的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05Spring中的@ControllerAdvice和@ExceptionHandler注解處理全局異常
這篇文章主要介紹了Spring中的@ControllerAdvice和@ExceptionHandler注解處理全局異常,@ControllerAdvice ,@ControllerAdvice是一個非常有用的注解,顧名思義,這是一個增強的 Controller,一般配合@ExceptionHandler使用來處理全局異常,需要的朋友可以參考下2024-01-01