HttpServletResponse 的使用

Posted lshan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpServletResponse 的使用相关的知识,希望对你有一定的参考价值。

 

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

 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);
    }

 

以上是关于HttpServletResponse 的使用的主要内容,如果未能解决你的问题,请参考以下文章

HttpServletResponse sendRedirect 永久

HelloServlet类继承HttpServlet利用HttpServletResponse对象

Servlet响应httpServletResponse

Servlet响应httpServletResponse

Servlet响应httpServletResponse

Servlet响应httpServletResponse