0% found this document useful (0 votes)
49 views23 pages

Servlets 14.3.24

The document discusses servlets in Java, which are programs that run on web servers to handle requests from clients. Servlets can process requests, generate responses, access databases, and support features like load balancing and online conferencing. The document also describes how servlets use APIs to interact with web servers and handle different HTTP request types like GET and POST.

Uploaded by

gikurujoseph53
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)
49 views23 pages

Servlets 14.3.24

The document discusses servlets in Java, which are programs that run on web servers to handle requests from clients. Servlets can process requests, generate responses, access databases, and support features like load balancing and online conferencing. The document also describes how servlets use APIs to interact with web servers and handle different HTTP request types like GET and POST.

Uploaded by

gikurujoseph53
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/ 23

Servlets

1
Intro
• in Java, then you will be happy to • Properties of Servlets are as
know that using Java there also follows:
exists a way to generate dynamic • Servlets work on the server-side.
web pages and that way is Java
Servlet • Servlets are capable of handling
complex requests obtained from
• Servlets are the Java programs that the webserver.
run on the Java-enabled web
server or application server. They
are used to handle the request
obtained from the webserver,
process the request, produce the
response, then send a response
back to the webserver.
2
Advantages
• Advantages of servlets: • Servlets can be used when collaboration is needed
between people. A servlet can handle multiple
• Servlets are portable among operating systems and requests concurrently, and can synchronize
among servers. requests. So servlets can support on-line
• Servlets have access to all the APIs of the Java conferencing
platform (e.g. a servlet can interact with a • When a servlet loads, its init() method is called.
database using JDBC API). You can use init() to create I/O intensive resources,
• Servlets can forward requests to other servers and such as database connections, for use across
servlets. Thus, servlets can be used to balance load multiple invocations. If you have a high-traffic site,
among several servers that mirror the same the performance benefits can be quite dramatic.
content, and to partition a single logical service • Instead of creating thousands of database
over several servers, according to task type or connections, the servlet needs to create a
organizational boundaries. connection only once.
• Servlets are a natural fit if you are using the web • The servlet’s destroy() method can clean up
for enterprise computing. Web browsers then resources when the server shuts down.
function as universally available thin clients; the
web server becomes middleware responsible for
running applications for these clients

3
4
• he server-side extensions are nothing • These APIs allow us to build programs
but the technologies that are used to that can run with a Web server. In this
create dynamic Web pages. Actually, case, Java Servlet is also one of the
to provide the facility of dynamic Web component APIs of Java Platform
pages, Web pages need a container or Enterprise Edition which sets
Web server. standards for creating dynamic Web
• To meet this requirement, applications in Java
independent Web server providers • The Servlet technology is similar to
offer some proprietary solutions in other Web server extensions such
the form of APIs(Application as Common Gateway Interface(CGI)
Programming Interface). scripts and Hypertext
Preprocessor (PHP). However, Java
Servlets are more acceptable since
they solve the limitations of CGI such
as low performance and low degree
scalability.
5
Servlets API’s
Servlets are build from two
packages:
• javax.servlet(Basic)
• javax.servlet.http(Advance)

6
7
8
9
10
11
12
HTTP Servlets • import javax.servlet.*;
• import javax.servlet.http.*;
• import java.io.*;

• The HttpServlet class is an extension of GenericServlet class • public class JamboServlet extends HttpServlet {
that includes methods for handling HTTP specific data.
• public void doGet(HttpServletRequest uliza,
• HttpServlet defines a number of methods, such as doGet(), HttpServletResponse jibu) throws
and doPost(), to handle particular types of HTTP requests
(GET, POST, etc.). • ServletException, IOException {
• These methods are called by the default implementation of •
the service() method, which figures out the kind of request • jibu.setContentType(“text/html”);
being made and then invokes the appropriate method.
(service() is defined in GenericServlet class). • PrintWriter sema = jibu.getWriter();

• sema.println(“<HTML>”);
• sema.println(“<HEAD><TITLE>Have you seen this
• before?</TITLE></HEAD>”);
• sema.println(“<BODY><H1> Mambo sawa sawa
!</H1></BODY></HTML>”);
• }
• }

13
The HTML form that calls the servlet
using a GET request is as follows:

