如何使用response.senderror返回json


问题内容

在我的应用程序中,我使用springMVC和tomcat,我的控制器返回对象,但是当出现问题时,我只想返回内容为tye
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;

问题答案:

根据Javadoc的HttpServletReponse#sendError方法:

使用指定的状态将错误响应发送到客户端。 服务器默认创建响应,使其看起来像一个包含指定消息的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,该属性会将消息放入自定义响应标头中。