0% found this document useful (0 votes)
51 views65 pages

S LT LT 1 Servlets: Lecture 1 The Basics: ELE406, 2012, Karen Shoop

1. The web server receives the HTTP request and passes it to the servlet container. 2. The container identifies that the request URL maps to the BMIServlet. 3. If it hasn't already, the container creates an instance of BMIServlet and calls its init() method. 4. The container spawns a new thread to handle this request and calls the doGet() method of BMIServlet, passing the request and response objects.

Uploaded by

Minh Quang Hoang
Copyright
© Attribution Non-Commercial (BY-NC)
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)
51 views65 pages

S LT LT 1 Servlets: Lecture 1 The Basics: ELE406, 2012, Karen Shoop

1. The web server receives the HTTP request and passes it to the servlet container. 2. The container identifies that the request URL maps to the BMIServlet. 3. If it hasn't already, the container creates an instance of BMIServlet and calls its init() method. 4. The container spawns a new thread to handle this request and calls the doGet() method of BMIServlet, passing the request and response objects.

Uploaded by

Minh Quang Hoang
Copyright
© Attribution Non-Commercial (BY-NC)
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/ 65

Servlets: Lecture 1 S l t L t the basics

ELE406, 2012 , Karen Shoop

EECS

Homework Week 1: general feedback


HTML HTTP O l one form (for the example provided) Only f (f h l id d) Think about where to place the user text (before or after the elements) Comments: <!-- Hello --> All h homework should be handwritten k h ld b h d itt TextAreas for large text M k th element name something sensible (not eg i t4) Make the l t thi ibl ( t input4) as this is helpful in eg the servlet

EECS

<input type="text" name="age">enter age<br> <input type="text" name="height">enter height</input><br> <input type="text" name="weight"></input>enter height<br> g <input type="text" name="salary"/>enter height<br>

EECS

<select name="nationality"> <option>british i bii h <option>french </select> / l <select name="town"> <option>london</option> <option>paris</option> </select>
EECS

<select name="postcode"> <option i value="br">br2</option> <option value="e">e22</option> </select>


Browsers Tested: Chrome, Firefox, IE, Opera, Safari

Java Servlets and the HTTP Protocol


HTML client information What are servlets and why are they useful? y Servlet structure and lifecycle Handling request data HTTP request headers Generating the HTTP response Session tracking

EECS

Write an HTML page


Textbox asking for full name and age, being sent to www.tg.cn/day2/serv1.do /d 2/ 1d

Tips: save the file as sendName.html (if you are not using an IDE use eg Notepad not Word as Word may store some characters that impact on the page; one EECS common error is to forget the .html extension). Note, we do not know the name of6 h l l l f h ( b ll d )

HTTP: GET and POST

EECS

A general purpose Web Server e.g. Apache Uses environment


variables Function call cgi program Tomcat container/plug in

URL & request


HTTP request

Web Server container e.g Apache p

HTTP response

response page
php container/plug in

Uses java method call on an object called a servlet

Still HTTP
EECS

php script
8

Servlet no1: A Basic Servlet


import javax.servlet.*; import javax.servlet.http.*; import java.io.*; pub c c ss e oSe v e e e ds public class HelloServlet extends HttpServlet{ pSe v e { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOE H S l R ) h IOException, S l E i ServletException { i response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(<html><body>Hello!</body></html>);} }
We will ignore how the Container finds the servlet (the deployment descriptor (web.xml) ) for now

This is a dumb servlet as could be replaced by a static .html page

EECS

Servlet no2: Echo Servlet


Testing an echo g Please enter your name: HTTP request message

Echo Webpage 1 (HTML)

Webpage 1

Servlet s Servlets responsibilities: 1. Get users name from HTTP p g 2. Write a webpage 3. Add the users name 4. Send back in HTTP response

Hello Karen Echo has worked Webpage 2 HTTP response message


EECS

10

Servlet no2: Echo Servlet


import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

Method in HTML <FORM>: GET Name of textbox: fullname

public class GetEchoServlet extends HttpServlet{ public void doGet(HttpServletRequest request request, HttpServletResponse response) throws IOException, ServletException { String userName = request.getParameter(fullname); response.setContentType("text/html"); response setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(<html><body>Hello); if(userName!=null) if( N ! ll) Validate! out.println(userName); else out.println(mystery person); out.println(</body></html>);}}
EECS 11

Servlet no2: Echo Servlet


