Transcript PPT

Webb applications
Chapter 13
Lecture 7
1
Today we will deal with





Web applications
Servlets
JSP
Good design in web
apps
In 1999 this was
cutting edge, big
bubbles.
2
Client / server
Client
DNS helps in looking
up the address
Protocol (http or other)
Listens on a “port”
Server
3
“Web site” vs “Web app”



Web site
•
•
•
The first use of a web site was to distribute information, such as static
HTML documents.
Server side content on a web site is static.
All application processing occurs on the client side.
•
•
•
Provides server side application processing.
Web browser - a Web-based interface to a server-based application.
B2B, B2C
Web applications (“Web apps”)
Web apps and web sites
•
•
are both accessed through a Web browser retrieving content from a
Web server.
But the Web app requires an application server in addition to the Web
server.
4
Web apps…

Is a small part of the J2EE specification
•
•

In 1999 the APIs and tools supporting server-side Java for
the Web, became part of the enterprise edition.
J2EE formalized the definition of a Web app.
J2EE is quite big
•
•
Includes frameworks for handling enterprise needs for
•
•
•
•
•
Secure distributed access
Scalability/performance
Robustness
Data persistance with transactional integrity
Management of distributed resources.
Introduced in Chapter 14.
5
Network programming vs Web app

Pure Java distributed applications
•
•
•

can be realized through socket programming or
Remote Method Invocation (RMI)
Accesses native features of the hardware and
software platform.
Relative hard work, since the application must handle
communications layer, security and related issues.
Wep apps
•
Has a great advantage over “network programming”
•
Works on a higher level.
• Reuse of standard web technologies.
6
A simple schema of a webb app system


Application server
HTTP
HTTPS
Static
Web
content
Plug-in

Relationships between web
browsers, web servers and
application servers.
Web
The web and application
browser
server may or may not
reside on the same
machine.
Web application code may
use any resource available
to the JVM.
(A more detailed design
proposal comes later)
Web server

JVM
Web
application
code
Static
Web
content
7
Application servers




Internet Information Server (Microsoft)
Netscape Enterprise Server
WebSphere Application Server (IBM)
Apache Tomcat
• HTTP-server
• plus app-server: JSP and Java Servlets.
• Not J2EE compliant, since J2EE servers must
handle Enterprise Java Beans (EJB)
8
Client side vs Server side




JavaScript, Applets, HTML
•
•
Typically constitute the view layer of a Web app.
Client side
JSP
•
•
Typically in the View layer
Server side
Servlets
•
•
Typically is the control layer
Server side
Supporting classes
•
•
Typically is in the control or model layer
Server side
9
A few words on the HTTP protocol



On top of TCP/IP
Stateless request/response protocol
A request or response always contains
•
•


Headers
•
•
Info about the client
Instructions to the client or meta info about the body content
Body
Continuity in a conversation?
The most common client request:
•
•
GET me this RESOURCE
A HTTP response may contain a HTML document in its
body.
10
A few words on the HTTPS protocol




Adds security
With the help of Secure Sockets Layer (SSL) that sits
between TCP/IP and the HTTP layer
Assures confidentiality in the point-to-point
communication.
May also handle Authentication via certificates.
11
HTTP request



Has a method
•
•
•
•
GET (request a resource)
POST (Transmit information, e.g. from a HTML form)
PUT (Store a resource on the server)
And a few other not so common methods
Has headers
•
Optional number of them
Has body
12
URI, URL, URN ???

Uniform Resource Identifier (URI)
•
•
•

http://my.domain.com:9080/my/site/myPage.html
Uniform Resource Locator (URL)
•
•

Generic term.
Helps us “distinguish what is being identified from all other
things within its scope of identification”
Refers to the subset of URIs that, in addition to identifying a
resource, provide a means of locating the resource by
describing its primary access mechanism.
http://my.domain.com:9080/my/site/myPage.html
Uniform Resource Name (URN)
•
•
Location of the resource within the local host or domain.
/my/site/myPage.html
13
HTML and XHMTL


HTML
•
•
may not be well formed
Tags may not have closing tags
•
May not have proper nesting of tags
•
Is not case sensitive
•
Tag attributes may not be enclosed in double quotes
• <p>
• <b><i>oopsidaisy</b></i>
• <B>itworx</b>
XHTML always is, has, has, is, and is!
•
Any well-formed XHTML document is a well-formed
XML document.
14
Web app packaging



J2SE apps are packaged into JAR files
Web apps are packaged into WAR files
Enterprise apps are packaged into EAR
files
15
WAR files








