如何使用response.senderror返回json

如何使用response.senderror返回json,第1张

如何使用response.senderror返回json

根据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
,该属性会将消息放入自定义响应标头中。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4962266.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-13
下一篇 2022-11-13

发表评论

登录后才能评论

评论列表(0条)

保存