Download Servlet - Computer Science and Engineering

Document related concepts
no text concepts found
Transcript
COMP9321 Web Application Engineering
Semester 2, 2016
Dr. Amin Beheshti
Service Oriented Computing Group, CSE, UNSW Australia
Week 2
http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2445
COMP9321, 16s2, Week 2
1
Different Layers in an Application
COMP9321, 16s2, Week 2
2
Presentation Layer
HTML is a markup language for describing Web documents (Web pages).
is-a
set of markup tags
describe
different document content
html -> describes an HTML document.
head -> provides information about the document.
title -> provides a title for the document.
body -> describes the visible page content.
h1 -> describes a heading.
p -> describes a paragraph
COMP9321, 16s2, Week 2
3
Presentation Layer
HTML forms are used to collect user input.
If you click "Submit", the form-data will be sent to a
page called "main.jsp".
COMP9321, 16s2, Week 2
4
Presentation Layer
HTML <form> method attribute
specifies
how to send form-data
as
 URL variables (with method="get") , or
 HTTP post transaction (with method="post").
Method? Get/Post
COMP9321, 16s2, Week 2
5
Presentation Layer
HTML <form> method attribute
action_page.jsp?firstname=Tim&lastname=Berners-Lee
GET:
• Appends form-data into the URL in name/value pairs
• The length of a URL is limited (about 2-3k characters)
• Never use GET to send sensitive data! (will be visible in the URL)
• Useful for form submissions where a user want to bookmark the result,
to enable quick access in future.
Google("HTML Links - Create a Bookmark“)
• GET is better for non-secure data, like query strings in Google.
• GET is supposed to be used for getting things - information retrieval
With the GET method, the HTTP request
looks like this:
COMP9321, 16s2, Week 2
6
Presentation Layer
HTML <form> method attribute
POST:
• Appends form-data inside the body of the HTTP request (data is not
shown in URL).
• Has no size limitations.
• Form submissions with POST cannot be bookmarked.
Clicking a bookmark will always fire a GET request!
• POST is supposed to be used for sending data to be processed - update or
change something on the server
When sent using the POST method, the HTTP request
looks like this:
COMP9321, 16s2, Week 2
7
Static vs. Dynamic Web Page
A static web page is delivered to the user exactly as stored, in contrast to
dynamic web pages which are generated by a web application, and on demand!
Static websites:
• Quick to develop
• Cheap to develop
• Cheap to host
Dynamic websites:
• Much more functional website
• Much easier to update
• New content brings people back to the site and helps in the search engines
• Can work as a system to allow staff or users to collaborate
• Slower / more expensive to develop
• Hosting costs
COMP9321, 16s2, Week 2
8
Static vs. Dynamic Web Page
A static web page is delivered to the user exactly as stored, in contrast to
dynamic web pages which are generated by a web application, and on demand!
is-a
web page whose construction is controlled by an
application server processing server-side scripts.
is-a
e.g.
software framework that provides both facilities to create web
applications and a server environment to run them.
Java application servers
http://docs.oracle.com/javaee/6/tutorial/doc/
It's core set of API and features are defined by Java EE.
The Web modules include Java Servlets and Java Server Pages.
COMP9321, 16s2, Week 2
9
Java Servlets
http://java.sun.com/products/servlet/index.jsp
http://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html
COMP9321, 16s2, Week 2
10
Apache Tomcat
An open source implementation of the Java Servlet, JavaServer Pages, Java
Expression Language and Java WebSocket technologies..
Tomcat's Installed Directory Structure:
• bin: for Tomcat's binaries and startup scripts.
• conf: global configuration applicable to all the webapps.
• lib: Keeps the JAR-file that are available to all webapps.
• logs: contains the engine logfile Catalina ("Catalina" is the codename
for Tomcat 5 and above).
• webapps: the default appBase - web applications base directory of the
host localhost.
• work: contains the translated servlet source files and classes of JSP.
• temp: temporary files.
COMP9321, 16s2, Week 2
11
Making servlets available in the Web container
Google(“what is 8080 port”)
e.g., Ant tasks for Tomcat, Eclipse Web Tools Platform (WTP)
COMP9321, 16s2, Week 2
12
How container handles the Servlet request
1. Client Browse Servlet URL: User clicks a link that has a URL of Servlet.
2. HttpServletRequest and HttpServletResponse: Container (e.g. Apache Tomcat) sees
that the request is for servlet , so create two objects : Request and Response
COMP9321, 16s2, Week 2
((HeadFirst) p.42)
http://www.jitendrazaa.com/blog/java/servlet/
13
How container handles the Servlet request
3. Create Thread for Servlet: Container finds correct servlet using “web.xml” file; and
Creates/Allocate thread for that request …
Google(“what is a thread?”)
A thread is a single sequential flow of
control within a program.
4. Service method of servlet: Container calls the servlets service() method, on the type
of request, service calls doGet() or doPost() methods.
COMP9321, 16s2, Week 2
((HeadFirst) p.42)
http://www.jitendrazaa.com/blog/java/servlet/
14
How container handles the Servlet request
5. Servlet response object: Lets assume that service calls the doPost() method. doPost()
method generates dynamic page and add the page in response object.
6. destroy response and request object: Thread completes, container converts the response
object into HttpResponse object and destroys the response and request object.
COMP9321, 16s2, Week 2
((HeadFirst) p.42)
http://www.jitendrazaa.com/blog/java/servlet/
15
Your Servlet inherits "lifecycle" methods
COMP9321, 16s2, Week 2
16
A typical Servlet looks like this
Note: No main() - the container calls the servlet methods like doGet() through service()
COMP9321, 16s2, Week 2
17
Servlet Names
COMP9321, 16s2, Week 2
18
Servlet Names
Why do we need a servlet name?
It allows you to have multiple servlet mappings on a single servlet instance without the
unnecessary need to create a separate instance per mapping. More?
<servlet>
<servlet-name>someServlet</servlet-name>
<servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>someServlet</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>someServlet</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>someServlet</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
COMP9321, 16s2, Week 2
19
A Lifecycle of a Servlet
The Web container controls the lifecycle of a servlet class:
COMP9321, 16s2, Week 2
20
Servlet's Life
((HeadFirst) p.99)
COMP9321, 16s2, Week 2
21
Why care about this initialisation details?
Once the servlet is initialised, the servlet gets access to two important objects:
ServletConfig and ServletContext
ServletConfig:
•
•
•
•
•
It is implemented by the servlet container to initialize a single servlet using init();
you can pass initialization parameters to the servlet using the web.xml;
For understanding, this is similar to a constructor in a java class;
One ServletCong object per servlet;
Use it to pass deploy-time information to the servlet (any info. that you do not want to
hard-code into the servlet);
• Parameters are configured in the deployment descriptor;
• Use it to access the ServletContext;
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>com.javapapers.ServletConfigTest</servlet-class>
<init-param>
<param-name>topic</param-name>
<param-value>Difference between ServletConfig and ServletContext</param-value>
</init-param>
</servlet>
COMP9321, 16s2, Week 2
22
Why care about this initialisation details?
Once the servlet is initialised, the servlet gets access to two important objects:
ServletConfig and ServletContext
ServletContext:
• It is implemented by the servlet container for all servlets to communicate with its
servlet container;
• For example, to get the MIME type of a file, to get dispatch requests, or to write to a
log file. That is to get detail about its execution environment;
• For understanding, this is like a application global variable mechanism for a single
web application deployed in only one JVM;
• One ServletContext per Web application (they should have named it AppContext);
• Use it to access parameters that are Web application-wide;
<context-param>
<param-name>globalVariable</param-name>
<param-value>comp9321</param-value>
</context-param>
• The ServletContext object is contained within the ServletConfig object, and can be
accessed using the ServletConfig object within a servlet; You can specify param-value
pairs for ServletContext object in <context-param> tags in web.xml file.
COMP9321, 16s2, Week 2
23
Why care about this initialisation details?
So to sum up there is only one ServletContext for an entire app and all the parts of the web
app share it. But each servlet in the app has its own ServletConfig.
Remember if you change a value you must redeploy the web app in order to get the new value
because a servlet is only initialized once at the beginning of its life.
COMP9321, 16s2, Week 2
24
ServletRequest & ServletResponse Interfaces
The container implements HttpServletRequest and HttpServletRequest
All you should care about is when servlet is called, the service() passes two
objects to your servlet.
COMP9321, 16s2, Week 2
25
HttpServletRequest, HttpServletResponse
COMP9321, 16s2, Week 2
26
A simple servlet that generates a text message
COMP9321, 16s2, Week 2
27
RequestDispatcher in Servlet
• The RequestDispatcher interface provides the facility of dispatching the
request to another resource, e.g., servlet, jsp, or html.
• This interface can also be used to include the content of another resource also.
• It is one of the way of servlet collaboration.
The RequestDispatcher interface provides two methods: forward and include
• Forward: Forwards a request from a servlet to another resource
(servlet, JSP file, or HTML file) on the server.
public void forward(ServletRequest request,ServletResponse response)
COMP9321, 16s2, Week 2
http://www.javatpoint.com/
28
RequestDispatcher in Servlet
• The RequestDispatcher interface provides the facility of dispatching the
request to another resource, e.g., servlet, jsp, or html.
• This interface can also be used to include the content of another resource also.
• It is one of the way of servlet collaboration.
The RequestDispatcher interface provides two methods: forward and include
• Include: Includes the content of a resource (servlet, JSP page, or HTML file)
in the response.
public void include(ServletRequest request,ServletResponse response)
COMP9321, 16s2, Week 2
http://www.javatpoint.com/
29
Attributes and Sharing Attributes
COMP9321, 16s2, Week 2
30
Who has access to the board and how long does it live?
COMP9321, 16s2, Week 2
31
Attributes API
The return type for attributes is an Object, whereas the return type for a parameter is a String.
COMP9321, 16s2, Week 2
HeadFirst, p. 189
32
Request attributes and Request dispatching
COMP9321, 16s2, Week 2
33
Managing the User State
COMP9321, 16s2, Week 2
34
Managing the User State
A problem in HTTP request/response:
• HTTP is a stateless protocol.
• A single request/response;
• Nothing is remembered 'between requests' from the same user;
• Web applications need to maintain users + their data.
It is a programmer's responsibility:
• The term "session" is used to represent the data associated with one user while
she navigates around a Web application.
• Session is a conversional state between client and server.
• Session can consists of multiple request and response between client and server.
• Since HTTP is stateless, the only way to maintain a session is when some unique
information about the session (session id) is passed between server and client in
every request and response.
COMP9321, 16s2, Week 2
35
Session Management
COMP9321, 16s2, Week 2
36
Session Management
COMP9321, 16s2, Week 2
37
Session Management
COMP9321, 16s2, Week 2
38
URL Rewriting
COMP9321, 16s2, Week 2
39
HTML hidden fields
COMP9321, 16s2, Week 2
40
Cookies
• Cookies are text files stored on the client computer and they are kept for
various information tracking purpose.
• Java Servlets transparently supports HTTP cookies.
• There are three steps involved in identifying returning users:
• Server script sends a set of cookies to the browser. e.g. session id
• Browser stores this information on local machine for future use.
• Next time, browser sends request + those cookies to the server
and server uses that information to identify the user.
COMP9321, 16s2, Week 2
41
Cookies
The Anatomy of a Cookie:
• Cookies are usually set in an HTTP header.
• JavaScript can also set a cookie directly on a browser.
• A servlet that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Mon, 03 Aug 2015 17:03:38 GMT
Server: Apache…
Set-Cookie: name=xyz; expires=Monday, 03-Aug-15 22:00:00 GMT;
path=/; domain=comp9321.com
Connection: close
Content-Type: text/html
• Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
• The name and value will be URL encoded.
• Expires field is an instruction to the browser to "forget" the cookie after the given time/date.
COMP9321, 16s2, Week 2
42
Servlet Cookies Methods
Method Name
Method Description
setDomain()
sets the domain to which cookie applies, for example comp9321.com.
getDomain()
gets the domain to which cookie applies, for example comp9321.com.
setMaxAge()
sets how much time (in seconds) should elapse before the cookie expires.
If you don't set this, the cookie will last only for the current session.
getMaxAge()
returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie
will persist until browser shutdown.
getName()
returns the name of the cookie. The name cannot be changed after creation.
setValue()
sets the value associated with the cookie.
getValue()
gets the value associated with the cookie.
setPath()
sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all
URLs in the same directory as the current page as well as all subdirectories.
getPath()
gets the path to which this cookie applies.
setSecure()
sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL)
connections.
setComment()
specifies a comment that describes a cookie's purpose. The comment is useful if the browser
presents the cookie to the user.
getComment()
returns the comment describing the purpose of this cookie, or null if the cookie has no comment.
http://www.tutorialspoint.com/servlets/
COMP9321, 16s2, Week 2
43
Setting Cookies with Servlet
Setting cookies with servlet involves three steps:
1. Creating a Cookie object:
Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of the
following characters: [ ] ( ) = , " / ? @ : ;
2. Setting the maximum age (in seconds):
cookie.setMaxAge(60*60*24);
3. Sending the Cookie into the HTTP response headers
response.addCookie(cookie);
http://www.tutorialspoint.com/servlets/
COMP9321, 16s2, Week 2
44
HTTP Sessions with JSESSIONID cookie
COMP9321, 16s2, Week 2
45
HTTP Sessions Interface
COMP9321, 16s2, Week 2
46
An example of using HttpSession object: the scenario
COMP9321, 16s2, Week 2
47
The Journey Object
COMP9321, 16s2, Week 2
48
Using a Journey Object
COMP9321, 16s2, Week 2
49
How session tracking works ...
COMP9321, 16s2, Week 2
50
Getting rid of Sessions
COMP9321, 16s2, Week 2
51
Servlets ...
COMP9321, 16s2, Week 2
52
10 Minutes Break
then
Servlet Examples!
COMP9321, 16s2, Week 2
53
Installing Apache Tomcat…
download
unzip
COMP9321, 16s2, Week 2
54
Installing Apache Tomcat…
Next: Verifying Tomcat's Java Dependencies
Tomcat 8.0 requires Java 7 or later …
System variables:
“Java_Home”
Check
Didn’t set? then
Google
How to Set JAVA_HOME environment variable on
Mac
Windows
…
Notice: we use JDK (not JRE) as we like to experiment and make changes to the example
servlets, so we need to compile Java code in the servlets and produce .class files …
COMP9321, 16s2, Week 2
55
Installing Apache Tomcat…
e.g. in Windows …
click
COMP9321, 16s2, Week 2
56
Start and Stop Tomcat
COMP9321, 16s2, Week 2
57
Start and Stop Tomcat
COMP9321, 16s2, Week 2
58
Servlet Examples
• Download the Servlet-Example zip file
• Unzip and copy the folder under “webapps” folder
COMP9321, 16s2, Week 2
59
Servlet Examples
COMP9321, 16s2, Week 2
60
Servlet Examples: Hello World
COMP9321, 16s2, Week 2
61
Servlet Examples: Request Info
COMP9321, 16s2, Week 2
62
Servlet Examples: Request Headers
COMP9321, 16s2, Week 2
63
Other Examples, LAB
COMP9321, 16s2, Week 2
64
COMP9321, 16s2, Week 2
65