import javax.servlet.*; import javax.servlet.http.*; import java.io.*; pub c c ss os c oSe v e extends public class PostEchoServlet e e ds HttpServlet{ pSe v e { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException ServletException { IOException, String c = request.getParameter(country); response.setContentType("text/html"); PrintWriter out = response.getWriter(); response getWriter(); out.println(<html><body>Hello<br>); out.println(You are from +c+</body></html>);} }
EECS 12

Method in HTML Form tag: POST y Name of element: country

Page that asks for weight (kg) and height (cm)


Write the HTML and the HTTP Request (GET)

EECS

Thinking ahead (JavaScript validation): height type safety (numberint) and value safety (eg >100)

13

BMI Servlet
import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

public class BMIServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

string ht = request.getParameter(height); int height = Integer.parseInt(ht); double weight = Double.parseDouble(request.getParameter(weight));


double ht_squared=(height/100)*(height/100); response.setContentType("text/html"); PrintWriter out = response.getWriter();

out.println(<html><body><br>); out.println(Your BMI is: +weight/ht_squared+<body></html>);} }


EECS 14

Servlet no4: Write your own Servlet: name and salary


import javax.servlet.*; import javax.servlet.http.*; import java io *; java.io. ;

public class HelloServlet extends HttpServlet{ public void do______(HttpServletRequest request, do (HttpServletRequest request HttpServletResponse response) throws IOException, ServletException { ___________________________________ ___________________________________ response.setContentType("text/html"); PrintWriter out = response.getWriter(); ______________________________________ ______________________________________ }//end of method }//end of class
EECS 15

Tracing the User Data


Tracing the user data:
HTML: <input type=text name=city>enter city<br> <input type=text name=price>enter price HTTP: GET /sv.do?city=New+York&price=345 HTTP/1.1 Servlet: String c = request.getParameter(city); int p = Integer.parseInt(request.getParameter(price));
EECS 16

A general purpose Web Server e.g. Apache

Servlet URL & request

cgi

Web Server container

service() () method

request

request responseservlet
php

response page

Tomcat plug in
EECS

Servlet S l t container, or engine app

17

What servlets (plus JavaBeans and JSPs) do


Read any data sent by the user (explicit) Look up information embedded in HTTP request (implicit) G Generate results t lt Format results inside a document Format HTML or XML or GIF or Excel.. Set appropriate HTTP response parameters Send the document back to the client C only do this with the help of the container Can l d thi ith th h l f th t i
EECS 18

Servlet is deployed in a container, which is..


a program that receives (e.g. HTTP) requests to servlets from a web server application
fi d the servlet (and loads, calls constructor & i i if finds h l ( dl d ll init not ready) creates or re-uses a thread which will call the service method of chosen servlet p q p j creates & passes request and response objects for each request to the chosen servlet passes the response (e.g. HTTP response) back to the web server app; kill servlet thread or recycles into b kills l t th d l i t thread pool; deletes request and response objects

EECS

19

Also
More generally, manages the lifecycle of its servlets
Calls constructor, init, service, destroy also invokes methods of any listening classes that a servlet implements

It has a main and is working all the time main all time Provides declarative security using settings in Deployment Descriptor (Tomcat: web.xml) web xml) Provides JSP support
EECS 20

Typical generic servlet code


ONLY creates an object. import javax.servlet.*; ONLY becomes a proper servlet after init

public class AnyServlet extends GenericServlet { public AnyServlet() {} // constructor BUT USE THE DEFAULT // NEVER ANY NEED TO WRITE ONE

public void init(ServletConfig config) throws ServletException; // The method actually called by container when servlet is // first created or loaded public void service(ServletRequest req, ServletResponse res) throws ServletException IOException; ServletException, // called by a new thread (in the container) each time a request is received. public void destroy(); // called when servlet is destroyed or removed
EECS } 21

Call constructor
Exists but not ready for work

at first request or server start up


(depending on web server configuration)

The servlet life cycle


Called once only
init(..) e.g. Can be used for opening a DB connection GET doOptions(..) POST do ost( ) doPost(..) doPut(..) doDelete(..) doGet(..)

Should be thread safe on receiving request

waiting for client requests q request se ce( ) service(..)

at server shutdown

destroy(..) e.g. Can be used for closing a DB connection i

doTrace(..) If HTTPServlet
22

can now be g.c.


EECS

We do not need to write a service method for an HttpServlet


<interface> Servlet Overrides service() in GenericServlet, check the HTTP method and invokes the matching method (doGet/Post) in the developers servlet GenericServlet (abstract) service service

HttpServlet

service

Class objects bj t

Your own servlet class

doGet doPost

service()
EECS

instance
23

One Servlet Instance


Either when the container is loaded or when the first request is made the container instantiates a servlet, calling servlet first its constructor and then init() Request arrives: container makes/spawns a servlet thread (& request + request object) for EVERY request:
One servlet object; multiple threads j p Two users call the same servlet: two threads, each with their own request/reponse objects, but share the same resources (eg instance variables) One user calls the same servlet twice: two threads, each with their own request/reponse objects, but share the same resources (eg instance variables)
EECS 24

Dissecting the Containers actions


HTTP request: GET /myServlet/BMIInfo height=161&name=karen+shoop HTTP/1.1 Host:. Servlet: public class BMIServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { string ht = request.getParameter(height);
EECS 25

Life Cycle
Constructor:
NOT written or called by a developer
no args

called by the container, which then calls: ll d b h i hi h h ll

public void init()


called once, at the beginning (so potentially useful for initialisation of eg databases) Can be over-written by the developer eg to manage resources

EECS

26

Life Cycle (2)


public void service()
Rarely over-written by the developer called every time a request is made, then calls:

public void doGet()/ public void doPost()


must be written by the developer must match the HTTP method in <FORM> in the clients HTML

public void destroy()


can be over-written by the developer eg to manage y p g g resources
EECS 27

Mapping names using the DD


<web-app .> <servlet> <servlet-name>.</servlet-name> <servlet-class></servlet-class> </servlet> <servlet-mapping> <servlet-name>.</servlet-name> < l t > </ l t > <url-pattern></url-pattern > </servlet mapping> </servlet-mapping> . </web-app>
Lots more goes here
EECS

For each servlet in the web application

maps internal name to fully qualified class name name. (except without .class)

maps internal name to public URL name e.g. /makebooking

Internal name can be anything I t l b thi following XML rules


28

If using remote Tomcat in the ITL: you MUST add servlet/ in front of the action value in <FORM>, and / /servlet/ before the url-pattern in web.xml / p

HTML:
<FORM method=post th d t action=servlet/MyTest.do>

Server (webapps): Se ve
WEB-INF/classes/Echo.class

<servlet> <servlet-name>.</servlet-name> <servlet-class>..</servlet-class> <servlet-class> </servlet-class> </servlet> <servlet-mapping> <servlet-name>.</servlet-name> servlet name . /servlet name <url-pattern></url-pattern > </servlet-mapping> <servlet> <servlet-name>.</servlet-name> <servlet-class>..</servlet-class> </servlet> <servlet-mapping> <servlet-name>.</servlet-name> <url-pattern></url-pattern > </servlet-mapping>
29

HTML:
<FORM method=post action=servlet/Test> ti l t/T t>

Server (webapps):
WEB-INF/classes/foo/Name.class WEB INF/classes/foo/Name class
EECS

Putting Everything in the Right Place


Tomcat (ITL) specific:
Level 1: WEB-INF (folder) and .html .jsp Level 2 (inside WEB-INF): web.xml and classes (folder) (f ld ) Level 3 (inside classes): servlet class files (and other business class files, eg Javabeans) b i l fil J b )

EECS

30

EECS

31

Inside classes

EECS

32

Inside chain

EECS

33

Inside classes/chain/web

EECS

34

Inside classes/chain/model

EECS

35

Keep your servlet code in a similarly structured folder

EECS

36

Where we keep the java source for compilation

The code for the Chaining2005 Ch i i 2005 web b app The corresponding folder p g

EECS

37

Copy into tomcat class directory

Compile creates the directory structure

This has same structure as classes seen before but with source code aide memoir
EECS 38

SmallForm.html
<html><title>Sending Form Information to a Servlet</title> <body> <form method="post action=servlet/ProcessSmallForm> Please input your login: <br> <input type="text" name="Login"> i i <input type="submit" value="Login"> </form> </f > </body> </html>

EECS

39

Homework: Write the deployment descriptor ( (web.xml) and the servlet (uname.class to be ) ( stored inside ele406 directory)

EECS

40

What there is in the ITL (remote Tomcat)


You do not see webapps! It is shared by all students. You Y create a di t t directory i id webapps. inside b I have called mine karens my user name To invoke the downloading of an html file held in karens directory e.g. http://tomcat_stu.dcs.qmul.ac.uk/ karens/Currency.html

Path in webapps

To invoke a servlet

Apache

Must contain /servlet/ because of the way Apache is configured in the ITL

http://tomcat_stu.dcs.qmul.ac.uk/ karens/servlet/CC You can add a classes folder, html and jsp files in karens and edit the existing web.xml <servlet-mapping> <servlet-name>My Servlet</servlet-name> <url-pattern> /servlet/CC </url-pattern > </servlet-mapping> 41

NB You

cannot create subdirectories each with their own web.xml (but if you are using Netbeans or Tomcat on your own machine you can)
EECS

Servlet initialisation & Servlet Configuration object


Only one servlet instance is created
each request serviced by a separate thread in container q y p Need to prevent race conditions (avoid instance variables) [One request and one response object for each request]

Prior to initialisation the ServletConfig object is created by the container One ServletConfig object per servlet
Container uses it to pass deploy-time information to the servlet
Facts you do not want to hard code into the servlet, e.g. DB name

The names are specified in the DD

EECS

42

Parameters are set in a server-specific manner, e.g.


in Tomcat in a file called web.xml in Resin in a file call resin.config

Parameters do not change while servlet is deployed and running


Like constants If change them, need to redeploy

EECS

43

Example of init parameters in a DD (web.xml for tomcat)


<servlet> <servlet-name>Hello World Servlet</servlet-name> l H ll W ld S l / l <servlet-class>S1</servlet-class> <init-param> i i <param-name>lecturersEmail</param-name> <param-value>[email protected]</param-value> </init-param> </servlet>
Container reads these and gives to ServletConfig object
EECS 44

Creating a servlet: ServletConfig and init()


Step 1: container reads the deployment descriptor S 2 container creates new ServletConfig object Step 2: i S l C fi bj Step 3: container creates name/value pair (Strings) for each servlet init parameter Step 4: container passes refs to these to the ServletConfig object Step 5: container creates new instance of the servlet class Step 6: container calls servlet s init() method passing in ref servlets to the servletConfig

EECS

45

Getting a parameter value from the ServletConfig object


out.println(email: [email protected]); Now replaced by: p ( out.println( getServletConfig().getInitParameter(lecturersEmail));
Returns the servlets ServletConfig object All servlets have this method

EECS

46

init()
Not usually overridden BUT may override if:
If connecting to a Database only want to do this once
But would this servlet be the only servlet that needs to connect to that database? Other solutions may be better

M need t register with other objects May d to it ith th bj t Read information in from a file (eg proxy database)
Thinking ahead: servletContext objectwhen we need to share/set information for servlets in the same application.
EECS 47

Instance Variables
public class SillyClass extends HttpServlet{ private int age; public void init(){ Remember init is only ever called once age=0; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ ) th IOE ti S l tE ti { age = Integer.parseInt(request.getParameter(age)); response.setContentType(text/html); p yp ( ); PrintWriter out = response.getWriter(); out.println(<HTML><BODY>You are +age+ weeks old); out.println(</BODY></HTML>); }}

EECS

48

age=?

SillyClass //thread

SillyClass //thread

SillyClass //thread

16

20

28

EECS

49

Threads Access Same Resources


We do not know whose age will be displayed Solution 1:
Never use instance variables in servlets (some books say you cant what they mean is you shouldnt) Find a way to save information (state) about each user (ie each request) see later

Solution 2:
Synchronisation lock that makes a variable threadsafe [find out more in the Threads lecture or read Head First J ] Fi Java]
EECS 50

Access introducing the ServletContext object


Servlet S l tC fi object one per servlet (JSP) ServletConfig
Contains init params All requests made to a servlet can access this object

Web app ServletContext object one per web app


Web apps normally have several servlets/JSPs Used to access web app parameters that need to be seen by all pp p y servlets/JSPs in the application A misnomer as relates not to a servlet but the set of servlets and JSPs in the web app
EECS 51

The DD of the web app specifies the context parameters


<web-app > b <servlet> <servlet-name> </servlet-name><servlet-class> </servlet-class> <init-param><param-name>.</param-name> <param-value>.</param-value> </init-param> </servlet> l t> + other servlets th l t ServletContext </
object created and set up when web app is deployed Note: Not inside any servlet

<context-param> p <param-name>Principal_Email</param-name> <param-value>[email protected]</param-value> </context-param> </context param> .. </web-app>


both are strings

These are parameter name value pairs:


52

EECS

To access parameters in servlet code


ServletContext ctx = getServletContext()
out.println(ctx.getInitParameter(HOS_Email));
Note: Same name for accessor method as when accessing th d h i ServletConfig object

Context parameters generally more commonly used than Config


Why would you choose to store eg a DataBase (DB) name in the ServletContext object rather than ServletConfig?

EECS

53

Can access ServletContext().


directly getServletContext().getInitParameter(.) g from ServletConfig getServletConfig().getServletContext().getInitParameter() Latter useful if in a method of an auxiliary class, e.g. a bean, and only the ServletConfig object has been passed as a d l h S l C fi bj h b d parameter
EECS 54

ServletContext also has Attributes


Parameters are name value pairs, where both name and value are strings d l i Attributes are name value pairs where the name is a string, but the value is an object (that may not be a String)
Accessed by getAttribute(String) Set by setAttribute(String, Object)
We will look at this when we look at Listeners

EECS

55

Servlets 1: Key Points



EECS

How to call a servlet in an HTML form What a deployment descriptor does How to write a servlet Where to deploy files How to access client information Servlet life-cycle Initialisation g ServletConfig ServletContext
56

What we cannot do yet


Have a conversation with a client
Shopping basket Sessionobject

Run any code before a servlet starts


eg Database set up Listeners

Send client information, or control, to another servlet/JSP


Could be in another web server Redirectandforward
EECS

And other thingsfilters things filters etc


57

MVC: Beans, JSPs and Servlets


Although a servlet can be a completely self-contained program, to ease server side programming content should be split into: server-side
The business logic (content generation), which governs the relationship between input, processing, and output The presentation logic (content presentation, or graphic design rules), which determines how information is presented to the user

Typically,
the servlet handles the HTTP protocol and coordination of which other servlets & auxiliary class methods to call J Java classes/ beans the business logic (model), l /b th b i l i ( d l) Java Server Pages the presentation logic (view)

EECS

58

Advantages of servlets over other technologies, eg CGI


Efficient
S l t run in JVM. E h request is serviced using a thread rather Servlets i JVM Each ti i d i th d th than a new process (lower overhead)
Though some scripting languages e.g. PERL on certain web servers do this now

Convenient
P id i f t t Provides infrastructure that parses and decodes HTML forms th t dd d f

Powerful
Can communicate directly with web server Multiple servlets can share database connections Simplifies session tracking p g
EECS 59

Extra Example: Extracting unknown parameters and multiple values


NB. NB Case sensitive

String getParameter(String) used when

p parameter name is known


returns null if unknown parameter ( py g) parameter has no value returns "" (empty string) if p Else use Enumeration getParameters() to

obtain parameters p Then String[] getParameterValues(String) to obtain an array of values for each one y
returns null if unknown parameter returns a single string () if parameter has no values
EECS 60

A Big Form

EECS

61

BigForm.html
<form action= http://localhost:8080/servlet/elem004.ProcessBigForm action="http://localhost:8080/servlet/elem004 ProcessBigForm" method="post"> Single value parameters Please enter: <br><br> Your login: <input type="text" name="Login"> <br><br> Your favourite colour: <input type="radio" name= Colour value="blue">Blue type= radio name="Colour" value= blue >Blue <input type="radio" name="Colour" value="red">Red <input type="radio" name="Colour" value="green">Green <br><br> Which of these courses you are taking: <br> <input type="checkbox" name="Course" value="elem001">ELEM001 <input type="checkbox" name="Course" value="elem002">ELEM002 <input type="checkbox" name= Course value= elem003 >ELEM003 type= checkbox name="Course" value="elem003">ELEM003 <input type="checkbox" name="Course" value="elem004">ELEM004 <input type="submit" value="Send to Servlet"> </form>
EECS

<br> <br> <br> <br>

Multiple value parameter


62

ProcessBigForm.java (1)
out.println("<table border=1>"); // obtain all the f b i ll h forms parameters f from the request object h bj Enumeration paramNames = req.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); //obtain values for this parameter and check how many there are String [] paramValues = req.getParameterValues(paramName); St i V l tP t V l ( N ) if(paramValues.length == 1) { // a single value String paramVal = req.getParameter(paramName); out.println("<tr><td>" + paramName +"</td><td>" + paramVal + "</td></tr>");

}
EECS

63

ProcessBigForm.java (2)
else { // if several values print a list in the table out.println("<tr><td>" + paramName +"</td><td><ul>"); i l (" d " N " / d d l ") for(int i = 0; i < paramValues.length; i++) out.println( <li> out.println("<li>" + paramValues[i]); } out.println("</ul></td></tr>");

} out.println("</table>");

EECS

64

After Big Form is processed

EECS

NB. getParameterNames() returns them in no particular order

65

You might also like