A good servlet does not return the same response for every failure. Missing parameters usually mean 400, unauthorized access means 401 or 403, missing resources mean 404, and unexpected server failures mean 500.
Logs should help developers debug without leaking secrets. Include request path, user ID when safe, correlation ID, and exception stack trace. Avoid passwords, tokens, full card numbers, and private form values.
Production users should see helpful error pages, not stack traces. Error pages should explain what happened in plain language and provide navigation back to a safe page.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
String id = request.getParameter("id");
if (id == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing id");
return;
}
response.getWriter().println("Loading item " + id);
} catch (Exception ex) {
log("Failed to load item", ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/views/errors/404.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/WEB-INF/views/errors/500.jsp</location>
</error-page>
try {
productService.load(productId);
} catch (ProductNotFoundException ex) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Product not found");
} catch (ValidationException ex) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
} catch (Exception ex) {
log("Unexpected product error", ex);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
<%@ page isErrorPage="true" %>
<h1>Something went wrong</h1>
<p>Please try again or contact support if the issue continues.</p>
<a href="${pageContext.request.contextPath}/">Go home</a>
Let a configured error handler or container error page produce the response after the failure is logged.
It exposes implementation details and does not provide a useful recovery message.
No. Once output is committed, the status and headers can no longer be replaced reliably.
Practice, interview questions, and compiler links for Servlet.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.