spring—SpringMVC的請求和響應

SpringMVC的數據響應-數據響應方式

  1. 頁面跳轉

直接返回字符串

   @RequestMapping(value = {"/qq"},method = {RequestMethod.GET},params = {"name"})public  String method(){System.out.println("controller");return "success";}
    <bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="suffix" value=".jsp"/><property name="prefix" value="/WEB-INF/"/></bean>

通過ModelAndView對象返回

    @RequestMapping(value = {"/qq2"})public  ModelAndView method2(ModelAndView modelAndView){modelAndView.addObject("name","ccc");modelAndView.setViewName("success");return modelAndView;}@RequestMapping(value = {"/qq3"})public  String method3(Model model){model.addAttribute("name","kkk");return "success";}

2) 回寫數據

直接返回字符串

返回對象或集合

SpringMVC的數據響應-回寫數據-返回對象或集合

在方法上添加@ResponseBody就可以返回json格式的字符串,但是這樣配置比較麻煩,配置的代碼比較多,因此,我們可以使用mvc的注解驅動代替上述配置

<mvc:annotation-driven/>

在 SpringMVC 的各個組件中,處理器映射器、處理器適配器、視圖解析器稱為 SpringMVC 的三大組件。

使用<mvc:annotation-driven />自動加載 RequestMappingHandlerMapping(處理映射器)和

RequestMappingHandlerAdapter( 處 理 適 配 器 ),可用在Spring-xml.xml配置文件中使用

<mvc:annotation-driven />替代注解處理器和適配器的配置。

同時使用<mvc:annotation-driven />

默認底層就會集成jackson進行對象或集合的json格式字符串的轉換

<?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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
"><context:component-scan base-package="com.controller" />
<!--    <mvc:annotation-driven />--><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><property name="messageConverters"><list><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/></list></property></bean><bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="suffix" value=".jsp"/><property name="prefix" value="/WEB-INF/"/></bean>
</beans>
    @RequestMapping(value = {"/qq5"})@ResponseBodypublic  Student method5(Model model){Student student=new Student();student.setName("gg");student.setSno("1122");return student;}

SpringMVC的請求

SpringMVC的請求-獲得請求參數-請求參數類型

客戶端請求參數的格式是:name=value&name=value……

服務器端要獲得請求的參數,有時還需要進行數據的封裝,SpringMVC可以接收如下類型的參數

基本類型參數

POJO類型參數

數組類型參數

集合類型參數

SpringMVC的請求-獲得請求參數-獲得基本類型參數(應用)

Controller中的業務方法的參數名稱要與請求參數的name一致,參數值會自動映射匹配。并且能自動做類型轉換;

http://localhost:8080/qq6?name=zzx&sno=17582

自動的類型轉換是指從String向其他類型的轉換

    @RequestMapping(value = {"/qq6"})@ResponseBodypublic  void method6(String name,String sno){System.out.println(name);System.out.println(sno);}

SpringMVC的請求-獲得請求參數-獲得POJO類型參數(應用)

Controller中的業務方法的POJO參數的屬性名與請求參數的name一致,參數值會自動映射匹配。

    @RequestMapping(value = {"/qq7"})@ResponseBodypublic  void method7(Student student){System.out.println(student);}

SpringMVC的請求-獲得請求參數-獲得數組類型參數

Controller中的業務方法數組名稱與請求參數的name一致,參數值會自動映射匹配。

    @RequestMapping(value = {"/qq8"})@ResponseBodypublic  void method8(String[] student){System.out.println(Arrays.asList(student));}

SpringMVC的請求-獲得請求參數-獲得集合類型參數

獲得集合參數時,要將集合參數包裝到一個POJO中才可以。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/qq9" method="post"><%--表明是第一個User對象的username age--%><input type="text" name="students[0].name"><br/><input type="text" name="students[0].sno"><br/><input type="text" name="students[1].name"><br/><input type="text" name="students[1].sno"><br/><input type="submit" value="提交">
</form>
</body>
</html>
    @RequestMapping(value = {"/qq9"})@ResponseBodypublic  void method9(VO student){System.out.println(student);}public class VO {List<Student> students;public List<Student> getStudents() {return students;}public void setStudents(List<Student> students) {this.students = students;}@Overridepublic String toString() {return "VO{" +"students=" + students +'}';}
}

