你真的懂@ResponseBody和@RequestBody嗎?


你真的懂@ResponseBody和@RequestBody嗎?

簡介

Response、Request是指的HTTP協議的請求和響應。我們知道一個請求有請求頭,請求行、請求體三部分組成。響應也是如此,分為響應頭,響應行和響應體三部分。Body在這里指的就是“體”。@ResponseBody和@RequestBody都是SpringMVC的一個注解。我們先從@ResponseBody開始說起。

@ResponseBody

其一般加在web層的方法上,作用是將加入此注解的方法返回的對象序列化,放在本次響應的響應體中傳遞給前端。它可以將數據序列化為JSON、XML返回,不過我們一般用的都是JSON類型,用作AJAX調用。

僅使用@RequestMapping注解時,我們可以通過return一個字符串用來跳轉頁面。但是加入了@ResponseBody以后返回的字符串也會被解析為json格式的數據,無法進行跳轉。

@RestController

SpringMVC提供了一個神奇的注解@RestController,我們可以先看一下它的源碼。

/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Controller;

/**
 * A convenience annotation that is itself annotated with
 * {@link Controller @Controller} and {@link ResponseBody @ResponseBody}.
 * <p>
 * Types that carry this annotation are treated as controllers where
 * {@link RequestMapping @RequestMapping} methods assume
 * {@link ResponseBody @ResponseBody} semantics by default.
 *
 * <p><b>NOTE:</b> {@code @RestController} is processed if an appropriate
 * {@code HandlerMapping}-{@code HandlerAdapter} pair is configured such as the
 * {@code RequestMappingHandlerMapping}-{@code RequestMappingHandlerAdapter}
 * pair which are the default in the MVC Java config and the MVC namespace.
 *
 * @author Rossen Stoyanchev
 * @author Sam Brannen
 * @since 4.0
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 * @since 4.0.1
	 */
	@AliasFor(annotation = Controller.class)
	String value() default "";

}

我們可以看到,其包含了@Controller、@ResponseBody等幾個注解,我們知道@Controller是加在web層的類上的,@RestController同樣也是加在web層的類上,其作用就是為該類中的所有方法都默認加上@ResponseBody,就不用每個方法都單獨加了,這也是對RESTful風格的實現。

@RequestBody

@RequestBody與@ResponseBody相反,是將請求體中的數據拿出,使用適合的 HttpMessageConverter 將請求體寫入某個對象。

作用:

1) 該注解用於讀取Request請求的body部分數據,使用系統默認配置的HttpMessageConverter進行解析,然后把相應的數據綁定
    到要返回的對象上; 
2) 再把HttpMessageConverter返回的對象數據綁定到 controller中方法的參數上。

使用時機:

A) GET、POST方式提時, 根據request header Content-Type的值來判斷:

application/x-www-form-urlencoded, 可選(即非必須,因為這種情況的數據@RequestParam, @ModelAttribute

也可以處理,當然@RequestBody也能處理);
multipart/form-data, 不能處理(即使用@RequestBody不能處理這種格式的數據);
其他格式, 必須(其他格式包括application/json, application/xml等。這些格式的數據,必須使用@RequestBody來處理);

B) PUT方式提交時, 根據request header Content-Type的值來判斷:

application/x-www-form-urlencoded, 必須;multipart/form-data, 不能處理;其他格式, 必須;
說明:request的body部分的數據編碼格式由header部分的Content-Type指定;

例如:

@RequestMapping(value = "user/login")
@ResponseBody
// 將ajax(datas)發出的請求寫入 User 對象中
public User login(@RequestBody User user) {   
// 這樣就不會再被解析為跳轉路徑,而是直接將user對象寫入 HTTP 響應正文中
    return user;    
}

可以通俗的理解為@RequestBody是解析請求中的json或者xml,放入后台用於接收的POJO參數中。但是其不支持一些特定類型的內容。

參考博客:CSDN鏈接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM