Category: java
Exception handling and servlet mvc
Published on 30 Sep 2026
Explanation
Servlet applications should handle exceptions gracefully instead of exposing technical error details to users.
Code:
try {
// Business operation
} catch (Exception e) {
response.sendError(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR
);
}
Explanation
web.xml can define an error page for a particular HTTP status or exception type.
Code:
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
Explanation
In MVC architecture, the Servlet acts as the Controller, Java classes represent the Model, and JSP represents the View.
Code:
Browser | v Servlet Controller | v Model / Service / DAO | v Database | v JSP View | v Browser
Explanation
The controller receives the request, calls the service layer, stores the result as a request attribute, and forwards to the JSP.
Code:
protected void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
List<User> users = userService.findAll();
req.setAttribute("users", users);
req.getRequestDispatcher("users.jsp")
.forward(req, resp);
}
Explanation
Keeping business logic outside the servlet makes the application easier to maintain and test.
Code:
Servlet ↓ Service ↓ DAO ↓ Database JSP ↑ Request Attributes ↑ Servlet