• The doGet() method is called whenever anyone <HTML>


requests a URL that points to this servlet.
<HEAD><TITLE> Greetings Form</TITLE></HEAD>
• The servlet is installed in the servlets directory and
its URL is http://site:8080/servlet/JamboServlet. <BODY>
• The doGet() method is actually called by the <FORM METHOD=GET
default service() method of HttpServlet. ACTION=”/servlet/JamboServlet”>
• The service() method is called by the web server What is your name?
when a request is made of JamboServlet; the <INPUT TYPE=TEXT NAME=jina SIZE=20>
method determines what kind of HTTP request is
being made and dispatches the request to the <INPUT TYPE=SUBMIT VALUE=”Introduce Yourself”>
appropriate doXXX() method (in this case, doGet()).
doGet() is passed two objects, HttpServletRequest </FORM>
,and HttpServletResponse, that contain information </BODY>
about the request and provide a mechanism for
the servlet to provide a response, respectively. </HTML>

14
The form submits a variable named jina to the URL
/servlet/JamboServlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
• The getParameter() method of HttpServletRequest is used to
retrieve the value of the form variable.
public class JamboServlet extends HttpServlet { • When a server calls a servlet, it can also pass a set of request
public void doGet(HttpServletRequest req, parameters
HttpServletResponse resp) throws • The POST request is designed for posting information to the
ServletException, IOException { server, although in practice it is also used for long
parameterized requests and larger forms, to get around
limitations on the length of URLs. The doPost() method is the
corresponding method for POST requests.
resp.setContentType(“text/html”);
• If your servlet is performing database updates, charging a
PrintWriter out = resp.getWriter(); credit card, or doing anything that takes an explicit client
action, you should make sure that this activity is happening in
a doPost() method.
out.println(“<HTML>”); • To create a servlet that can handle POST requests, you need
out.println(“<HEAD><TITLE>Finally, interaction!</TITLE></HEAD>”); to override the default doPost() method from HttpServlet and
implement the necessary functionality.
out.println(“<BODY><H1>Hello,” + req.getParameter(“jina”) + • If necessary, your application can implement different code
“!</H1>” ); in doPost() and doGet(). For instance, the doGet() method
might display a postable data entry form that the doPost()
out.println(</BODY></HTML>”); method processes. doPost() can even call doGet() at the end
to display the form again.
}
}
15
Servlet Responses

• In the case of an Http servlet, the • ServletResponse and HttpServletResponse


response can include three components: each define two methods for producing
a status code, any number of HTTP output streams, getOutputStream() and
headers, and a response body. getWriter(). The former returns a
• You use setContentType() method of the ServletOutputStream that can be used for
response object passed into the servlet to text or binary data. The latter returns a
set the type of the response. Examples java.io.PrintWriter object used for text
include “text/html” for text, “image/gif” data.
for returning a GIF file from the database, • You can use setStatus() or sendError()
and “application/pdf” for Adobe Acrobat method to specify the status code sent
files. back to the server. Examples include, 200
(“OK”), 404 (“Not Found”) etc. The
sendRedirect() method allows you to
issue a page redirect. Calling this sets the
Location header to the specified location
and uses the appropriate status code for
a redirect.

16
Servlet Requests • ServletRequest provide these
methods. Examples include:
• getProtocol() (protocol used by
• When a servlet is asked to request),
handle a request, it typically • getRemoteHost() (client host
needs specific information about name),
the request so that it can • getServerName() (name of the web
process the request server),
appropriately. For example, a • getServerPort() (port number the
servlet may need to find out web server listens at),
about the actual user who is • getParameter() (access to request
accessing the servlet, for parameters as form variables), and
authentication purposes. • getParameterValues() (returns an
array of strings that contains all the
values for a particular parameter).
17
This servlet requests information to restrict access.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

if(scheme.equalsIgnoreCase(“https”) && remoteHost.endsWith(“.gov”) &&


public class SecureRequestServlet extends HttpServlet {
authType.equals(“Digest”)) {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
out.println(“Special, secret information”);
}
resp.setContentType(“text/html”); else {
PrintWriter out = resp.getWriter(); out.println(“You are not authorized to read this
information”);
out.println(“<HTML>”); }
out.println(“<HEAD><TITLE>Semi-Secure Request</TITLE></HEAD>”); out.println(“</BODY></HTML>”);
out.println(“<BODY>”); }
}
String remoteHost = req.getRemoteHost();
String scheme = req.getScheme();
String authType = req.getAuthType();

