SpringMVC之使用ResponseEntity,java接口返回HttpStatus

Post请求

一般情况下,在非必须的情况下,使用Jquery实现post请求,而后台返回一般都需要手动封装ResponseUtil,和使用@ResponseBody注解来实现返回。然而我们书上学到的关于Spring的知识只是我们日常使用频率较高的,Spring还提供了很多工具与方法,可以方便与快捷实现原有的功能。

后台代码:

@RequestMapping("/responseEntity.do")
    public ResponseEntity<Map<String,Object>> responseEntity(){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("message", "Hello Wrold");
        return new ResponseEntity(map, HttpStatus.OK);
    }

当然,使用的时候可以对ResponseEntity进行重写,如

    @RequestMapping(value = "/getAAA",method=RequestMethod.POST)
    @ResponseBody
    public BaseResponseEntity<List<Restype>> getResTypeList2() {
        List<Restype> list = resBaseService.selectSSS();
        return new BaseResponseEntity("resTypeList", list, HttpStatus.OK,null);
    }


------------api方法改写成4个参数,如下--------------------
/**
* @param name,返回时的data结果集的name,如下面的resTypeList
* {
“code”:”调用结果”,
“msg”:”执行结果详情”,
“resTypeList”: {}
}
* */
public BaseResponseEntity(String name,T body, HttpStatus code,String msg) {
super(body);
this.code = code;
this.msg = (StringUtils.isNotEmpty(msg)) ? msg : "";
if(StringUtils.isNotEmpty(name)){
map.put("name", body);
}
}
 
原文地址:https://www.cnblogs.com/xiaoliu66007/p/9962201.html