响应@ResponseBody

一、响应数据

响应@ResponseBody_第1张图片

响应@ResponseBody_第2张图片

二、统一响应结果

响应@ResponseBody_第3张图片

因为不便管理,难以维护

所以在pojo中引入了一个Result.java封装类,这样响应结果比较统一,便于维护和管理

package com.itheima.pojo;

/**
 * 统一响应结果封装类
 */
public class Result {
    private Integer code ;//1 成功 , 0 失败
    private String msg; //提示信息
    private Object data; //数据 data

    public Result() {
    }
    public Result(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }

    public static Result success(Object data){
        return new Result(1, "success", data);
    }
    public static Result success(){
        return new Result(1, "success", null);
    }
    public static Result error(String msg){
        return new Result(0, msg, null);
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}

ResponseController.java

package com.itheima.controller;

import com.itheima.pojo.Address;
import com.itheima.pojo.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class ResponseController {
   @RequestMapping("/hello")
   public Result hello(){
      return Result.success("hello world~");
   }

   @RequestMapping("/getAddr")
   public Result getAddr(){
      Address address = new Address();
      address.setProvince("山东");
      address.setCity("济南");
      return Result.success(address);
   }

   @RequestMapping("/listAddr")
   public Result addAddr(){
      ArrayList list = new ArrayList();
      Address addr1 = new Address();
      addr1.setProvince("陕西");
      addr1.setCity("西安");
      Address addr2 = new Address();
      addr2.setProvince("广东");
      addr2.setCity("广州");
      list.add(addr1);
      list.add(addr2);
      return Result.success(list);
   }
}

@RestController中的@ResponseBody会将Result对象转为一个json格式的数据

小结

响应@ResponseBody_第4张图片

你可能感兴趣的:(2023javaweb,java,servlet,jvm)