【问题标题】:how can return json using response.senderror如何使用 response.senderror 返回 json
【发布时间】:2013-12-17 16:13:05
【问题描述】:

在我的应用程序中,我使用 springMVC 和 tomcat,我的控制器返回对象,但是当出现问题时,我只想返回一些内容为 json 的字符串消息,所以我使用 response.error,但它不起作用,返回是一个html。 我的控制器:

@RequestMapping(value = "{id}/{name}" ,method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)

public @ResponseBody UserBean  login(@PathVariable String id,@PathVariable("name") String userName,
        @RequestHeader(value = "User-Agent") String user_agen,
        @CookieValue(required = false) Cookie userId,
        HttpServletRequest request,HttpServletResponse response,@RequestBody UserBean entity
        ) throws IOException {
     System.out.println("dsdsd");
     System.out.print(userName);

     response.setContentType( MediaType.APPLICATION_JSON_VALUE);
     response.sendError(HttpServletResponse.SC_BAD_REQUEST, "somethind wrong");
     return  null;

【问题讨论】:

    标签: spring-mvc


    【解决方案1】:

    根据HttpServletReponse#sendError 方法的Javadoc:

    使用指定状态向客户端发送错误响应。 该 服务器默认创建响应看起来像 包含指定消息的 HTML 格式的服务器错误页面, 将内容类型设置为“text/html”, 留下 cookie 和其他 标题未修改...

    因此,sendError 将使用您提供的消息生成 HTML 错误页面,并将内容类型覆盖为 text/html

    由于客户端期望 JSON 响应,您最好使用 UserBean 上的字段手动设置响应代码和消息 - 假设它可以支持它。然后将其序列化为您的客户端 Javascript 可以评估的 JSON 响应。

    @RequestMapping(value = "{id}/{name}" ,method=RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody UserBean  login(@PathVariable String id,@PathVariable("name") String userName,
            @RequestHeader(value = "User-Agent") String user_agen,
            @CookieValue(required = false) Cookie userId,
            HttpServletRequest request,HttpServletResponse response,@RequestBody UserBean entity
            ) throws IOException {
         System.out.println("dsdsd");
         System.out.print(userName);
    
         response.setContentType( MediaType.APPLICATION_JSON_VALUE);
         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    
         UserBean userBean = new UserBean();
         userBean.setError("something wrong"); // For the message
         return userBean;
    

    还可以选择使用 Tomcat 属性org.apache.coyote. USE_CUSTOM_STATUS_MSG_IN_HEADER,它将消息放入自定义响应标头中。请参阅this postthe Tomcat docs 了解更多信息。

    【讨论】:

    • 谢谢,这是一个很好的解决方案。但问题是所有响应 bean 都必须有一个字段名称错误,它不是那么友好。好吧,这仍然是一个成功的解决方案。
    • 也许有一个基类UserBean(和其他bean)继承自它可能包含error 属性?这将节省重复。或者,我在答案中提到的 USE_CUSTOM_STATUS_MSG_IN_HEADER Tomcat 特定属性也有可能。那么你就不需要error 属性了。
    猜你喜欢
    • 2017-07-20
    • 1970-01-01
    • 2017-07-20
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多