SpringMVC的請求-獲得請求參數-獲得集合類型參數2

當使用ajax提交時,可以指定contentType為json形式,那么在方法參數位置使用@RequestBody可以直接接收集合數據而無需使用POJO進行包裝

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body>
<script src="${pageContext.request.contextPath}/js/jquery-3.3.1.js"></script>
<script>var userList = new Array();userList.push({name:"zhangsan",sno:"c11"});userList.push({name:"lisi",sno:"c12"});$.ajax({type:"POST",url:"${pageContext.request.contextPath}/qq10",data:JSON.stringify(userList),contentType:"application/json;charset=utf-8"});</script>
</body>
</html>@RequestMapping(value = {"/qq10"})@ResponseBodypublic  void method10(@RequestBody List<Student> userList){System.out.println(userList);}

SpringMVC的請求-獲得請求參數-靜態資源訪問的開啟

<url-pattern>/</url-pattern>攔截所有請求包括靜態資源,springMVC會將靜態資源當做一個普通的請求處理,從而也找不到相應的處理器導致404錯誤.這時候dispatchServlet完全取代了default servlet,將不會再訪問容器中原始默認的servlet,而對靜態資源的訪問就是通過容器默認servlet來處理的,故而這時候靜態資源將不可訪問。
當有靜態資源需要加載時,比如jquery文件,通過谷歌開發者工具抓包發現,沒有加載到jquery文件,原因是SpringMVC的前端控制器DispatcherServlet的url-pattern配置的是/,代表對所有的資源都進行過濾操作,我們可以通過以下兩種方式指定放行靜態資源:

?在spring-mvc.xml配置文件中指定放行的資源

? <mvc:resources mapping="/js/**"location="/js/"/>

?使用<mvc:default-servlet-handler/>標簽

<!--開發資源的訪問--><!--<mvc:resources mapping="/js/**" location="/js/"/><mvc:resources mapping="/img/**" location="/img/"/>--><mvc:default-servlet-handler/>

這里有有一點要注意,default servlet對于使用beanName方式配置的處理器,是可以訪問的.但是對于@RequestMapping注解方式配置的處理器是不起作用的,
因為沒有相應的HandlerMapping和HandlerAdapter支持注解的使用。這時候可以使用<mvc:annotation-driven/>配置在容器中注冊支持@RequestMapping注解的組件即可.

SpringMVC的請求-獲得請求參數-配置全局亂碼過濾器

當post請求時,數據會出現亂碼,我們可以設置一個過濾器來進行編碼的過濾。

    <filter><filter-name>filter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>ending</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>filter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
    @RequestMapping(value = {"/qq6"})@ResponseBodypublic  void method6(String name,String sno){System.out.println(name);System.out.println(sno);}

19-SpringMVC的請求-獲得請求參數-參數綁定注解@RequestParam(應用)

當請求的參數名稱與Controller的業務方法參數名稱不一致時,就需要通過@RequestParam注解顯示的綁定

    @RequestMapping(value = {"/qq11"})@ResponseBodypublic  void method11(@RequestParam(value="name",required = false, defaultValue = "xxx") String userName){System.out.println(userName);}<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>hhhh</title>
</head>
<body>
<h1>hello</h1>
<form action="${pageContext.request.contextPath}/qq11" method="post"><input type="text" name="name"><br><input type="submit" value="提交"><br>
</form>
</body>
</html>

SpringMVC的請求-獲得請求參數-Restful風格的參數的獲取

Restful是一種軟件架構風格、設計風格,而不是標準,只是提供了一組設計原則和約束條件。主要用于客戶端和服務器交互類的軟件,基于這個風格設計的軟件可以更簡潔,更有層次,更易于實現緩存機制等。

Restful風格的請求是使用“url+請求方式”表示一次請求目的的,HTTP 協議里面四個表示操作方式的動詞如下:

GET:用于獲取資源

POST:用于新建資源

PUT:用于更新資源

