使用ResponseEntity进行返回json数据

在最近的项目中,与上位机进行数据传输时,上位机需要服务器的响应得知服务器是否正常运行,数据是否正常发送

在最近的调试中我使用ResponseEntity<Map<String,Object>>作为返回对象,response响应一个json,{"massage","success"}

ResponseEntity可以定义返回的HttpStatus(状态码)和HttpHeaders(消息头:请求头和响应头)

如果不使用ResponseEntity,直接返回,则是直接跳转到对应return字符串的页面

部分代码:

    public ResponseEntity<Map<String,Object>> save(HttpServletRequest request) {

//中间为接收数据代码
        // 创建对象
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("message","success");
//        System.out.println("测试返回......");
        // 转换
//        ObjectMapper mapper = new ObjectMapper();
//        String str = null;
//        try {
//            str = mapper.writeValueAsString(map);
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//        }
        return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
    }
原文地址:https://www.cnblogs.com/flypig666/p/11729771.html