1 chapter 2 the web tier web applications and web containersweb applications and web containers ...
TRANSCRIPT
1
Chapter 2 The Web Tier
Web Applications and Web Containers Dynamic Content Creation Application Designs Servlets Technology JSP Technology
2
Web Applications and Web Containers
Web application• A collection of HTML/XML documents, Web components and other resources • Provides dynamic and interactive content to browser-based clients. Web container • A runtime environment for a Web application• Provides Web components with a naming context and life cycle management.
3
Dynamic Content Creation
Common Gateway Interface (CGI) scripts Java servlets technology Java Server Pages technology
5
JavaServer Pages Technology
Providing a declarative, presentation-centric method
Content and display logic are separated Reusing code through a component-based architecture
9
EJB-Centric Applications
Model - Represents the data on which an application is based View - Presents the data represented by the model in a way that's targeted at a specific type of clientController -A Central point of control. Maintains the data in the model and ensures data and view consistency.
11
Servlet Technology
What Is a Servlet? Servlet API and Servlet life cycle HTTP Support Security Issues
12
What Is a Servlet?
A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model.
13
A servlet is a Java component that can be plugged into a Java-enabled web server to provide custom services:
•New features •Runtime changes to content •Runtime changes to presentation •New standard protocols (such as FTP) •New custom protocols
Servlets are designed to work within a request/response processing model.
What Is a Servlet?
14
Servlet API
Defining the interface between servlets and servers:•Package javax.servlet •Package javax.servlet.http
15
Servlet API Functions
Servlet life cycle management Access to servlet context Utility classes HTTP-specific support classes
16
Servlet Life Cycle
three main methods: • init() • service() • destroy()
two ancillary methods: •getServletConfig() •getServletInfo()
17
Servlet life cycle
If an instance of the servlet does not exist, the Web container
•Loads the servlet class.•Creates an instance of the servlet class. •Initializes the servlet instance by calling the init method. •Invokes the service method, passing a request and
response object. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.
18
Writing Service Methods Writing Service Methods
The general pattern for a service method is to extract information from the request, access external resources, and then populate the response based on that information. Getting Information from RequestsConstructing Responses
19
Getting Information from RequestsGetting Information from Requests
All requests implement the ServletRequest interface. This interface defines methods for accessing parameters, etal.
An input stream can be retrieved from the request for manually parsing the data:– getInputStream( )– getReader( )
HTTP servlets are passed an HTTP request object which contains the request URL, HTTP headers, query string, and so on.
20
Constructing ResponsesConstructing Responses
All responses implement the ServletResponse interface:
Retrieve an output stream to use to send data to the client. – getWriter(), return PrintWriter – getOutputStream( ), return ServletOutputStrea
m Indicate the content type (for example, text/html),
being returned by the response. Indicate whether to buffer output Set localization information.
21
Sample Servlet-1
import java.io.*;import javax.servlet.*;public class SampleServlet implements Servlet { private ServletConfig config; public void init (ServletConfig config) throws ServletException { this.config = config; } public void destroy() {} // do nothing public ServletConfig getServletConfig() { return config; } public String getServletInfo() { return "A Simple Servlet"; }
22
public void service (ServletRequest req, ServletResponse res ) throws ServletException, IOException { res.setContentType( "text/html" ); PrintWriter out = res.getWriter(); out.println( "<html>" ); out.println( "<head> ); out.println( "<title>A Sample Servlet</title>" ); out.println( "</head>" ); out.println( "<body>" ); out.println( "<h1>A Sample Servlet</h1>" ); out.println( "</body>" ); out.println( "</html>" ); out.close(); }}
Sample Servlet-2
23
Servlet Context
Servlet Initialization Information
Server Context Information
Servlet Context During a Service Request
24
Utility Classes
Interface javax.servlet.SingleThreadModel for
writing simple servlets
Two exception classes
•javax.servlet.ServletException
•javax.servlet.UnavailableException
25
HTTP Protocal
HTTP defines a set of text-based request messages called HTTP methods.
The HTTP methods include:– GET: Retrieves the resource identified by the request URL – HEAD: Returns the headers identified by the request URL – POST: Sends data of unlimited length to the Web server – PUT: Stores a resource under the request URL – DELETE: Removes the resource identified by the request
URL – OPTIONS: Returns the HTTP methods the server supports – TRACE: Returns the header fields sent with the TRACE
request
26
HTTP Support
Javax.servlet.http.HttpServlet implements the javax.servlet.Servlet interface.
HttpServlet methods:– Service(): Dispatches the HTTP message to one of severial
special methods.– Others:Called by the server (via the service method) to allow a serv
let to handle a GET, Post … request.• doGet(): • doDelete()• doOptions()• doPost()• doTrace()
To write an HTTP servlet, you can extend HttpServlet and add your own custom processing.
30
What Is a JSP Page?
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format, such as HTML, WML, and XML; and JSP elements, which construct dynamic content.
31
Components of JSP pages
Static HTML/XML components. Special JSP tags Snippets of code written in the Java programming language called "scriptlets."
32
JSP Advantages
Separation of static from dynamic content Write Once Run Anywhere Dynamic content can be served in a variety of formats Recommended Web access layer for n-tier architecture Completely leverages the Servlet API
35
… ...public class _0005cjsp_0005cjsptest_0002ejspjsptest_jsp_0extends HttpJspBase { … …public void _jspService(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException {JspFactory _jspxFactory = null;… …Date d = new Date();String today = DateFormat.getDateInstance().format(d);// end// beginout.write("\r\nToday is: \r\n<em> ");…...
Translation
40
Directives
<%@ ... %> tag.
two primary directives •page
<%@ page import="java.util.*, com.foo.*" buffer="16k" %>•include
<%@ include file="copyright.html" %>
41
scripting elements
Declarations ,<%! ... %> tag. <%! int i=0; %> Expressions, <%= ... %> tag <%= fooVariable %> <%= fooBean.getName() %> Scriptlets, <% ... %> tag Comments, <%-- ... --%> tag
42
Standard Actions
Using JavaBean Components <jsp:useBean id="user" class="com.jguru.Person" scope="session" /> Forwarding Requests <jsp:forward page="somePage.jsp" /> Including Requests <jsp:include page="shoppingcart.jsp" flush="true"/>
43
Java BeanJava Bean
JAVA BEANS components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions can be a JavaBeans component.
44
Java Bean Design PatternJava Bean Design Pattern
The bean encapsulates its properties by declaring them private;– Read/write, read-only, or write-only– Simple, which means it contains a single value, or indexed, which
means it represents an array of values The bean provides public accessor (getter/setter)
methods for reading and modifying properties’ values.– For each readable property, the bean must have a method of the f
ormPropertyClass getProperty() { ... }– For each writable property, the bean must have a method of the f
orm setProperty(PropertyClass pc) { ... }
45
Java Bean Design PatternJava Bean Design Pattern
In addition to the property methods, a JavaBeans component must define a constructor that takes no parameters.
46
An Example of Java BeanAn Example of Java Beanpublic class Currency {
private Locale locale;private double amount;public Currency() {
locale = null;amount = 0.0;}
public void setLocale(Locale l) {locale = l;}
public void setAmount(double a) {amount = a;}
public String getFormat() {NumberFormat nf =NumberFormat.getCurrencyInstance(locale);return nf.format(amount);}
}
49
Servlets and JSP Pages
Can be used to solve identical problems. Servlets are expressed in Java ; JSP pages are text-based documents A servlet uses print statements to post HTML data
•Cannot preview the look and feel of an HTML page
•Difficult to maitain when data or its display format needs changes
50
JSP can use graphical development tools , use JavaBeans components and/or custom tags that handle complex dynamic formatting of HTML Like servlets, JSP can work in a portable platform- or application-independent means and supports a reusable component model A sophisticated Web application can consist solely of JSP pages, custom tags, and JavaBeans components servlets are rarely necessary.
Servlets and JSP Pages