詳解springMVC獲取前端請(qǐng)求的數(shù)據(jù)與三個(gè)作用域
獲取請(qǐng)求數(shù)據(jù)
使用原生的Servlet API獲取請(qǐng)求數(shù)據(jù)
// 處理注冊(cè)請(qǐng)求
@PostMapping("/register/user")
public String register(HttpServletRequest request, HttpSession session, HttpServletResponse resp) {
// 獲取請(qǐng)求參數(shù)
// HttpServletRequest\HttpSession\HttpServletResponse 都屬于Servlet API,Spring MVC會(huì)自動(dòng)將它們注入到方法參數(shù)中
String username = request.getParameter("username");
String password = request.getParameter("password");
return "success";
}@RequestParam注解
@RequestParam的作用:將請(qǐng)求參數(shù)與方法上的形參映射
@PostMapping("/register/user/2")
public String register2(
// @RequestParam注解用于將請(qǐng)求參數(shù)綁定到方法參數(shù)上,value屬性指定請(qǐng)求參數(shù)的名稱(chēng),參數(shù)名可以和請(qǐng)求參數(shù)名不同
// 可以自動(dòng)將請(qǐng)求參數(shù)轉(zhuǎn)換為方法參數(shù)的類(lèi)型,例如將字符串轉(zhuǎn)換為整數(shù)、日期等
@RequestParam("username") String username,
@RequestParam("password") String password) {
return "success";
}@RequestParam的required和defaultValue屬性
required屬性:設(shè)置該參數(shù)是否是必須的。默認(rèn)true,默認(rèn)參數(shù)是必須的,如果前端沒(méi)有提交這個(gè)參數(shù),則報(bào)錯(cuò)。如果設(shè)置為false。則不會(huì)報(bào)錯(cuò)。
defaultValue屬性:給參數(shù)設(shè)置默認(rèn)值,如果前端沒(méi)傳這個(gè)參數(shù),則會(huì)使用默認(rèn)值。
@PostMapping("/register/user/2")
public String register2(
// @RequestParam注解用于將請(qǐng)求參數(shù)綁定到方法參數(shù)上,value屬性指定請(qǐng)求參數(shù)的名稱(chēng),參數(shù)名可以和請(qǐng)求參數(shù)名不同
// 可以自動(dòng)將請(qǐng)求參數(shù)轉(zhuǎn)換為方法參數(shù)的類(lèi)型,例如將字符串轉(zhuǎn)換為整數(shù)、日期等
@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam(value = "age",required = false,defaultValue = "20") Integer age) {
return "success";
}依靠控制器方法上的形參名接收
如果請(qǐng)求的參數(shù)名和控制器方法上的形參名保持一致。那么 @RequestParam注解可以省略。
如果沒(méi)對(duì)應(yīng)上,則值為null。
@PostMapping("/register/user/3")
public String register3(String username, String password) {
// 這種方式要求請(qǐng)求參數(shù)的名稱(chēng)必須與方法參數(shù)的名稱(chēng)一致,Spring MVC會(huì)自動(dòng)將請(qǐng)求參數(shù)綁定到方法參數(shù)上
return "success";
}使用POJO類(lèi)/JavaBean接收參數(shù)
要求:POJO類(lèi)/JavaBean的屬性名必須和請(qǐng)求參數(shù)的參數(shù)名保持一致。
底層原理使用反射機(jī)制。并且調(diào)用JavaBean的set方法,set方法的方法名是關(guān)鍵,springMVC是通過(guò)set方法的方法名將對(duì)應(yīng)的參數(shù)注入到JavaBean中的。
@PostMapping("/register/user/4")
public String register4(User user) {
// 這種方式要求請(qǐng)求參數(shù)的名稱(chēng)必須與User類(lèi)的屬性名稱(chēng)一致,Spring MVC會(huì)自動(dòng)將請(qǐng)求參數(shù)綁定到User對(duì)象的屬性上
return "success";
}RequestHeader注解
作用:將請(qǐng)求頭信息映射到方法的形參上。
和@RequestParam注解功能相似。
對(duì)于RequestHeader注解來(lái)說(shuō),也有三個(gè)屬性:value、required、defaultValue,和RequestParam一樣。
@PostMapping("/register/user/4")
public String register4(User user, @RequestHeader(value = "Referer",required = false,defaultValue = "") String referer) {
return "success";
}CookieValue注解
作用:將提交的cookie數(shù)據(jù)映射到形參上。
同樣有三個(gè)屬性:value、required、defaultValue。
@PostMapping("/register/user/4")
public String register4(User user,
@RequestHeader(value = "Referer",required = false,defaultValue = "") String referer,
@CookieValue(value = "JSESSIONID",required = false,defaultValue = "") String jsessionId) {
// 這種方式要求請(qǐng)求參數(shù)的名稱(chēng)必須與User對(duì)象的屬性名稱(chēng)一致,Spring MVC會(huì)自動(dòng)將請(qǐng)求參數(shù)綁定到User對(duì)象的屬性上
// @RequestHeader注解用于將請(qǐng)求頭信息綁定到方法參數(shù)上,value屬性指定請(qǐng)求頭的名稱(chēng)
// @CookieValue注解用于將Cookie信息綁定到方法參數(shù)上,value屬性指定Cookie的名稱(chēng)
return "success";
}請(qǐng)求的中文亂碼問(wèn)題
get請(qǐng)求亂碼
解決方法:對(duì)URI進(jìn)行編碼設(shè)置,在Tomcat的配置CATALINA_HOME/conf/server.xml文件中:設(shè)置Connector 標(biāo)簽,添加 URIEncoding="UTF-8"
tomcat9和10 不會(huì)亂碼。因?yàn)樗麄円呀?jīng)默認(rèn)設(shè)置URI編碼為UTF-8.
對(duì)于tomcat8.默認(rèn)是ISO。所以需要設(shè)置為UTF-8。
post請(qǐng)求亂碼
解決辦法:
// 這行代碼必須在獲取參數(shù)的代碼之前執(zhí)行,不能寫(xiě)在下面
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");在tomcat10中,已經(jīng)自動(dòng)幫我們解決了亂碼問(wèn)題。
在tomcat9和以前的版本,會(huì)出現(xiàn)亂碼問(wèn)題,需要手動(dòng)解決。
第一種方案:自己編寫(xiě)一個(gè)過(guò)濾器!過(guò)濾器Filter在Servlet執(zhí)行之前執(zhí)行。
編寫(xiě)過(guò)濾器類(lèi)
public class CharacterEncodingFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 設(shè)置請(qǐng)求和響應(yīng)的字符編碼為UTF-8,解決中文亂碼問(wèn)題
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html;charset=UTF-8");
// 將請(qǐng)求和響應(yīng)對(duì)象傳遞給下一個(gè)過(guò)濾器或目標(biāo)資源
filterChain.doFilter(servletRequest, servletResponse);
}
}在web.xml配置過(guò)濾器
<!-- 設(shè)置字符編碼過(guò)濾器,解決post請(qǐng)求中文亂碼問(wèn)題-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>第二種方案:使用內(nèi)置過(guò)濾器解決,在web.xml中配置如下:
<!-- 使用springmvc提供的字符編碼過(guò)濾器,解決post請(qǐng)求中文亂碼問(wèn)題-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 設(shè)置字符集為UTF-8-->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!-- 請(qǐng)求體和響應(yīng)體都使用UTF-8字符集-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>三個(gè)域?qū)ο?/h2>
請(qǐng)求域:request(作用于一個(gè)請(qǐng)求中)
會(huì)話(huà)域:session(作用于一個(gè)會(huì)話(huà)中,瀏覽器打開(kāi)到瀏覽器關(guān)閉期間,保存用戶(hù)登錄狀態(tài))
應(yīng)用域:application(作用于一個(gè)應(yīng)用,服務(wù)器啟動(dòng)到服務(wù)器關(guān)閉期間,記錄網(wǎng)站在線(xiàn)人數(shù))
request域?qū)ο?/h2>
在springMVC中,在request域?qū)ο笾泄蚕頂?shù)據(jù)有以下幾種方式:
- 使用原生的Servlet API方式
- 使用Model接口
- 使用Map接口
- 使用ModelMap類(lèi)
- 使用ModelAndView類(lèi)
使用原生的Servlet API方式
controller中的代碼
@RequestMapping("/testServletAPI")
public String testServletAPI(HttpServletRequest request) {
// 將共享數(shù)據(jù)存入request域?qū)ο笾?
request.setAttribute("testRequestScope", "hello,servletAPI");
// 這個(gè)跳轉(zhuǎn)視圖默認(rèn)是forward方式,request域?qū)ο笾械臄?shù)據(jù)可以共享到目標(biāo)資源中
return "ok";
}html代碼用來(lái)取數(shù)據(jù)
<body>
<div th:text="${testRequestScope}"></div>
</body>使用Model接口
不使用Servlet API,所以單元測(cè)試時(shí)比較方便。
@RequestMapping("/testModel")
public String testModel(Model model) {
// 將共享數(shù)據(jù)存入model中
model.addAttribute("testRequestScope", "hello,Model");
return "ok";
}使用Map接口
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map) {
// 將共享數(shù)據(jù)存入map中
map.put("testRequestScope", "hello,Map");
return "ok";
}使用ModelMap類(lèi)
@RequestMapping("/testModelMap")
public String testModelMap(ModelMap modelMap) {
// 將共享數(shù)據(jù)存入modelMap中
modelMap.addAttribute("testRequestScope", "hello,ModelMap");
return "ok";
}Model、Map、ModelMap三者之間的關(guān)系
表面上這三者是不同的類(lèi)和接口,實(shí)際上底層都使用了同一個(gè)對(duì)象BindingAwareModelMap,。
這三者的方法表面上是返回了邏輯視圖名稱(chēng),是一個(gè)字符串,在底層實(shí)際上都是返回了ModelAndView對(duì)象。
使用ModelAndView類(lèi)
ModelAndView類(lèi)的實(shí)例封裝了Model和View。也就是說(shuō)它既封裝了處理業(yè)務(wù)之后的數(shù)據(jù),還封裝跳轉(zhuǎn)到哪個(gè)視圖,使用它可以完成request域數(shù)據(jù)共享。
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(ModelAndView modelAndView) {
// 將共享數(shù)據(jù)存入modelAndView中
modelAndView.addObject("testRequestScope", "hello,ModelAndView");
// 設(shè)置視圖名稱(chēng)
modelAndView.setViewName("ok");
return modelAndView;
}這里需要注意:
- 方法返回值類(lèi)型不是String.而是ModelAndView對(duì)象。
- ModelAndView不是出現(xiàn)在參數(shù)位置,而是在方法體中new出來(lái)的
- 需要調(diào)用addObject向域中存儲(chǔ)數(shù)據(jù)
- 需要調(diào)用setViewName設(shè)置視圖名稱(chēng)。
session域?qū)ο?/h2>
使用原生Servlet API
@RequestMapping("/testSessionScope")
public String test(HttpSession session) {
// 將共享數(shù)據(jù)存入session域?qū)ο笾?
session.setAttribute("testSessionScope", "hello,Session");
return "ok";
}html代碼用來(lái)取數(shù)據(jù)
<body>
<div th:text="${session.testSessionScope}"></div>
</body>使用SessionAttributes注解
使用SessionAttributes注解標(biāo)注controller
@Controller
// @SessionAttributes注解:將指定的屬性存儲(chǔ)到session域?qū)ο笾?
// 表示 將modelMap中key為"x"和"y"的屬性存儲(chǔ)到session域?qū)ο笾?
@SessionAttributes(value = {"x", "y"})
public class SessionScopeTestController {
@RequestMapping("/testSessionAttribute")
public String testSessionAttribute(ModelMap modelMap) {
// 將共享數(shù)據(jù)存入session域?qū)ο笾?
modelMap.addAttribute("x", "hello,x");
modelMap.addAttribute("y", "hello,y");
return "ok";
}
}application域?qū)ο?/h2>
@RequestMapping("/testApplicationScope")
public String test(HttpServletRequest request) {
// 將共享數(shù)據(jù)存入application域?qū)ο笾?
ServletContext servletContext = request.getServletContext();
servletContext.setAttribute("testApplicationScope", "hello,Application");
return "ok";
}
@RequestMapping("/testApplicationScope")
public String test(HttpServletRequest request) {
// 將共享數(shù)據(jù)存入application域?qū)ο笾?
ServletContext servletContext = request.getServletContext();
servletContext.setAttribute("testApplicationScope", "hello,Application");
return "ok";
}html代碼。用來(lái)取數(shù)據(jù)
<body>
<div th:text="${application.testApplicationScope}"></div>
</body>到此這篇關(guān)于springMVC獲取前端請(qǐng)求的數(shù)據(jù)與三個(gè)作用域的文章就介紹到這了,更多相關(guān)springMVC獲取前端請(qǐng)求的數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringMVC打印請(qǐng)求參數(shù)和響應(yīng)數(shù)據(jù)最優(yōu)方案
- SpringMVC 重新定向redirect請(qǐng)求中攜帶數(shù)據(jù)方式
- 使用springmvc的controller層獲取到請(qǐng)求的數(shù)據(jù)方式
- Springmvc獲取前臺(tái)請(qǐng)求數(shù)據(jù)過(guò)程解析
- Springmvc處理ajax請(qǐng)求并返回json數(shù)據(jù)
- SpringMVC 跨重定向請(qǐng)求傳遞數(shù)據(jù)的方法實(shí)現(xiàn)
- SpringMVC解析JSON請(qǐng)求數(shù)據(jù)問(wèn)題解析
- SpringMVC環(huán)境下實(shí)現(xiàn)的Ajax異步請(qǐng)求JSON格式數(shù)據(jù)
相關(guān)文章
Java FileInputStream與FileOutputStream使用詳解
這篇文章主要介紹了Java FileInputStream與FileOutputStream使用詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
Java實(shí)現(xiàn)多線(xiàn)程下載和斷點(diǎn)續(xù)傳
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)多線(xiàn)程下載和斷點(diǎn)續(xù)傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06
Spring使用@Conditional進(jìn)行條件裝配的實(shí)現(xiàn)
在spring中有些bean需要滿(mǎn)足某些環(huán)境條件才創(chuàng)建某個(gè)bean,這個(gè)時(shí)候可以在bean定義上使用@Conditional注解來(lái)修飾,所以本文給大家介紹了Spring使用@Conditional進(jìn)行條件裝配的實(shí)現(xiàn),文中通過(guò)代碼示例給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
Java實(shí)現(xiàn)跨服務(wù)器上傳文件功能
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)跨服務(wù)器上傳文件功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
IDEA搭建多模塊的Maven項(xiàng)目方式(相互依賴(lài))
這篇文章主要介紹了IDEA搭建多模塊的Maven項(xiàng)目方式(相互依賴(lài)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
RabbitMQ消息總線(xiàn)方式刷新配置服務(wù)全過(guò)程
Spring Cloud Bus通過(guò)消息總線(xiàn)與MQ實(shí)現(xiàn)微服務(wù)配置統(tǒng)一刷新,結(jié)合Git Webhooks自動(dòng)觸發(fā)更新,避免手動(dòng)重啟,提升效率與可靠性,適用于配置管理及全局信息同步場(chǎng)景2025-07-07

