Java Servlets

fortunabrontideInternet and Web Development

Nov 13, 2013 (3 years and 10 months ago)

101 views

11/13/2013

G53ELC: Servlets

1

Servlets

Dave Elliman

11/13/2013

G53ELC: Servlets

2

Client

Server communication


Web browser client


HTML form


CGI/ASP/PHP/JSP/PHP


Or a servlet


HPPT GET/POST


Java Client


-

RMI or SOAP


General Client
-

SOAP, RPC, REST, JSON.


Often we have to use port 80 (firewalls)


Often we have to use HTTP as other
protocols are blocked


Could use a servlet for anything then….

11/13/2013

G53ELC: Servlets

3

What Is a Servlet?

“A
servlet

is a server
-
side Java replacement for CGI
scripts and programs.
Servlets

are much faster and
more efficient than CGI and they let you unleash the
full power of Java on your web server, including back
-
end connections to databases and object repositories
through JDBC, RMI, and CORBA”


Atlanta Java Users Group
(http://www.ajug.org/meetings/jun98.html)

11/13/2013

G53ELC: Servlets

4

A common design pattern


Has a servlet at the front end handling all
communication to and from the client


This is known as the “Front Controller
Pattern”


Works for web servers and also for other
kinds of services.

11/13/2013

G53ELC: Servlets

5

Agenda


HTTP Review


Servlet, HTTPServlet


Retrieving Information


Requests


Responses


Servlet Invocation


Session
-
Tracking

11/13/2013

G53ELC: Servlets

6

What Is a servlet?

A
servlet
is a Java based solution to
dynamic web content delivery. Just
as applets are little pieces of Java
code that are run on a
client
machine

(via a browser),
servlets
are little pieces of Java code that run
on the
server

11/13/2013

G53ELC: Servlets

7

A servlet Is a Server
-
side Java Class

Which Responds to Requests

service()

doPost()

doGet()

doPut()

doDelete()

11/13/2013

G53ELC: Servlets

8

An Example of a Servlet


a
servlet

responsible for taking data in an HTML
order
-
entry form and applying the business logic
used to update a company's order database


(
http
://www.uni
-
koblenz.de/~admin/Doku/Java/Tutorial/servlets/overview/index.html)

11/13/2013

G53ELC: Servlets

9

Why Use a servlet?


You want dynamic web pages


You wish to have all the power of Java


JDBC or Hibernate


EJBs maybe with Spring


+ all other Java APIs


They are much faster than CGI scripts

11/13/2013

G53ELC: Servlets

10

Other Technologies You
Might Use


CGI scripts (can be done in various
languages)


ASP (Mircrosoft) write in VBScript or
Jscript. Now ASP.NET


PHP (open source)


Massively used and
comprehensive language


JSP


compiled into servlets

11/13/2013

G53ELC: Servlets

11

What Do You Need to Deploy
servlets?


A servlet container
-

eg


http://jakarta.apache.org/tomcat


This can be integrated with MS IIS or
Apache web servers


Alternatives


all JEE containers
JBoss, Glassfish, WebSpher etc

11/13/2013

G53ELC: Servlets

12

Life
-
cycle of a servlet


init()


service()


destroy()


It can sit there simply servicing requests
with no start up overhead, no code
compilation. It is FAST


It may be stateless


minimal memory

11/13/2013

G53ELC: Servlets

13

A Servlet Is ...


module that extends request
-
response
servers, such as those that are Java
-
enabled


to a server as an applet is to a browser,
except servlets do not have graphical
interfaces


a server
-
side Java “application”

11/13/2013

G53ELC: Servlets

14

Why Use Servlets?


Portability


write once, serve everywhere


Power


can take advantage of all core Java APIs


Elegance


simplicity due to abstraction


Efficiency & Endurance


instance persistence, highly scalable

11/13/2013

G53ELC: Servlets

15

Why Use Servlets?


Safety (
compared to PHP
)


Strong type
-
checking


memory management


Integration


servlets tightly coupled with server


Extensibility & Flexibility


servlets designed to be easily extensible, though
currently optimized for HTTP uses


flexible invocation of servlet (SSI, servlet
-
chaining)

11/13/2013

G53ELC: Servlets

16

What Can servlets Do?


Essentially, any protocol that follows a request/response computing
model can be implemented by a servlet. This could include
:


SMTP


POP


FTP


11/13/2013

G53ELC: Servlets

17

HTTP: Request &
Response


Client sends HTTP
request

(method)
telling server the type of action it wants
performed


GET method


POST method


Server sends response

11/13/2013

G53ELC: Servlets

18

Http: Get & Post


GET method


For getting information from server


Can include
query string
, sequence with
additional information for GET, appended to
URL

e.g. Http://www.whoami.Com/Servlet/search?Name=Inigo+Montoya

11/13/2013

G53ELC: Servlets

19

Http: Get & Post


POST method


designed to give information to server


all information (unlimited length) passed as
part of request body


invisible to user


cannot be reloaded (by design)

11/13/2013

G53ELC: Servlets

20

Class Hierarchy

<<interface>>

javax.servlet.Servlet

<<interface>>

javax.servlet.ServletConfig

<<interface>>

Java.io.Serializable

javax.servlet.http.HttpServlet

javax.servlet.GenericServlet

11/13/2013

G53ELC: Servlets

21

GenericServlet and
HTTPServlet


If you decide to extend
GenericServlet
class you must implement service()
method


In case
HttpServlet
you don’t usually
implement service method. It is already
implemented for you


Most of the time you will be extending
HttpServlet

class

11/13/2013

G53ELC: Servlets

22

HelloWorld Example

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloWorld extends HttpServlet

{


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException


{



res.setContentType("text/html");



PrintWriter out = res.getWriter();




out.println("<HTML>");



out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");



out.println("<BODY>");



out.println("<BIG>Hello World</BIG>");



out.println("</BODY></HTML>");


}

}

11/13/2013

G53ELC: Servlets

23

Servlet


An interface that all servlets must implement


Void init(ServletConfig config)


Called every time the servlet is instantiated


Void service(ServletRequest req,
ServletResponse res)


ServletRequest
: parameters from the client


ServletResponse
: contains an output stream used to
return information to the client


Needs to be thread
-
safe since multiple requests can be
handled concurrently


Not called until init() has finished execution


11/13/2013

G53ELC: Servlets

24

Servlet


void destroy()


called by the servlet engine when it removes the
servlet


should free any resources (i.e. files or database
connections) held by the servlet


String getServletInfo()


Returns version and copyright information


11/13/2013

G53ELC: Servlets

25

HttpServlet


Implements
Servlet



Receives requests and sends responses to a
web browser


Methods to handle different types of HTTP
requests:


doGet()

handles GET requests


doPost()

handles POST requests


doPut()

handles PUT requests


doDelete()

handles DELETE requests

11/13/2013

G53ELC: Servlets

26

HttpServlet Request Handling

GET request

service()

HttpServlet subclass

response

doGet()

doPost()

Web
Server

POST request

response

11/13/2013

G53ELC: Servlets

27

Handling HttpServlet
Requests


service()

method not usually overridden


do
XXX
()

methods handle the different
request types


Needs to be thread
-
safe or must run on a STM
(SingleThreadModel) Servlet Engine


multiple requests can be handled at the same
time

11/13/2013

G53ELC: Servlets

28

Simple Counter Example

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;


public class SimpleCounter extends HttpServlet

{

int count = 0;


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException

{

res.setContentType(“text/plain”);

PrintWriter out = res.getWriter();

count++;

out.println(“This servlet has been accessed “ + count +

“ times since loading”);

}

}

11/13/2013

G53ELC: Servlets

29

Multithreading solutions


Synchronize the
doGet()

method


public synchronized void doGet(HttpServletRequest
req, HttpServletResponse res)


servlet can’t handle more than one GET
request at a time


Synchronize the critical section

PrintWriter out = res.getWriter();

synchronized(this)

{



count++;

out.println(“This servlet has been accessed “ + count + “
times since loading”);

}

11/13/2013

G53ELC: Servlets

30

Retrieving Information


Getting information about client


operate on request object


public String ServletRequest.getRemoteAddr()


returns IP address of client machine

public String ServletRequest.getRemoteHost()


returns host name of client machine

public String ServletRequest.getRemoteUser()


returns userid of individual on client (as long as you set up
restricted access to the page and requested authentication
from the remote user)

11/13/2013

G53ELC: Servlets

31

The Request


Request parameters:


tell the server what the client really wants


are word, value pairs


given to server through:


query string

on URL (GET)


within request body (POST)


in
<PARAM>

tags (Server
-
Side Include)


11/13/2013

G53ELC: Servlets

32

The Request


Every servlet retrieves parameters through
these methods:


public String ServletRequest.getParameterNames()


returns enumeration of parameter names


public String ServletRequest.getParameter(String name)


returns value for parameter with name

name


public String[] ServletRequest.getParameterValues
(String name)


returns array of values for parameter with name

name



11/13/2013

G53ELC: Servlets

33

Snooping Parameters
Example

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ParameterSnoop extends HttpServlet

{


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException

{



res.setContentType("text/plain");



PrintWriter out = res.getWriter();



out.println("Query String:");



out.println(req.getQueryString());



out.println();



out.println("Request Parameters:");



Enumeration enum = req.getParameterNames();




11/13/2013

G53ELC: Servlets

34

Snooping Parameters
Example [2]



while (enum.hasMoreElements())



{




String name = (String) enum.nextElement();




String values[] = req.getParameterValues(name);




if (values != null)




{





for (int i = 0; i < values.length; i++)





{






out.println(name +






" (" + i + "): " + values[i]);





}




}



}

11/13/2013

G53ELC: Servlets

35

The Response


Three parts to a response


status code (404 “Not Found”, 200 “OK”)


public void HttpServletResponse.setStatus(int sc)


public void HttpServletResponse.setStatus(int sc,
String sm)


HTTP headers (i.e. content
-
type)


response body

11/13/2013

G53ELC: Servlets

36

HTTP Headers: Content Type


Set the content MIME type using

public void ServletResponse.setContentType(String
type)


e.g.
res.setContentType(“text/html”);


getWriter()

method returns a
PrintWriter
for character data of
the content type

public PrintWriter ServletResponse.getWriter()


Set specific header values using

public void HttpServletResponse.setHeader(String
name, String value)

public void HttpServletResponse.setDateHeader
(String name, long date)

public void HttpServletResponse.setIntHeader(String
name, int value)


11/13/2013

G53ELC: Servlets

37

Response Body


Sequence of bytes (HTML, image)


Any length


Status code and headers must be sent before
the response body


HTML can be generated by hand


Can use HTML generation packages to abstract
away the details of HTML


Images can be sent by using an appropriate
encoder

11/13/2013

G53ELC: Servlets

38

Invoking Servlets


Directly from path


http://www.dge.org:8080/servlets/Hello


From Servlet
-
Chaining


one servlet returns a content
-
type that
another servlet is registered to handle
(filtering)

11/13/2013

G53ELC: Servlets

39

Session Tracking


HTTP is a stateless protocol


many web applications (i.e. shopping carts) are not


need to keep track of each user’s state (i.e. items in
the shopping cart)


Common techniques


user authorization


hidden form fields


URL rewriting


persistent cookies

11/13/2013

G53ELC: Servlets

40

Session Tracking API


Servlets have built
-
in session tracking


Every user has a
HttpSession

object


store and retrieve user information


i.e. shopping cart contents, database connections


Retrieve the user’s session:

public HttpSession HttpServletRequest.getSession (boolean create)


if the user has no valid session, a new one is created
if
create

is
true
;
null

is returned if
create

is
false

11/13/2013

G53ELC: Servlets

41

Session Tracking API


Add data to a session

public void HttpSession.putValue(String name, Object value)


value must implement
Serializable

interface


replaces any object that is bound in the session with
the same name


Retrieve data from a session

public Object HttpSession.getValue(String name)


returns
null

if no object is bound to the name

11/13/2013

G53ELC: Servlets

42

Session Tracking API


Retrieve the name of all session objects

public String[] HttpSession.getValueNames()


returns an empty array if no bindings


Remove a value from the session

public void HttpSession.removeValue(String name)


does nothing if no object is bound


These methods throw an
IllegalStateException

if the session is invalid

11/13/2013

G53ELC: Servlets

43

Hit Count With Session Tracking

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SessionTracker extends HttpServlet

{

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException

{

res.setContentType("text/html");

PrintWriter out = res.getWriter();


HttpSession session = req.getSession(true);


Integer count = (Integer)session.getValue("tracker.count");


if (count == null)


count = new Integer(1);

else


count = new Integer(count.intValue() + 1);

11/13/2013

G53ELC: Servlets

44

Hit Count With Session Tracking

session.putValue("tracker.count", count);

out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>
");

out.println("<BODY><H1>Session Tracking Demo</H1>");


out.println("You've visited this page " + count +
((count.intValue() == 1) ? " time." : " times."));

out.println("<P>");


out.println("<H2>Here is your session data:</H2>");

String[] names = session.getValueNames();

for (int i = 0; i < names.length; i++)

{


out.println(names[i] + ": " + session.getValue(names[i]) +
"<BR>");

}

out.println("</BODY></HTML>");

}

}

11/13/2013

G53ELC: Servlets

45

Session Duration


Sessions expire after a set period of inactivity
(e.g. 30 minutes)


Sessions can be invalidated by a servlet


public void HttpSession.invalidate()


All data in a session object is lost when the
session is removed


persistent data should be stored externally (i.e. in a
database)

11/13/2013

G53ELC: Servlets

46

Storing Sessions


A unique ID is used to keep track of each
session


Session tracking often implemented by the
server using persistent cookies


URL rewriting used when the browser doesn’t
accept cookies


servlets need to rewrite every URL

public String HttpServletResponse.encodeUrl(String url)


URL left unchanged if the server doesn’t support URL
rewriting

11/13/2013

G53ELC: Servlets

47

Conclusions


Servlets are an efficient way of providing
dynamic web pages in the context of browser
-
based clients


They can use the full power of Java EE,
including the advantages of Application
Containers, and Spring/Hibernate etc


They can even be used if the client is not
browser
-
based especially if firewall restrictions
mean that HTTP has to be used.


Need to think about reliability of connection