if((remoteHost == null) || (scheme == null) || (authType == null)) {


out.println(“Request information was not available”);
return;
}

18
Servlet Initialization

• When a server loads a servlet for the first • The server passes the init() method a
time, it calls the servlet’s init() method. ServletConfig object.
• In its default implementation, init() handles • This object encapsulates the servlet
some basic housekeeping, but a servlet can initialization parameters, which are accessed
override the method to perform other tasks. via the getInitParameter() and
This includes performing I/O intensive tasks getInitParameterNames() methods.
such as opening a database connection.
• GenericServlet and HttpServlet both
• You can also create threads in init() to implement the ServletConfig interface, so
perform other tasks such as pinging other these methods are always available in a
machines on the network to monitor the servlet.
status of these machines. • Each servlet also has a destroy() method that
• When an actual request occurs, the service can be overwritten. This method is called
methods can use the resources created in when a server wants to unload a servlet. You
init(). The default init() is not a do-nothing can use this method to free important
method. You must always call super.init() as resources.
the first action in your own init() routines.

19
ATM Example import javax.servlet.*;
import javax.servlet.http.*;
• This servlet implements an ATM display. The import java.util.*;
doGet() method displays the current account import java.io.*;
balance and provides a small ATM control
panel for making deposits and withdrawals.
The control panel uses a POST request to
send the transaction back to the servlet, public class AtmServlet extends HttpServlet {
which performs the appropriate action and Account act;
calls doGet() to redisplay the ATM screen with
the updated balance. This example also
demonstrates thread safety public void init (ServletConfig conf) throws
ServletException {
super.init();
act = new Account();
act.balance = 0;
}

20
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
ServletException, IOException { int amt = 0;
try {
resp.setContentType(“text/html”); amt = Integer.parseInt(req.getParameter(“AMOUNT”));
PrintWriter out = resp.getWriter(); }
out.println(“<HTML><BODY>”); catch (NullPointerException e) {
out.println(“<H2> First Bank of Java ATM</H2>”); // No amount Parameter passed
out.println(“Current Balance: <B>” + act.balance + “</B><BR>”); }
out.println(“<FORM METHOD=POST catch (NumberFormatException e) {
ACTION=/servlet/AtmServlet>”);
//Amount parameter was not a number
out.println(“Amount: <INPUT TYPE=TEXT NAME=AMOUNT
}
SIZE=3><BR>”);
out.println(“INPUT TYPE=SUBMIT NAME=DEPOSIT
synchronized(act) {
VALUE=\”Deposit\”>”); if (req.getParameter(“WITHDRAW”) != null) && (amt <
act.balance))
out.println(“INPUT TYPE=SUBMIT NAME=WITHDRAW
act.balance = act.balance – amt;
VALUE=\”Withdraw\”>”);
if (req.getParameter(“DEPOSIT”) != null) && (amt > 0)
out.println(“</FORM>”);
act.balance = act.balance + amt;
out.println(“</BODY></HTML>”);
} //end synchronized block
}

21
doGet(req, resp); // Show ATM screen
} // end doPost()

public void destroy() {


// save balance to a file before servlet is unloaded. If servlet used JDBC to // write to
a database, need to destroy all database resources here.
}

class Account {
public int balance;
}
}

22
Setting up the Eclipse IDE (Practicals):
• Understanding how a Servlet works : • Download the Eclipse IDE for Java EE
• The client sends a request to the Development from
server and the request goes to the http://www.eclipse.org/downloads/
Web Container. • Download the Tomcat server from
• The Web Container uses a file named https://tomcat.apache.org
web.xml to detect which servlet to call • Go to File>New>Dynamic Web
and it calls the required servlet. Project.
• The servlet will process the • Add the link to the folder containing
information and will send a response Tomcat to the Servlets tab at the
to the client machine. bottom of the window and you’re all
• set to create your first servlet!

23

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy