java - How do I return a JSON response message and an HTTP error code from javax.servlet.filter doFilter method? -


i have created servlet filter our application processes rest requests. have annotated web.xml , created filter. filter works well, returns json text message. need return 405 http status code. when perform tests, , 1 fails, have simple printwriter prints error message:

public class myfilter implements filter {     @override     public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception {         httpservletresponse apiresponse = (httpservletresponse) response;         apiresponse.setcontenttype("application/json");         htmlout = apiresponse.getwriter();         mainerrorobject = new jsonobject();         if(true){             htmlout.println(mainerrorobject.tostring());         }         htmlout.close();     } } 

so, said, how return both json text message , http error code?

servletresponse implements httpservletresponse , has setstatus method, sets status code response.

setstatus

void setstatus(int sc)

sets status code response. method used set return status code when there no error (for example, status codes sc_ok or sc_moved_temporarily). if there error, , caller wishes invoke error-page defined in web application, senderror method should used instead. container clears buffer , sets location header, preserving cookies , other headers.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -