Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
3 4
Advanced Topics:
? Session Tracking
? Servlet Filters
?
?
Servlet life-cycle events
Including, forwarding to, and redirecting to
Servlet in a
?
other web resources
Concurrency Issues Big Picture of J2EE
? Invoker Servlet
5 6
An extensible Web technology that uses template data, Java Servlet A Java program that
custom elements, scripting languages, and server-side extends the functionality of a Web
Java objects to return dynamic content to a client. server, generating dynamic content
Typically the template data is HTML or XML elements. and interacting with Web clients
The client is often a Web browser. using a request-response
paradigm.
7 8
What is Servlet? First Servlet Code
? Java™ objects which are based on servlet Public class HelloServlet extends HttpServlet {
framework and APIs and extend the
functionality of a HTTP server. public void doGet(HttpServletRequest request,
HttpServletResponse
? Mapped to URLs and managed by response){
container with a simple architecture response.setContentType("text/html");
PrintWriter out = response.getWriter();
? Available and running on all major out.println("<title>Hello World!</title>");
}
web servers and app servers ...
? Platform and server independent }
9 10
11 12
Advantages of Servlet What is JSP Technology?
? No CGI limitations ? Enables separation of business logic from
? Abundant third-party tools and Web servers presentation
supporting Servlet – Presentation is in the form of HTML or
XML/XSLT
? Access to entire family of Java APIs
– Business logic is implemented as Java Beans or
? Reliable, better performance and scalability custom tags
? Platform and server independent – Better maintainability, reusability
? Secure ? Extensible via custom tags
? Most servers allow automatic reloading of ? Builds on Servlet technology
Servlet's by administrative action
13 14
15 16
Servlets and JSP - Comparison
JSP Benefits
Servlets JSP ? Content and display logic are separated
• HTML code in Java • Java-like code in HTML
? Simplify development with JSP, JavaBeans
• Any form of Data • Structured Text and custom tags
• Not easy to author a • Very easy to author a ? Supports software reuse through the use of
web page web page
components
• Code is compiled into a
servlet ? Recompile automatically when changes are
made to the source file
? Easier to author web pages
? Platform-independent
17 18
19 20
Servlet Request and Response
Model
Servlet Container
Request
Response Model
Request
HTTP Servlet
Response
Web
Web Response
Server
21 22
the request to another servlet or JSP page ? HTTP headers, cookies, etc
23 24
HTTP HTTP GET and POST
? The most common client requests
? HTTP request contains – HTTP GET & HTTP POST
– header ? GET requests:
– a method – User entered information is appended to the URL in a
query string
?
Get: Input form data is passed as part of URL
– Can only send limited amount of data
? Post: Input form data is passed within message body
?
Put
? .../servlet/ViewCourse?FirstName=Sang&LastName=Shin
? Header ? POST requests:
– request data – User entered information is sent as data (not appended
to URL)
– Can send any amount of data
25 26
First Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
GenericServlet HttpSession
HttpServletRequest HttpServletResponse
29 30
Http
request
Load Invoke
No
init( ) destroy( )
Ready
Init parameters
Http
response Yes
Run
Servlet
Servlet Container
? service() - implementation
33 34
Service( )
Service( )
Response doPost( )
Response
initialized }
}
– init (ServletConfig servletConfig) in Servlet interface
57 58
if (dispatcher != null)
dispatcher.include(request, response);
...
59 60
Why HttpSession?
? Need a mechanism to maintain client
state across a series of requests from a
same user (or originating from the same
browser) over some period of time
Session ?
– Example: Online shopping cart
Yet, HTTP is stateless
63 64
What is Servlet Request?
? Contains data passed from client to servlet
? All servlet requests implement ServletRequest
interface which defines methods for accessing
– Client sent parameters
Servlet Request – Object-valued attributes
– Locales
(HttpServletRequest) –
–
Client and server
Input stream
– Protocol information
– Content type
– If request is made over secure channel (HTTPS)
65 66
Requests
Getting Client Sent Parameters
data,
client, server, header ? A request can come with any number of
servlet itself parameters
Request Servlet 1 ? Parameters are sent from HTML forms:
– GET: as a query string, appended to a URL
– POST: as encoded POST data, not appeared in the URL
Servlet 2
? getParameter("paraName")
– Returns the value of paraName
Response Servlet 3 – Returns null if no such parameter is present
– Works identically for GET and POST requests
Web Server 67 68
A Sample FORM using GET A Sample FORM using GET
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Collecting Three Parameters</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Please Enter Your Information</H1>
<FORM ACTION="/sample/servlet/ThreeParams">
First Name: <INPUT TYPE="TEXT" NAME="param1"><BR>
Last Name: <INPUT TYPE="TEXT" NAME="param2"><BR>
Class Name: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>
</BODY>
</HTML>
69 70
73 74
75 76
Getting Client Information Getting Server Information
? Servlet can get client information from ? Servlet can get server's information:
the request – String request.getServerName()
–
?
e.g. "www.sun.com"
String request.getRemoteAddr()
? Get client's IP address – int request.getServerPort()
–
?
e.g. Port number "8080"
String request.getRemoteHost()
? Get client's host name
77 78
HTTP Request URL: [request path] HTTP Request URL: [query string]
? http://[host]:[port]/[request path]?[query string] ? http://[host]:[port]/[request path]?[query string]
? [request path] is made of ? [query string] are composed of a set of parameters
– Context: /<context of web app> and values that are user entered
– Servlet name: /<component alias> ? Two ways query strings are generated
– Path information: the rest of it – A query string can explicitly appear in a web page
? Examples ?
<a href="/bookstore1/catalog?Add=101">Add To Cart</a>
– http://localhost:8080/hello1/greeting ? String bookId = request.getParameter("A d d") ;
– http://localhost:8080/hello1/greeting.jsp – A query string is appended to a URL when a form with a
– http://daydreamer/catalog/lawn/index.html GET HTTP method is submitted
?
http://localhost/hello1/greeting?username=Monica+Clinton
? String userName=request.getParameter(“username”)
83 84
Context, Path, Query, Parameter HTTP Request Headers
Methods
? HTTP requests include headers which provide
? String getContextPath() extra information about the request
? String getQueryString() ? Example of HTTP 1.1 Request:
? String getPathInfo() GET /search? keywords= servlets+ jsp HTTP/ 1.1
Accept: image/ gif, image/ jpg, */*
? String getPathTranslated() Accept-Encoding: gzip
Connection: Keep- Alive
Cookie: userID= id456578
Host: www.sun.com
Referer: http:/www.sun.com/codecamp.html
User-Agent: Mozilla/ 4.7 [en] (Win98; U)
85 86
89 90
91 92
Authentication & User Security Cookie Method (in
Information Methods HTTPServletRequest)
? String getRemoteUser() ? Cookie[] getCookies()
– name for the client user if the servlet has been
– an array containing all of the Cookie objects the
password protected, null otherwise
client sent with this request
? String getAuthType()
– name of the authentication scheme used to protect
the servlet
? boolean isUserInRole(java.lang.String role)
– Is user is included in the specified logical " role" ?
? String getRemoteUser()
– login of the user making this request, if the user
has been authenticated, null otherwise
93 94
95 96
Responses Response Structure
Status Code
Request Servlet 1
Response Headers
Response Servlet 3
Web Server
97 98
Status Code in
Http Response
99 100
Methods for Setting HTTP Example of HTTP Response
Response Status Codes Status
? public void setStatus(int statusCode) HTTP/ 1.1 200 OK
Content-Type: text/ html
– Status codes are defined in HttpServletResponse <! DOCTYPE ...>
– <HTML
Status codes are numeric fall into five general ...
categories: </ HTML>
? 100-199 Informational
? 200-299 Successful
?
300-399 Redirection
? 400-499 Incomplete
?
500-599 Server Error
– Default status code is 200 (OK) 101 102
message) try {
returnAFile(fileName, out)
– Wraps message inside small HTML document }
catch (FileNotFoundException e)
{ response.sendError(response.SC_NOT_FOUND);
}
105 106
113 114
117 118
121 122