Hackforge Academy

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

🚀 Learn Spring Boot with real-world projects

💡 Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
⚛️

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
☕

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community