DELETE:用于刪除資源

例如:

/user/1 GET : 得到 id = 1 的 user

/user/1 DELETE: 刪除 id = 1 的 user

/user/1 PUT: 更新 id = 1 的 user

/user POST: 新增 user

上述url地址/user/1中的1就是要獲得的請求參數,在SpringMVC中可以使用占位符進行參數綁定。地址/user/1可以寫成/user/{id},占位符{id}對應的就是1的值。在業務方法中我們可以使用@PathVariable注解進行占位符的匹配獲取工作。

http://localhost:8080/qq12/xxx

    @RequestMapping(value = {"/qq12/{name}"})@ResponseBodypublic  void method12(@PathVariable(value="name",required = false) String userName){System.out.println(userName);}

SpringMVC的請求-獲得請求參數-自定義類型轉換器

SpringMVC 默認已經提供了一些常用的類型轉換器,例如客戶端提交的字符串轉換成int型進行參數設置。

但是不是所有的數據類型都提供了轉換器,沒有提供的就需要自定義轉換器,例如:日期類型的數據就需要自定義轉換器。

public class DateConverter implements Converter<String, Date> {public Date convert(String s) {SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");Date date=null;try {date =simpleDateFormat.parse(s);} catch (ParseException e) {e.printStackTrace();}return date;}
}@RequestMapping(value = {"/qq13"})@ResponseBodypublic  void method13(Date date){System.out.println(date);}
    <mvc:annotation-driven conversion-service="conversionService2"/><mvc:default-servlet-handler/><bean id="conversionService2" class="org.springframework.context.support.ConversionServiceFactoryBean"><property name="converters"><list><bean class="com.controller.DateConverter"/></list></property></bean>

SpringMVC的請求-獲得請求參數-獲得Servlet相關API

SpringMVC支持使用原始ServletAPI對象作為控制器方法的參數進行注入,常用的對象如下:

HttpServletRequest

HttpServletResponse

HttpSession

    @RequestMapping(value = {"/qq14"})@ResponseBodypublic  void method14(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, HttpSession httpSession){System.out.println(httpServletRequest);System.out.println( httpServletResponse);System.out.println(httpSession);}

SpringMVC的請求-獲得請求參數-獲得請求頭信息

使用@RequestHeader可以獲得請求頭信息,相當于web階段學習的request.getHeader(name)
@RequestHeader注解的屬性如下:

value:請求頭的名稱

required:是否必須攜帶此請求頭

使用@CookieValue可以獲得指定Cookie的值

    @RequestMapping(value = {"/qq16"})@ResponseBodypublic  void method16(@RequestHeader(value = "User-Agent",required = false) String User ){System.out.println(User);}

@CookieValue注解的屬性如下:

value:指定cookie的名稱

required:是否必須攜帶此cookie

    @RequestMapping(value = {"/qq17"})@ResponseBodypublic  void method17(@CookieValue(value = "JSESSIONID",required = false) String User ){System.out.println(User);}

SpringMVC的請求-文件上傳-客戶端表單實現

文件上傳客戶端表單需要滿足:

表單項type=“file”

表單的提交方式是post

表單的enctype屬性是多部分表單形式,及enctype=“multipart/form-data”

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>hhhh</title>
</head>
<body><form action="${pageContext.request.contextPath}/qq18" method="post" enctype="multipart/form-data">名稱 <input type="text" name="name"><br/>文件1<input type="file" name="multipartFile"><br/><input type="submit" value="提交">
</form></body>
</html>

3-SpringMVC的請求-文件上傳-單文件上傳的代碼實現

添加依賴

<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.3</version></dependency>

配置多媒體解析器

<!--配置文件上傳解析器,id必須為multipartResolver,否則會出錯--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="UTF-8"/><property name="maxUploadSize" value="500000"/></bean>

完成文件上傳

    @RequestMapping(value = {"/qq18"})@ResponseBodypublic  void method17(String name, MultipartFile multipartFile){System.out.println(name);try {multipartFile.transferTo(new File("e://"+multipartFile.getOriginalFilename()));} catch (IOException ioException) {ioException.printStackTrace();}}

SpringMVC的請求-文件上傳-多文件上傳的代碼實現

多文件上傳,只需要將頁面修改為多個文件上傳項,將方法參數MultipartFile類型修改為MultipartFile[]即可

