Sei sulla pagina 1di 46

Web Components & Web Container

Confidential
 Web components are in the form of either Servlet or JSP (along with
JavaBean's andcustom tags)
 Web components run in a Web container

 Tomcat and Resin are popular web containers


 All J2EE compliant app servers (Sun Java System
App Server) provide web containers
 Web container provides system services to Web components

 Request dispatching, security, and life cycle


management

Confidential
 Web Application is a deployable package

 Web components (Servlets and JSP's)


 Static resource files such as images
 Helper classes
 Libraries
 Deployment descriptor (web.xml file)
 Web Application can be represented as

 A hierarchy of directories and files (unpacked form) or


 *.WAR file reflecting the same hierarchy (packed form)

Confidential
Web Request Handling

Confidential
Java Web Application Technologies

Confidential
Steps for creating a Web Application

 Write (and compile) the Web component code (Servlet or JSP) and
helper classes referenced by the web component code
 Create any static resources (for example, images or HTML pages)
 Create deployment descriptor (web.xml)
 Build the Web application (*.war file or deployment-ready directory)
 Deploy the web application into a Web container
 Web clients are now ready to access them via URN

Confidential
Write and compile the Web component code

 Create development tree structure


 Write either servlet code or JSP pages along with related helper
code
 Create build.xml for Ant-based build (and other application
development life-cycle management) process
 IDE (i.e. eclipse) handles all these chores

Confidential
Development Structure

 Hello

 src
 webroot
 WEB-INF
 classes
 GreetingServlet.class
 ResponseServlet.class
 web.xml

 duke.waving.gif

 build.xml

Confidential
Deploy structure of Web application

Confidential
Create *.WAR file

 Use “jar cvf <filename>.war .” command under build directory


 Use IDE (eclipse) export in java web archive format
 Use ant tool after putting proper build instruction in build.xml file

 “asant create-war” (under J2EE 1.4 tutorial)

Confidential
Web Applications Deployment Descriptor (web.xml)

 Prolog
 Alias Paths
 Context and Initialization Parameters
 Event Listeners
 Filter Mappings
 Error Mappings
 Reference to Environment Entries, Resource environment entries,
or Resources

Confidential
Prolog (of web.xml)

 Every XML document needs a prolog

 <?xml version="1.0" encoding="ISO-8859-


1"?>
 <!DOCTYPE web-app PUBLIC "-//Sun
Microsystems, Inc.//DTD Web Application
2.3//EN"
"http://java.sun.com/dtd/webapp_2_3.dtd">

Confidential
Alias Paths (of web.xml)

 When a request is received by Servlet container,it must determine


which Web component in a which web application should handle the
request. It does so by mapping the URL path contained in the
request to a Web component
 A URL path contains the context root and alias path

 – http://<host>:8080/context_root/alias_path
 Alias Path can be in the form of either

 /alias-string (for servlet) or


 /*.jsp (for JSP)

Confidential
Alias Paths (of web.xml)

<servlet>
<servlet-name>greeting</servlet-name>
<display-name>greeting</display-name>
<description>no description</description>
<servlet-class>GreetingServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>response</servlet-name>
<display-name>response</display-name>
<description>no description</description>
<servlet-class>ResponseServlet</servlet-class>
</servlet>

Confidential
<servlet-mapping>
<servlet-name>greeting</servlet-name>
<url-pattern>/greeting</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>response</servlet-name>
<url-pattern>/response</url-pattern>
</servlet-mapping>

Confidential
Context and Initialization Parameters (of web.xml)

 Represents application context


 Can be shared among Web components in a WAR file

<web-app>
...
<context-param>
<param-name>
javax.servlet.jsp.jstl.fmt.localizationContext
</param-name>
<param-value>messages.BookstoreMessages</param-value>
</context-param>
...
</web-app>

Confidential
Event Listeners (of web.xml)

 Receives servlet life-cycle events

<listener>
<listener-class>listeners.ContextListener</listener-class>

</listener>

Confidential
Filter Mappings (of web.xml)

 Specify which filters are applied to a request, and in what order

<filter>
<filter-name>OrderFilter<filter-name>
<filter-class>filters.OrderFilter<filter-class>
</filter>
<filter-mapping>
<filter-name>OrderFilter</filter-name>
<url-pattern>/receipt</url-pattern>
</filter-mapping>

Confidential
Error Mappings (of web.xml)

 Maps status code returned in an HTTP response to a Java


programming language exception returned by any Web component
and a Web resource

<error-page>
<exception-type>exception.OrderException</exception-type>
<location>/errorpage.html</location>
</error-page>

Confidential
References (of web.xml)

 Need when web components make references to environment


entries, resource environment entries, or resources such as
databases

<resource-ref>
<res-ref-name>jdbc/BookDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

Confidential
Example web.xml of hello2

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>hello</display-name>

<servlet>
<display-name>GreetingServlet</display-name>
<servlet-name>GreetingServlet</servlet-name>
<servlet-class>servlets.GreetingServlet</servlet-class>
</servlet>
<servlet>
<display-name>ResponseServlet</display-name>
<servlet-name>ResponseServlet</servlet-name>
<servlet-class>servlets.ResponseServlet</servlet-class>
</servlet>
Confidential
<servlet-mapping>
<servlet-name>GreetingServlet</servlet-name>
<url-pattern>/greeting</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>ResponseServlet</servlet-name>
<url-pattern>/response</url-pattern>
</servlet-mapping>

</web-app>

Confidential
Servlet

 Servlet in big picture of J2EE


 Servlet request & response model
 Servlet life cycle
 Servlet scope objects
 Servlet request
 Servlet response: Status, Header, Body
 Error Handling

Confidential
 Session Tracking
 Servlet Filters
 Servlet life-cycle events
 Including, forwarding to, and redirecting to other web resources
 Concurrency Issues
 Invoker Servlet

Confidential
What is Servlet?

 Java™ objects which are based on servlet framework and APIs and
extend the functionality of a HTTP server.
 Mapped to URLs and managed by container with a simple
architecture
 Available and running on all major web servers and app servers
 Platform and server independent

Confidential
CGI versus Servlet

Confidential
Confidential
Advantages of Servlet

 No CGI limitations
 Abundant third-party tools and Webservers supporting Servlet
 Access to entire family of Java APIs
 Reliable, better performance and scalability
 Platform and server independent
 Secure
 Most servers allow automatic reloading of Servlet's by administrative
action

Confidential
First Servlet Code

Public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse
response){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>Hello World!</title>");
}
...
}

Confidential
Servlet Request and Response Model

Confidential
What does Servlet Do?

 Receives client request (mostly in the form of HTTP request)


 Extract some information from the request
 Do content generation or business logic process (possibly by
accessing database, invoking EJBs, etc)
 Create and send response to client (mostly in the form of HTTP
response) or forward the request to another servlet or JSP page

Confidential
Requests and Responses

 What is a request?

 Information that is sent from client to a server


 Who made the request
 What user-entered data is sent
 Which HTTP headers are sent
 What is a response?

 Information that is sent to client from a server


 Text(html, plain) or binary(image) data
 HTTP headers, cookies, etc

Confidential
HTTP

 HTTP request contains

 header
 a method
 Get: Input form data is passed as part of URL
 Post: Input form data is passed within message body
 Put
 Header

 request data

Confidential
HTTP GET and POST

 The most common client requests

 HTTP GET & HTTP POST


 GET requests:

 User entered information is appended to the URL in a query


string
 Can only send limited amount of data
 .../servlet/ViewCourse?FirstName=Sang&LastName=Shin

 POST requests:

 User entered information is sent as data (not appended to URL)


 Can send any amount of data

Confidential
First Servlet

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
Public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>First Servlet</title>");
out.println("<big>Hello Code Camp!</big>");
}
}

Confidential
Servlet Interfaces & Classes

Confidential
Servlet Life-Cycle

Confidential
Servlet Life Cycle Methods

Confidential
Servlet Life Cycle Methods

 Invoked by container

 Container controls life cycle of a servlet


 Defined in

 javax.servlet.GenericServlet class or
 init()
 destroy()
 service() - this is an abstract method

 javax.servlet.http.HttpServlet class
 doGet(), doPost(), doXxx()
 service() - implementation

Confidential
Servlet Life Cycle Methods

 init()

 Invoked once when the servlet is first instantiated


 Perform any set-up in this method
 Setting up a database connection
 destroy()

 Invoked before servlet instance is removed


 Perform any clean-up
 Closing a previously created database

 connection

Confidential
Service() Method

Confidential
doGet() and doPost() Methods

Confidential
Things You Do in doGet() & doPost()

 Extract client-sent information (HTTP parameter) from HTTP


request
 Set (Save) and get (read) attributes to/from Scope objects
 Perform some business logic or access database
 Optionally forward the request to other web components (Servlet or
JSP)
 Populate HTTP response message and send it to client

Confidential
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
Public class HelloServlet extends HttpServlet { public void
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>First Servlet</title>");
out.println("<big>Hello J2EE Programmers! </big>");

}
}

Confidential
Steps of Populating HTTP Response

 Fill Response headers


 Set some properties of the response

 Buffer size
 Get an output stream object from the response
 Write body content to the output stream

Confidential
Example: Simple Response

Public class HelloServlet extends HttpServlet { public void


doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Fill response headers


response.setContentType("text/html");
// Set buffer size
response.setBufferSize(8192);
// Get an output stream object from the response
PrintWriter out = response.getWriter();
// Write body content to output stream
out.println("<title>First Servlet</title>");
out.println("<big>Hello J2EE Programmers! </big>");

}
}

Confidential

Potrebbero piacerti anche