I have the jetty server started this way by the sample code below where I have written my own errorHandler class. Through some few research, I got some information here. But it seems not enough to get me what I want. The name of the class that I set to be called by the server is HandleClient.
So if error 404 occurs, it display {"message":"HTTP error 404"}
. the program works fine anyway But the response is in text/plain format.
My Problem is: How can I configure the class to format and display the error in MIME MediaType: application/json.
I have had sleepless nights on this. Will be very grateful to all helps.
public class MVCPattern{
public MVCPattern(){
}
public static void main(String args[]) throws JSONException, IOException{
MVCPattern mvcPattern = new MVCPattern();
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(9000);
jettyServer.setHandler(context);
context.setErrorHandler(new ErrorHandler());
// default error handler for resources out of "context" scope
jettyServer.addBean(new ErrorHandler());
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
// Tells the Jersey Servlet which REST service/class to load.
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
HandleClient.class.getCanonicalName() );
try {
jettyServer.start();
jettyServer.join();
} catch (Exception ex) {
Logger.getLogger(HandleClient.class.getName()).log(Level.SEVERE, null, ex);
} finally {
jettyServer.destroy();
}
}
/**
* Dummy error handler that disables any error pages or jetty related messages and returns our
* ERROR status JSON with plain HTTP status instead. All original error messages (from our code) are preserved
* as they are not handled by this code.
*/
static class ErrorHandler extends ErrorPageErrorHandler {
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter()
.append("{\"message\":\"HTTP error ")
.append(String.valueOf(response.getStatus()))
.append("\"}");
}
}
}