0% found this document useful (0 votes)
12 views5 pages

Servlet API & Deployment

Servlets are Java classes that enable dynamic web content generation by responding to HTTP requests within a managed web container. They handle request processing, execute business logic, generate dynamic responses, interact with databases, and control page navigation, often following the MVC architecture. Best practices include separating concerns, validating input, and using JSP for presentation logic to maintain scalability and maintainability.

Uploaded by

ssw947473
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views5 pages

Servlet API & Deployment

Servlets are Java classes that enable dynamic web content generation by responding to HTTP requests within a managed web container. They handle request processing, execute business logic, generate dynamic responses, interact with databases, and control page navigation, often following the MVC architecture. Best practices include separating concerns, validating input, and using JSP for presentation logic to maintain scalability and maintainability.

Uploaded by

ssw947473
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Servlet API & Deployment

Servlets – Dynamic Web Components


Why Servlets?
A plain web server (e.g., Apache HTTP Server, Nginx) can only serve static
content such as:

HTML files
CSS stylesheets
JavaScript files
Images, videos, and other media

To enable dynamic behavior—where content is generated at runtime based on user


input, database state, or business rules—we use Servlets.

✅ Servlets bridge the gap between static web delivery and dynamic
application logic.

What is a Servlet?
A Servlet is a Java class that:

Extends HttpServlet (or implements Servlet interface)


Does not have a main() method
Runs inside a Web Container (e.g., Tomcat, Jetty)
Is managed entirely by the container (lifecycle, threading, resource access)

📌 Key Point: A servlet is not a standalone program—it’s a component that


responds to HTTP requests within a managed environment.
Core Responsibilities of a Servlet
1. Request Processing
Receives and parses HTTP requests via the HttpServletRequest object.
Extracts:
Request parameters ( ?name=value )
Headers (e.g., User-Agent , Content-Type )
Cookies
Session data
HTTP method (GET, POST, PUT, DELETE, etc.)

1 String username = request.getParameter("username");


2 String userAgent = request.getHeader("User-Agent");

2. Business Logic Execution


Implements application-specific logic, such as:
Input validation
Authentication & authorization
Calculations (e.g., tax, pricing)
Orchestration of service-layer calls
Often delegates complex operations to service classes or business-tier
components (separation of concerns).

⚠️ Best Practice: Keep servlets lean—avoid embedding heavy logic directly.


Use them as controllers in an MVC architecture.

3. Dynamic Response Generation


Constructs custom responses based on request context and application state.
Can generate multiple content types:
HTML (for web pages)
JSON (for REST APIs)
XML (for legacy integrations)
Plain text, PDFs, images, etc.
1 response.setContentType("application/json");
2 PrintWriter out = response.getWriter();
3 out.println("{\"status\": \"success\", \"user\": \"" + username +
"\"}");

4. Database Interaction (via DAO Layer)


Coordinates with Data Access Objects (DAOs) to:
Query databases
Insert/update/delete records
Handle transactions (often delegated to service/DAO layers)
Never accesses the database directly in well-designed apps—uses DAOs for
abstraction and testability.

1 UserDAO dao = new UserDAO();


2 User user = dao.findByEmail(email);

5. Page Navigation & Flow Control


Controls user navigation after processing:
Forward to a JSP (server-side, same request):
1 request.getRequestDispatcher("/result.jsp").forward(request,
response);

Redirect to another URL (client-side, new request):


1 response.sendRedirect("dashboard.html");

Enables MVC pattern: Servlet (Controller) → processes logic → forwards to JSP


(View).

Servlet in Context: MVC Architecture


graph TD
A[Client
(Browser, Mobile App)] -->|HTTP/REST| B[Application Server]
B --> C[Web Container
(Servlets, JSP, JSF)]
B --> D[EJB Container
(Business Logic)]
B --> E[Persistence Layer
(JPA/Hibernate)]
B --> F[Security Domain
(Users, Roles)]
B --> G[Transaction Manager]
E --> H[(Database)]
D -->|Uses| E
C -->|Calls| D

Servlet = Controller: Handles input, invokes logic, selects view.


JSP = View: Renders dynamic HTML using data from request/session.
DAO/Service = Model: Encapsulates data and business rules.

Key Characteristics

Feature Description
Language Java

Execution Environment Web Container (e.g., Tomcat)

Entry Point doGet() , doPost() , etc. (not main() )

Concurrency Single instance, multi-threaded

State Management Uses HttpSession , cookies, or URL rewriting

Configuration Via web.xml or annotations ( @WebServlet )

Common Use Cases


User login/registration forms
RESTful web services (returning JSON/XML)
Shopping cart processing
Form data validation and submission
File upload/download handlers
Dashboard data aggregation

Best Practices
1. Separate concerns: Use servlets for control flow, not business logic.
2. Validate input: Always sanitize and validate request parameters.
3. Handle exceptions: Use try-catch or container-managed error pages.
4. Avoid instance variables: Ensure thread safety.
5. Use JSP for views: Keep presentation logic out of servlets.

💡 Remember: A servlet’s job is to coordinate, not to do everything. Delegate


to specialized layers for maintainability and scalability.

You might also like