Include all Web resources: HTML, XHTML, JSP files
Image files into a “images” folder (by convention)
Executable java code into WEB-INF/classes
Put any JAR files into folder lib.
Add a file web.xml into folder WEB-INF. This
“deployment descriptor” is important.
May contain an ordinary MANIFEST.MF file in folder
META-INF.
May contain additional application server-specific files.
If including java source: put them in “WEB-INF/source”
16
Servlets



The role is to accept requests from the
client and invoke application logic to
fulfill the request
Act as controllers in a MVC oriented
Web app.
Is an entry point into a Web app.
17
How a web app processes requests



1. HTTP request
2. Activation of Servlets that
are loaded into a Web
container (JVM). Servlets
may validate user input.
3. invocation of supporting
classes in the model layer.
4. A HTML page is
assembled and sent back to
client.
Application server
Servlets
Other classes
1
2
3
2
Web
browser
4
Web server

2
3
18
The Servlet API




Javax.servlet.http.HttpServlet
•
Most common methods
•
•
•
Init(): may be overrided, but is often not.
service(): May be overrided, but is often not
doXxx(): Is often overrided
•
doGet(), doPost(), doPut().
Either service() or doXxx() must be overrided.
You should get familiar with the javax.servlet.http
package
•
•
•

Base class to be extended
HttpServlet class
HttpServletRequest
HttpServletResponse
Read chapter 13.
19
My first servlet
package examples.servlets;
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class TodayServlet extends HttpServlet {
public void doGet( HttpServletRequest request,
HttpServletResponse response )
throws IOException, ServletException {
response.setContentType("text/HTML");
response.setHeader("Pragma", "no cache");
response.setHeader("Expires", "-1");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<head>");
out.println("<title>Today</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>The current date and Time is:</h1>");
Date today = new Date();
out.println("<p>" + today + "</p>");
out.println("</body>");
out.println("</HTML>");
out.flush();
}
}
20
Another example
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session = req.getSession(false);
if ( session != null ) {
session.invalidate();
}
ClubMember skier = null;
try {
skier = getMemberData(req);
confirmLogin( req, resp, skier );
} catch( BadDataException e ) {
req.setAttribute( "message", e.getMessage() );
RequestDispatcher rd =
getServletContext().getRequestDispatcher("/badinput.jsp”);
rd.forward( req, resp );
} catch( Exception e ) {
getServletContext().
setAttribute( "exception", e );
RequestDispatcher rd =
getServletContext().getRequestDispatcher("/errorReport.jsp");
rd.forward( req, resp );
}
return;
}
21
Easy to


Use session objects
Forward to a JSP page (View) for output
back to client
• see previous slide

The request object
• Contains data from the “form”
• You may add more data to it before
forwarding to a JSP page.
22
How to store data on the server side



HttpSession object
•
•
Duration: client session.
Automatically handled through cookies.
HttpServletRequest object
•
Duration: Request-response cycle
The Servlet object
•
Is available to all servlets. Should not be client or request
specific.
• getServletContext.setAttribute()
• Don’t use the Servlet fields. Not thread safe. Many threads
(requests) may invoke methods in the same servlet object.
23
Remember

You should design all conversations so
that each request-response could be the
last exchange in the conversation
24
Java Server Pages


Everything you can do with a servlet, you
can do with a JSP page.
Why both?
• Clumsy
• Team of people with different skills
• Cleaner design (MVC).
25
MVC design with JSP


JSP presents info and
results (View layer)
Servlet gets user input Web
and invokes application browser
logic in the control
and/or model layer
Servlets
Servlet forwards results
Other classes
to a JSP page the
creates a view and
sends it as a response
back to the client
Application server
Web container
1
5
Web server

2
3
4
5
JSP
26
JSP example code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<TITLE>BadInputMessage.jsp</TITLE>
</HEAD>
<BODY>
<CENTER>
<IMG SRC="images/SkiClub.gif"
ALT="Near Hills Ski Club " >
</CENTER>
<h2>Unable to complete operation</h2>
<p>There is a problem with the informaton you entered:</p>
<TABLE Border=1 BGCOLOR=#0000FF>
<TR><TD><FONT COLOR=#FFFFFF><em>
<%= request.getAttribute( "message" ) %></em></TD></TR>
</TABLE>
<p>Use the <strong>BACK</strong> button to try again. </p>
</BODY
</HTML>
27
JSP tags

<%= … %>
• Expression inserts the value of the Java
expression

<% … %>

See figure 13-13 and the web.
• Execute embedded java code.
28
Example of flow of a HTTP
request and response

Servlet recieves HTTP request
• If GET, forward to JSP that displays a form
• If POST, retrieve user input and forward to
model layer classes for processing


Servlet forwards results to the JSP
The JSP produces output.
29