- 2068 Chaitra (old course) · 6 marks
Server-side programming and Java Servlet
Short answer
Server-side programming runs code on the server to generate dynamic responses, accessing databases and sending only HTML to the browser. A servlet is a Java class loaded once in a container; init() runs once, service() calls doGet or doPost per request in a thread, and destroy() runs at shutdown.
What is server-side programming? Explain how a Java Servlet works.
Server-side programming
Server-side programming is writing programs that run on the web server to process client requests and generate dynamic responses. The server executes the code, accesses databases and files, applies business logic and sends only the resulting HTML (or JSON/XML) to the browser. Examples: PHP, JSP/Servlets, ASP.NET, Python (Django/Flask), Node.js. Uses: login and sessions, database-driven pages, form processing, e-commerce.
Java Servlet
A servlet is a Java class that runs inside a servlet container (web container) such as Apache Tomcat or Jetty. It extends HttpServlet and handles HTTP requests. Unlike CGI, a servlet is loaded once and each request runs in a lightweight thread, so it is fast and portable.
How a servlet works (life cycle)
- The browser sends an HTTP request to a URL mapped to the servlet.
- The web server passes it to the servlet container.
- Loading and
init(): On the first request (or at startup) the container loads the class, creates one instance and callsinit()once. service(): For every request the container createsHttpServletRequestandHttpServletResponseobjects and callsservice()in a new thread, which callsdoGet()ordoPost().- The servlet reads parameters, may use JDBC to access the database, and writes the response through
response.getWriter(). - The container sends the response back to the browser.
destroy(): When the container shuts down or unloads the servlet,destroy()is called once to release resources.
Browser -> Web server -> Servlet container
init() (once)
service() -> doGet()/doPost() (per request)
destroy() (once)
Browser <- response <------+
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Hello, " + req.getParameter("name") + "</h1>");
}
}
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Short note: Server side programming · Web Technology, chapter 3
- Client-side versus server-side scripting · Web Technology, chapter 3 · asked 3×
- Server side languages and multi-tier architecture · Web Technology, chapter 3
- Java simulation of single server queue · Simulation and Modeling, chapter 9 · asked 5×
- XML and JavaScript for client-side web apps · Internet and Intranet, chapter 6