Servlets: Basics, Syntax, and Examples
1. What is a Servlet?
A Servlet is a Java class used to extend the capabilities of servers that host applications accessed via a
request-response model. Servlets can respond to any request but are commonly used for extending web
servers.
They run on a web container such as Apache Tomcat and follow the servlet lifecycle.
2. Simple Servlet Program
import java.io.*;
import javax.servlet.*;
public class SimpleServlet extends GenericServlet {
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Hello from Servlet</h1>");
}
}
Output:
<h1>Hello from Servlet</h1>
3. Servlet Lifecycle Methods
- init(): Called once during servlet initialization
- service(): Called for every client request
- destroy(): Called before servlet is removed from service
Code: Servlet Lifecycle Example
public class LifeCycleServlet extends GenericServlet {
public void init() {
System.out.println("Init called");
}
Servlets: Basics, Syntax, and Examples
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("Service called");
}
public void destroy() {
System.out.println("Destroy called");
}
}
Output:
Service called
(also logs: Init called / Destroy called)
4. HttpServlet with doGet()
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<p>This is a GET response</p>");
}
}
Output:
<p>This is a GET response</p>
5. Reading Request Parameters
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
String user = req.getParameter("username");
res.getWriter().println("User is: " + user);
}
Servlets: Basics, Syntax, and Examples
Output:
User is: [entered_username]
6. ServletConfig Example
public void init(ServletConfig config) throws ServletException {
String driver = config.getInitParameter("driver");
System.out.println("Driver name: " + driver);
}
Output:
Driver name: com.mysql.jdbc.Driver (example value from web.xml)
7. ServletContext Example
ServletContext context = getServletContext();
String appName = context.getInitParameter("applicationName");
out.println("App Name: " + appName);
Output:
App Name: MyWebApp (example value)
8. RequestDispatcher Example
RequestDispatcher rd = request.getRequestDispatcher("nextServlet");
rd.forward(request, response);
Output:
Output of nextServlet is shown (control transferred)
9. Session Tracking Using HttpSession
HttpSession session = request.getSession();
session.setAttribute("user", "John");
String user = (String) session.getAttribute("user");
out.println("Logged in as: " + user);
Servlets: Basics, Syntax, and Examples
Output:
Logged in as: John
10. Sending and Reading Cookies
Cookie cookie = new Cookie("username", "john123");
response.addCookie(cookie);
Cookie[] cookies = request.getCookies();
for (Cookie c : cookies) {
if (c.getName().equals("username")) {
out.println("Cookie found: " + c.getValue());
}
}
Output:
Cookie found: john123
11. Servlet Filter Example
public class MyFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain
chain) throws IOException, ServletException {
PrintWriter out = response.getWriter();
out.println("Filter applied before servlet");
chain.doFilter(request, response);
}
}
Output:
Filter applied before servlet
Servlet output...
12. JDBC with Servlets Example
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"pass");
Servlets: Basics, Syntax, and Examples
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
out.println("User: " + rs.getString("username"));
}
Output:
User: nikhil
User: rohit ... (fetched from DB)