how can return json using response.senderror
spring-mvc
Solution
According to the Javadoc for the `HttpServletReponse#sendError` method:
Sends an error response to the client using the specified status. The server defaults to creating the response to look like an HTML-formatted server error page containing the specified message, setting the content type to "text/html", leaving cookies and other headers unmodified...
So `sendError` will generate an HTML error page using the message that you supplied and will override the content type to `text/html`.
Since the client end is expecting a JSON response, you may be better to manually set the response code and the message yourself using fields on your `UserBean` - assuming it can support it. That will then be serialized to a JSON response that your clientside Javascript can evaluate.
@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;
There is also the option of using the Tomcat property `org.apache.coyote. USE_CUSTOM_STATUS_MSG_IN_HEADER` which will place the message into a custom response header. See this post and the Tomcat docs for more info.
Problem
In my app,I use springMVC and tomcat,my controller return object,but when something wrong,I only want return some string message with content tye json,so I use response.error, but it not work,the return is a html. my controller: ``` @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; ```