當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringMVC实现PUT请求上传文件
生活随笔
收集整理的這篇文章主要介紹了
SpringMVC实现PUT请求上传文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在JQuery中,我們可以進行REST ful中delete和put的請求,但是在java EE標準中,默認只有在POST請求的時候,servlet 才會通過getparameter()方法取得請求體中的相應的請求參數的數據。而PUT,delete請求的請求體中數據則默認不會被解析。
SpringMVC實現PUT,DELETE請求
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><servlet><servlet-name>dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:dispatcher-servlet.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcher</servlet-name><url-pattern>/</url-pattern></servlet-mapping><filter><filter-name>HiddenHttpMethodFilter</filter-name><filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class></filter><filter-mapping><filter-name>HiddenHttpMethodFilter</filter-name><servlet-name>dispatcher</servlet-name></filter-mapping>然后我們看源碼:
@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {String paramValue = request.getParameter(this.methodParam);if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {String method = paramValue.toUpperCase(Locale.ENGLISH);HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);filterChain.doFilter(wrapper, response);}else {filterChain.doFilter(request, response);}}或者在$.ajax中
function login() {$.ajax({type: "post",//請求方式url: "", //發送請求地址timeout: 30000,//超時時間:30秒data: {"username": $('#username').val(),"password": $("#password").val(),"_method": delete},dataType: "json",//設置返回數據的格式success: function (data) {console.log(data);},error: function () { //請求出錯的處理}});}然后我們就可以在后臺@RequestMapping(value = "", method = RequestMethod.PUT)注解中標識我們的方法,最后就可以成功地獲得數據。
SpringMVC實現PUT請求上傳文件
可是后來我又有遇到另外一個需求那就是修改的時候需要傳送文件到put方法中,于是這種方法就不可行了,但是我在HiddenHttpMethodFilter源碼中看到這樣一句話
* <p><b>NOTE: This filter needs to run after multipart processing in case of a multipart* POST request, due to its inherent need for checking a POST body parameter.</b>* So typically, put a Spring {@link org.springframework.web.multipart.support.MultipartFilter}* <i>before</i> this HiddenHttpMethodFilter in your {@code web.xml} filter chain.和MultipartFilter源碼中這樣的注釋
/*** Set the bean name of the MultipartResolver to fetch from Spring's* root application context. Default is "filterMultipartResolver".*/最后,就可以實現將文件上傳提交給put方法。
轉載于:https://www.cnblogs.com/morethink/p/6378015.html
總結
以上是生活随笔為你收集整理的SpringMVC实现PUT请求上传文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HTTP协议整理
- 下一篇: Coursera公开课-Machine_