    @RequestMapping(value = {"/qq19"})@ResponseBodypublic  void method19(String name, MultipartFile[] multipartFiles){System.out.println(name);try {for (MultipartFile multipartFile : multipartFiles) {multipartFile.transferTo(new File("e://"+multipartFile.getOriginalFilename()));}} catch (IOException ioException) {ioException.printStackTrace();}<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>hhhh</title>
</head>
<body><form action="${pageContext.request.contextPath}/qq19" method="post" enctype="multipart/form-data">名稱 <input type="text" name="name"><br/>文件1<input type="file" name="multipartFile"><br/>文件2<input type="file" name="multipartFile"><br/><input type="submit" value="提交">
</form></body>
</html>

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

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

相關文章

Maven+eclipse快速入門

1.eclipse下載 在無外網情況下&#xff0c;無法通過eclipse自帶的help-install new software輸入url來獲取maven插件&#xff0c;因此可以用集成了maven插件的免安裝eclipse(百度一下有很多)。 2.jdk下載以及環境變量配置 JDK是向前兼容的&#xff0c;可在Eclipse上選擇編譯器版…

源碼閱讀中的收獲

最近在做短視頻相關的模塊&#xff0c;于是在看 GPUImage 的源碼。其實有一定了解的伙伴一定知道 GPUImage 是通過 addTarget 鏈條的形式添加每一個環節。在對于這樣的設計贊嘆之余&#xff0c;想到了實際開發場景下可以用到的場景&#xff0c;借此分享。 我們的項目中應該有很…

馬爾科夫鏈蒙特卡洛_蒙特卡洛·馬可夫鏈

馬爾科夫鏈蒙特卡洛A Monte Carlo Markov Chain (MCMC) is a model describing a sequence of possible events where the probability of each event depends only on the state attained in the previous event. MCMC have a wide array of applications, the most common of…

PAT乙級1012

題目鏈接 https://pintia.cn/problem-sets/994805260223102976/problems/994805311146147840 題解 就比較簡單&#xff0c;判斷每個數字是哪種情況&#xff0c;然后進行相應的計算即可。 下面的代碼中其實數組是不必要的&#xff0c;每取一個數字就可以直接進行相應計算。 // P…

我如何在昌迪加爾大學中心組織Google Hash Code 2019

by Neeraj Negi由Neeraj Negi 我如何在昌迪加爾大學中心組織Google Hash Code 2019 (How I organized Google Hash Code 2019 at Chandigarh University Hub) This is me !!! Neeraj Negi — Google HashCode Organizer這就是我 &#xff01;&#xff01;&#xff01; Neeraj …

leetcode 665. 非遞減數列(貪心算法)

給你一個長度為 n 的整數數組&#xff0c;請你判斷在 最多 改變 1 個元素的情況下&#xff0c;該數組能否變成一個非遞減數列。 我們是這樣定義一個非遞減數列的&#xff1a; 對于數組中所有的 i (0 < i < n-2)&#xff0c;總滿足 nums[i] < nums[i 1]。 示例 1: …

django基于存儲在前端的token用戶認證

一.前提 首先是這個代碼基于前后端分離的API,我們用了django的framework模塊,幫助我們快速的編寫restful規則的接口 前端token原理: 把(token加密后的字符串,keyname)在登入后發到客戶端,以后客戶端再發請求,會攜帶過來服務端截取(token加密后的字符串,keyname),我們再利用解密…

數據分布策略_有效數據項目的三種策略

數據分布策略Many data science projects do not go into production, why is that? There is no doubt in my mind that data science is an efficient tool with impressive performances. However, a successful data project is also about effectiveness: doing the righ…

cell 各自的高度不同的時候

1, cell 根據文字、圖片等內容&#xff0c;確定自己的高度。每一個cell有自己的高度。 2&#xff0c;tableView 初始化 現實的時候&#xff0c;不是從第一個cell開始顯示&#xff0c;&#xff08;從第二個&#xff1f;&#xff09;&#xff0c;非非正常顯示。 a:cell 的高度問題…

leetcode 978. 最長湍流子數組(滑動窗口)

當 A 的子數組 A[i], A[i1], …, A[j] 滿足下列條件時&#xff0c;我們稱其為湍流子數組&#xff1a; 若 i < k < j&#xff0c;當 k 為奇數時&#xff0c; A[k] > A[k1]&#xff0c;且當 k 為偶數時&#xff0c;A[k] < A[k1]&#xff1b; 或 若 i < k < j&…

spring boot源碼下載地址

github下載&#xff1a; https://github.com/spring-projects/spring-boot/tree/1.5.x git地址&#xff1a; https://github.com/spring-projects/spring-boot.git 因為項目中目前使用的就是spring boot 1.5.19版本&#xff0c;因此這里先研究spring boot 1.5版本源碼.轉載于:h…

java基礎學習——5、HashMap實現原理

一、HashMap的數據結構 數組的特點是&#xff1a;尋址容易&#xff0c;插入和刪除困難&#xff1b;而鏈表的特點是&#xff1a;尋址困難&#xff0c;插入和刪除容易。那么我們能不能綜合兩者的特性&#xff0c;做出一種尋址容易&#xff0c;插入刪除也容易的數據結構&#xff1…

看懂nfl定理需要什么知識_NFL球隊為什么不經常通過?

看懂nfl定理需要什么知識Debunking common NFL myths in an analytical study on the true value of passing the ball在關于傳球真實價值的分析研究中揭穿NFL常見神話 Background背景 Analytics are not used enough in the NFL. In a league with an abundance of money, i…

Docker初學者指南-如何創建您的第一個Docker應用程序

您是一名開發人員&#xff0c;并且想要開始使用Docker&#xff1f; 本文是為您準備的。 (You are a developer and you want to start with Docker? This article is made for you.) After a short introduction on what Docker is and why to use it, you will be able to cr…

mybatis if-else(寫法)

mybaits 中沒有else要用chose when otherwise 代替 范例一 <!--批量插入用戶--> <insert id"insertBusinessUserList" parameterType"java.util.List">insert into business_user (id , user_type , user_login )values<foreach collection…

spring—攔截器和異常

SpringMVC的攔截器 SpringMVC攔截器-攔截器的作用 Spring MVC 的攔截器類似于 Servlet 開發中的過濾器 Filter&#xff0c;用于對處理器進行預處理和后處理。 將攔截器按一定的順序聯結成一條鏈&#xff0c;這條鏈稱為攔截器鏈&#xff08;InterceptorChain&#xff09;。在…

29/07/2010 sunrise

** .. We can only appreciate the miracle of a sunrise if we have waited in the darkness .. 人們在黑暗中等待著&#xff0c;那是期盼著如同日出般的神跡出現 .. 附&#xff1a;27/07/2010 sunrise ** --- 31 July 改動轉載于:https://www.cnblogs.com/orderedchaos/archi…

密度聚類dbscan_DBSCAN —基于密度的聚類方法的演練

密度聚類dbscanThe idea of having newer algorithms come into the picture doesn’t make the older ones ‘completely redundant’. British statistician, George E. P. Box had once quoted that, “All models are wrong, but some are useful”, meaning that no model…

node aws 內存溢出_在AWS Elastic Beanstalk上運行生產Node應用程序的現實

node aws 內存溢出by Jared Nutt賈里德努特(Jared Nutt) 在AWS Elastic Beanstalk上運行生產Node應用程序的現實 (The reality of running a production Node app on AWS Elastic Beanstalk) 從在AWS的ELB平臺上運行生產Node應用程序兩年的經驗教訓 (Lessons learned from 2 y…

Day2-數據類型

數據類型與內置方法 數據類型 數字字符串列表字典元組集合字符串 1.用途 用來描述某個物體的特征&#xff1a;姓名&#xff0c;性別&#xff0c;愛好等 2.定義方式 變量名 字符串 如&#xff1a;name huazai 3.常用操作和內置方法 1.按索引取值&#xff1a;&#xff08;只能取…