By default, jetty display error message like below.
It is security risk to expose server details like name,
version etc., to outside world. So we need to override this default behavior.
We can override this behavior by extending ‘ErrorPageErrorHandler’
class.
static class ErrorHandler extends ErrorPageErrorHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter() .append("{\"status\":\"ERROR\",\"message\":\"HTTP ") .append(String.valueOf(response.getStatus())).append("\"}"); } }
Add the custom handler to server by using addBean method.
server.addBean(new
ErrorHandler());
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; public HelloServlet() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hello from HelloServlet</h1>"); } }
import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ErrorPageErrorHandler; import org.eclipse.jetty.servlet.ServletHandler; public class HelloWorld { public static void main(String[] args) throws Exception { Server server = new Server(8080); ServletHandler handler = new ServletHandler(); server.setHandler(handler); handler.addServletWithMapping(HelloServlet.class, "/hello"); server.addBean(new ErrorHandler()); server.start(); server.join(); } static class ErrorHandler extends ErrorPageErrorHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter() .append("{\"status\":\"ERROR\",\"message\":\"HTTP ") .append(String.valueOf(response.getStatus())).append("\"}"); } } }
Run above application and hit the url ‘http://localhost:8080////’,
you will get custom error message.
No comments:
Post a Comment