场景:避免一些简单的响应数据,需要手动封装放回对象

 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "haha 系统崩了");

 

public class OrderController {

    private static final Logger LOGGER = getLogger(OrderController.class);

    @Autowired
    private CommandGateway commandGateway;

    @Autowired
    private HttpServletResponse response;

    @RequestMapping(method = RequestMethod.POST)
    public void create(@RequestBody(required = true) JSONObject input){
        LOGGER.info(input.toJSONString());

        int responseCode = HttpServletResponse.SC_BAD_REQUEST;

        if(input.containsKey("username") && input.containsKey("products")){
            String username = input.getString("username");
            JSONArray products = input.getJSONArray("products");
            if(!StringUtils.isEmpty(username) && products.size()>0){
                Map<String, Integer> map = new HashMap<>();
                CreateOrderCommand command = new CreateOrderCommand(username, map);
                for(Object each:products){
                    JSONObject o = (JSONObject)each;
                    if(!o.containsKey("id") || !o.containsKey("number"))
                        return;
                    map.put(o.getString("id"), o.getInteger("number"));
                }
                commandGateway.sendAndWait(command);
                responseCode = HttpServletResponse.SC_CREATED;
            }
        }

        response.setStatus(responseCode);
    }

 

posted on 2019-05-20 12:03  lshan  阅读(909)  评论(0编辑  收藏  举报