How unit 4 is examined
This unit covers servlets, JSP and Java multimedia (images, animation, audio); no recent paper has asked any of them, so learn the definition, lifecycle or method names, and one short program for each.
Servlets: Overview and Architecture, Setting Up the Apache Tomcat Server, Handling HTTP get Requests, Deploying a web Application, Multitier Applications, Using JDBC from a Servlet
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>A servlet is a Java class that runs inside a web server's container, such as Apache Tomcat, and answers client requests over HTTP by generating a dynamic response.</mark>
Architecture. The browser sends an HTTP request to the web server, the container passes it to the servlet, and the servlet builds the response, often after reading a database.
Browser --HTTP request--> Web server / Tomcat container --> Servlet --JDBC--> Database
Browser <--HTTP response-- Web server / Tomcat container <-- Servlet <-------- Database
Key points.
- A servlet extends
HttpServlet(packagejavax.servlet.http) and is managed entirely by the container, which creates one instance and serves many requests from separate threads. - The life cycle has three steps: the container calls
init()once when the servlet is loaded, callsservice()for every request (which dispatches todoGet()ordoPost()), and callsdestroy()once when the servlet is removed. - Servlets are faster than old CGI programs because a CGI program starts a new process for every request, whereas a servlet is loaded once and each request is only a new thread.
HttpServletRequestcarries the request data (parameters, headers) andHttpServletResponseis used to set the content type and write the reply through aPrintWriter.
Setting up Tomcat.
- Install the JDK and set the
JAVA_HOMEenvironment variable. - Unpack or install Apache Tomcat and start it with
bin/startup(startup.baton Windows). - Open
http://localhost:8080in a browser; the Tomcat home page shows that it is running. - Stop it with
bin/shutdown.
Handling HTTP get requests. A GET request sends parameters in the URL and is meant for reading data, so the servlet overrides doGet(). Query data is read with request.getParameter("name").
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Hello " + req.getParameter("user") + "</h1>");
}
} // GET /app/welcome?user=Ravi prints: Hello Ravi
Deploying a web application.
- Create the folder
webapps/myappwith aWEB-INFfolder inside it. - Put compiled classes in
WEB-INF/classesand libraries inWEB-INF/lib; put HTML and JSP pages in the application root. - Map the servlet in
WEB-INF/web.xmlwith a<servlet>element (name and class) and a<servlet-mapping>element (name and URL pattern). - Restart Tomcat, or pack the folder as a
.warfile and copy it intowebapps, and openhttp://localhost:8080/myapp/welcome.
Multitier applications. A multitier application divides work into layers: the client tier (browser), the middle tier (servlet or JSP with the business logic) and the data tier (database). Layers can change independently, and the browser never touches the database directly, which improves security and scalability.
Using JDBC from a servlet. The servlet loads the driver, opens a Connection, runs a query with a Statement or PreparedStatement, reads the ResultSet and writes the rows as HTML.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/college", "root", "pass");
PreparedStatement ps = con.prepareStatement("SELECT name FROM student WHERE id=?");
ps.setInt(1, Integer.parseInt(req.getParameter("id")));
ResultSet rs = ps.executeQuery();
while (rs.next()) out.println(rs.getString("name") + "<br>");
con.close();
Java Server Pages (JSP): Overview, First JSP Example, Implicit Objects, Scripting, Standard Actions, Directives
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>JavaServer Pages (JSP) is a server-side technology in which a page of HTML contains embedded Java code, and the container translates the page into a servlet and runs it to produce a dynamic web page.</mark>
Key points.
- A JSP suits presentation work because the designer writes normal HTML and adds Java only where content must be dynamic, whereas a servlet suits control and business logic.
- On the first request the container translates
page.jspinto a servlet, compiles it, and then serves every later request from that compiled servlet, so only the first request is slow. - The JSP life cycle is translation, compilation, loading,
jspInit(),_jspService()for each request, andjspDestroy(). - A JSP file needs no
web.xmlentry; it is placed in the application folder and opened directly by its file name.
First JSP example. Save it as hello.jsp in webapps/myapp and open http://localhost:8080/myapp/hello.jsp.
<%@ page language="java" contentType="text/html" %>
<html><body>
<%! int count = 0; %>
<% count++; String user = request.getParameter("user"); %>
<h2>Hello <%= user %>, visit number <%= count %></h2>
</body></html>
<!-- ?user=Ravi first visit prints: Hello Ravi, visit number 1 -->
Scripting elements.
| Element | Syntax | Purpose |
|---|---|---|
| Comment | <%-- text --%> |
Hidden comment, not sent to the browser |
| Declaration | <%! int x = 0; %> |
Declares variables and methods at class level |
| Scriptlet | <% code %> |
Java statements placed inside _jspService() |
| Expression | <%= expr %> |
Evaluates the expression and prints it to the output |
Implicit objects. The container creates these nine objects, which can be used without declaring them.
| Object | Type | Use |
|---|---|---|
request |
HttpServletRequest |
Reads request parameters and headers |
response |
HttpServletResponse |
Sends the reply, cookies and redirects |
out |
JspWriter |
Writes output to the page |
session |
HttpSession |
Keeps data for one user across requests |
application |
ServletContext |
Data shared by the whole application |
config |
ServletConfig |
Initialisation data of this page |
pageContext |
PageContext |
Gives access to all scopes of the page |
page |
Object |
The current servlet instance, like this |
exception |
Throwable |
The error, only on pages with isErrorPage="true" |
Directives. A directive gives the container instructions at translation time and has the form <%@ name attribute="value" %>.
pagesets page properties, for example<%@ page import="java.util.*" errorPage="err.jsp" %>.includecopies another file into the page at translation time, for example<%@ include file="header.html" %>.taglibdeclares a tag library so that custom tags can be used on the page.
Standard actions. Actions are XML-style tags that act at request time.
| Action | Purpose |
|---|---|
<jsp:include page="a.jsp"/> |
Includes another resource at request time |
<jsp:forward page="b.jsp"/> |
Passes the request to another resource |
<jsp:useBean id="s" class="pkg.Student"/> |
Creates or finds a JavaBean |
<jsp:setProperty name="s" property="name"/> |
Sets a bean property |
<jsp:getProperty name="s" property="name"/> |
Prints a bean property |
Pitfall: Do not confuse the
includedirective (copied once at translation time) with the<jsp:include>action (run at request time).
Multimedia: Applets and Application: Loading, Displaying and Scaling Images, Animating a Series of Images, Loading and playing Audio clips
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. <mark>Java multimedia means loading images and audio clips from a URL or file and showing or playing them from an applet or an application.</mark>
Key points.
- An applet is a small Java program that extends
Applet(orJApplet), is embedded in a web page and is run by a browser or byappletviewer, while an application is a standalone program that starts frommain(). - The applet life cycle methods are
init()(once, at loading),start()(when the page is shown),paint(Graphics g)(whenever drawing is needed),stop()(when the page is left) anddestroy()(once, at removal). - Applets run in a security sandbox, so by default they cannot read local files or connect to a host other than the one they came from.
- Images of GIF, JPEG and PNG format are supported; audio clips are supported in formats such as AU, WAV, AIFF and MIDI.
Loading and displaying images. The method getImage(getDocumentBase(), "pic.gif") loads the image, and g.drawImage(img, x, y, this) draws it at its own size. In an application the same job is done with Toolkit.getDefaultToolkit().getImage("pic.gif") or with ImageIcon.
Scaling images. Giving a width and height to drawImage scales the image to that size; a negative or changed ratio stretches it.
import java.applet.*; import java.awt.*;
public class ImgApplet extends Applet {
Image img;
public void init() { img = getImage(getDocumentBase(), "pic.gif"); }
public void paint(Graphics g) {
g.drawImage(img, 10, 10, this); // original size
g.drawImage(img, 10, 150, 100, 60, this); // scaled to 100 by 60
}
}
Animating a series of images. Animation is a set of frames shown one after another quickly. The images are kept in an array, a Timer or a thread with sleep() advances the frame index, and repaint() redraws the applet.
public class Anim extends Applet implements Runnable {
Image[] f = new Image[4]; int n = 0;
public void init() { for (int i = 0; i < 4; i++) f[i] = getImage(getDocumentBase(), "f" + i + ".gif"); }
public void start() { new Thread(this).start(); }
public void run() {
while (true) { n = (n + 1) % 4; repaint();
try { Thread.sleep(200); } catch (InterruptedException e) {} }
}
public void paint(Graphics g) { g.drawImage(f[n], 10, 10, this); }
} // shows f0, f1, f2, f3, f0 ... every 200 ms
Loading and playing audio clips. An AudioClip object is created with getAudioClip(getDocumentBase(), "sound.wav") in an applet, or with Applet.newAudioClip(url) in an application. Its three methods are play() to play once, loop() to repeat continuously and stop() to stop.
AudioClip clip = getAudioClip(getDocumentBase(), "sound.wav");
clip.play(); // once
clip.loop(); // repeat until stop()
clip.stop();
Last-minute revision
- A servlet is a Java class in a container (Tomcat) that answers HTTP requests.
- Servlet life cycle:
init()once,service()per request,destroy()once. doGet()handles GET requests; parameters are read withgetParameter().- Tomcat runs at
http://localhost:8080;web.xmlinWEB-INFmaps URLs to servlets. - A multitier application has client, middle (servlet/JSP) and data (database) tiers.
- JDBC from a servlet: driver,
Connection,PreparedStatement,ResultSet, close. - JSP is translated to a servlet on the first request.
- JSP scripting elements: declaration
<%! %>, scriptlet<% %>, expression<%= %>; directives: page, include, taglib. - JSP has nine implicit objects:
request,response,out,session,application,config,pageContext,page,exception. - Images:
getImage,drawImage(with width and height to scale); audio:getAudioClip,play,loop,stop. - Applet life cycle:
init,start,paint,stop,destroy.
Memory hooks
- Servlet life: I-S-D (init, service, destroy).
- Scripting tags:
<% %>runs,<%= %>prints,<%! %>declares. - Directive is translation time, action is request time.
- Applet life: "I Start, Paint, Stop, Destroy".
- Audio: play once, loop repeats, stop halts.
Coverage checklist
- Servlets: Overview and Architecture, Setting Up the Apache Tomcat Server, Handling HTTP get Requests, Deploying a web Application, Multitier Applications, Using JDBC from a Servlet: no past questions.
- Java Server Pages (JSP): Overview, First JSP Example, Implicit Objects, Scripting, Standard Actions, Directives: no past questions.
- Multimedia: Applets and Application: Loading, Displaying and Scaling Images, Animating a Series of Images, Loading and playing Audio clips: no past questions.