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