ResponseEntity返回数据、状态、头部信息

版权声明:本文为博主原创文章,转载请注明链接 https://blog.csdn.net/sswqzx/article/details/84938223

ResponseEntity :标识整个http相应:状态码、头部信息、响应体内容(spring)

@ResponseBody:加在请求处理方法上,能够处理方法结果值作为http响应体(springmvc)

@ResponseStatus:加在方法上、返回自定义http状态码(spring)

ResponseEntity 事例:



import com.baidu.item.pojo.Category;
import com.baidu.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @ Author     :ShaoWei Sun.
 * @ Date       :Created in 10:37 2018/12/11
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("list")
    public ResponseEntity<List<Category>> queryByParentId(@RequestParam(value = "pid",defaultValue = "0") Long pid){
        List<Category> categories = this.categoryService.queryByParentId(pid);
        if (categories != null && 0!=categories.size()) {
            //返回数据就为http响应体内容
            return ResponseEntity.ok(categories);
        }
        //返回响应状态码204
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }}

猜你喜欢

转载自blog.csdn.net/sswqzx/article/details/84938223
今日推荐