java web applications. war web archive introduced with servlet 2.2 specification portable deployment...

37
Java Web Applications

Upload: amelia-davidson

Post on 18-Jan-2018

219 views

Category:

Documents


0 download

DESCRIPTION

Directory Structure find./webbasics -print./webbasics./webbasics/WEB-INF./webbasics/WEB-INF/classes./webbasics/WEB-INF/classes/ejava./webbasics/WEB-INF/classes/ejava/servlets./webbasics/WEB-INF/classes/ejava/servlets/webbasics./webbasics/WEB-INF/classes/ejava/servlets/webbasics/BonusServlet.class./webbasics/WEB-INF/classes/ejava/servlets/webbasics/PurchaseServlet.class./webbasics/WEB-INF/web.xml./webbasics/WEB-INF/weblogic.xml./webbasics/FormExample.html./webbasics/MenuExample.html

TRANSCRIPT

Page 1: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Java Web Applications

Page 2: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

WAR

• Web Archive• Introduced with servlet 2.2 specification• Portable deployment mechanism for web

applications• Defines directory structure

– Jar’d into a .war file for deployment• Uses XML deployment descriptor

Page 3: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Directory Structurefind ./webbasics -print./webbasics./webbasics/WEB-INF./webbasics/WEB-INF/classes./webbasics/WEB-INF/classes/ejava./webbasics/WEB-INF/classes/ejava/servlets./webbasics/WEB-INF/classes/ejava/servlets/webbasics./webbasics/WEB-INF/classes/ejava/servlets/webbasics/BonusServlet.class./webbasics/WEB-INF/classes/ejava/servlets/webbasics/PurchaseServlet.class./webbasics/WEB-INF/web.xml./webbasics/WEB-INF/weblogic.xml./webbasics/FormExample.html./webbasics/MenuExample.html

Page 4: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Directory Structure (Cont)

• WEB-INF– Contains web.xml deployment descriptor– Contains class files for web app (classes)– Contains .jar files for web app (lib)– Contains Tag Library Descriptors (tlds)– Cannot be served to client

• Other directories store web content i.e. jsp/html files, images, sound, etc.

Page 5: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Deployment Descriptor (web.xml)<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 1.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"><web-app> <display-name>HTML Basics</display-name> <context-param> <param-name>weblogic.httpd.servlet.reloadCheckSecs</param-name> <param-value>1</param-value> </context-param> <servlet> <servlet-name>PurchaseServlet</servlet-name> <servlet-class>ejava.servlets.webbasics.PurchaseServlet</servlet-class> <init-param> <param-name>param1</param-name> <param-value>value1</param-value> </init-param> </servlet> <servlet> <servlet-name>BonusServlet</servlet-name> <servlet-class>ejava.servlets.webbasics.BonusServlet</servlet-class> </servlet>...

Page 6: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Mapping Servlets to URLs (web.xml)

… <servlet-mapping> <servlet-name>PurchaseServlet</servlet-name> <url-pattern>PurchaseAlias</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>BonusServlet</servlet-name> <url-pattern>BonusAlias</url-pattern> </servlet-mapping>...

Page 7: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Declaring Default Pages (web.xml) … <welcome-file-list> <welcome-file>/welcome.html</welcome-file> </welcome-file-list>...

Page 8: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Creating the .war file%cd c:\\weblogic/myserver/public_html/webbasics; \

%//c/jdk1.3/bin/jar cvf /webbasics.war *added manifestadding: FormExample.html(in = 467) (out= 257)(deflated 44%)adding: MenuExample.html(in = 486) (out= 274)(deflated 43%)adding: WEB-INF/(in = 0) (out= 0)(stored 0%)adding: WEB-INF/classes/(in = 0) (out= 0)(stored 0%)adding: WEB-INF/classes/ejava/(in = 0) (out= 0)(stored 0%)adding: WEB-INF/classes/ejava/servlets/(in = 0) (out= 0)(stored 0%)adding: WEB-INF/classes/ejava/servlets/webbasics/(in = 0) (out= 0)(stored 0%)adding: WEB-INF/classes/ejava/servlets/webbasics/BonusServlet.class(in = 2403) (out= 1260)(deflated 47%)adding: WEB-INF/classes/ejava/servlets/webbasics/PurchaseServlet.class(in = 2585) (out= 1449)(deflated 43%)adding: WEB-INF/web.xml(in = 1843) (out= 587)(deflated 68%)adding: WEB-INF/weblogic.xml(in = 412) (out= 227)(deflated 44%)adding: WEB-INF/web.xml~(in = 1071) (out= 366)(deflated 65%)adding: welcome.html(in = 183) (out= 103)(deflated 43%)

Page 9: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Summary

• The web application format should be used for all web deployments

• Standardized mechanism for web tier deployments

Page 10: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Java Servlets

Page 11: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Servlet Definition

• “Web component, managed by a container, that generates dynamic content”

• Request-Response mechanism modeled after HTTP

• Required by J2EE v1.2 specification• Web Server configured to invoke servlets when

specified URLs are accessed (servlet mapping)– HTML Forms– Java programs

Page 12: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Architecture

WebServer

WebBrowser

Servlet Container

Servlet

Get/Post Request

HTML Page

Request

Reply

Page 13: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Servlet Benefits

• Efficiency– run as threads vs. CGI processes

• Written in Java– can use any Java API such as JDBC, EJB, RMI, etc.

• Portability– supported by many web/application servers

• Simplicity– Provides support for common operations including

session management

Page 14: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Servlet Container

• Provides the execution environment for a servlet• Must support HTTP as the request/response

protocol– HTTP 1.1 support strongly recommended by spec– May support HTTPS (HTTP over SSL)

• Can be installed directly in a web server or as an add-on using web server extension mechanisms

• May impose security constraints on servlet

Page 15: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

My First Servlet

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class HelloWorld extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException

{PrintWriter out = response.getWriter();out.println(“Hello World”);

}}

Page 16: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Notes• Default return mime type is text/plain• Can also implement doPost

– Same arguments– What if you want to answer to both?

• Running the servlet– Compile

• You will need the java 2 enterprise edition jar in your classpath– Put class into WEB-INF/classes– Put in servlet mapping and class info in

WEB-INF/web.xml– Invoke http://host/context/servletmapping

Page 17: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Key Servlet ClassesServlet

void destroy()getServletConfig() : ServletConfiggetServletInfo() : Stringinit(ServletConfig config)service(ServletRequest req, ServletResponse resp)

<<Interface>>

GenericServlet

ServletConfig

getIn itParameter(String name) : StringgetInitParameterNames() : EnumerationgetServletContext() : ServletContext

HttpServlet

doDelete(ServletRequest req, ServletResponse res)doGet(ServletRequest req, ServletResponse res)doOptions(ServletRequest req, ServletResponse res)doPost(ServletRequest req, ServletResponse res)doPut(ServletRequest req, ServletResponse res)doTrace(ServletRequest req, ServletResponse res)

Page 18: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Another Exampleimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class HelloWorld extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException

{response.setContentType(“text/html”);PrintWriter out = response.getWriter();out.println(“<HTML>\n” +

“<HEAD><title>Hello WWW</title></HEAD>\n” + “<body>\n” + “<h1>Hello World!</h1>\n” + “</body></html>”);

}}

Page 19: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Requests and ResponsesServletResponse

getOutputStream() : ServletOutputStreamgetWriter() : PrintWritersetContentLength(int len)setContentType(String type)

ServletRequest

getContentLength() : intgetContentType() : StringgetInputStream() : ServletInputStreamgetParameter(String name) : StringgetReader() : BufferedReader

HttpServletRequest

getAuthType() : StringgetCookies() : Cookie[]getHeader(String name) : StringgetSession() : HttpSession

HttpServletResponse

addCookie(Cookie c)setHeader(String name, String value)setStatus(int sc)

Page 20: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

The HttpServletRequest Object• Form parameters

– String choice=request.getParameter(“Product”);– String getParameter(String key)– String[] getParameterValues(String key)– Enumeration getParameterNames()

• Cookies– Cookie[] = request.getCookies()– getName(), getValue()

• Binary Data– InputStream is = request.getInputStream()

• Character Data– Reader r = request.getReader()

Page 21: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

The HttpServletResponse Object

• void setContentType(String type)• void setContentLength(int len)• PrintWriter getWriter()• ServletOutputStream getOutputStream()

– Used to send binary data back to client• void setHeader(String name, String value)

• Other methods as well

Page 22: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Servlet Implementationpackage ejava.servlets.webbasics;

import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

public class PurchaseServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config); log("BonusServlet:init(config)"); }

Page 23: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Servlet (Cont) public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html><head><title>"); out.println("Purchase Servlet"); out.println("</title></head><body>"); if (request.getParameter("BUYCMD") != null) { String product = request.getParameter("Product");

out.println("<p><b>purchased product:</b>"+product); } out.println("</body></html>"); out.close(); }

Page 24: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Performance Issues

• Strings are immutable– New string object is created for each string– Also for each concatenation of 2 strings a lot of object creation and cleanup

• Use a single StringBuffer object– Use append() method to add text to it

• Use flush method to push output to client

Page 25: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Organizational Issues

• WEB-INF/classes can get crowded• Use java packages to clean things up

– package mypackage; //place at top of file– Put classes in WEB-INF/classes/mypackage– Set up servlet mapping in WEB-INF/web.xml– Invoke http://host/context/servletmapping

Page 26: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Headers and CGI variables

• Request object has methods to access– String value getHeader(String name)– Others

• PrintEnv code– http://localhost:8080/ServletsAndJSP/TestGetP

ostServlet.html

Page 27: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Cookies

• Use the Cookie class• Constructor

– Cookie(String name, String value)• Cookie Methods

– String getDomain() or void setDomain(String dom)– String getName() or void setName(String name)– String getValue() or void setValue(String value) – String getPath() or void setPath(String path)– boolean getSecure() or void setSecure(boolean flag)– int getMaxAge() or void setMaxAge(int seconds)

Page 28: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Cookies

• Create a cookie– Construct it– Set values

• Add the cookie to the response before content type– response.addCookie(Cookie theCookie)

• Get Cookies from request– Cookie[] cookies = request.getCookies()

Page 29: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Sessions

• High level API– HttpSession object

• Built on top of cookies or URL-rewriting– You don’t have to worry which one

• Convenient place to store information– Arbitrary objects– Associated with each session

Page 30: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

The Session API• Get the HttpSession object

– HttpSession session = request.getSession(true);– true automatically creates one if one doesn’t exist

• Get and Set information using HttpSession methods– Object getAttribute(String name)– void setAttribute(String name, Object value)– void removeAttribute(String name)– String[] getAttributeNames()– String getID()– boolean getId()– long getCreationTime() and long getLastAccessedTime()– int getMaxInactiveInterval() and void setMaxInactiveInterval(int sec)– void invalidate()

Page 31: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Example: Toy Shop

• http://localhost:8080/ServletsAndJSP/ToyShop.html

Page 32: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

The Servlet Life Cycle• Initialization

– void init() or – void init(ServletConfig config)

• Be sure to call super.init(config) on first line

• doXxx methods are called (doGet, doPut, etc.)– Consider if you need single thread

• public class YourServlet extends HttpServlet implements SingleThreadModel

• Destruction– void destroy()

• don’t rely on this. The server could crash

Page 33: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Servlet Context

• Servlet may wish to interact with the host server

• GenericServlet::getServletContext()– getMimeType( String file )– getServlet(String name) : Servlet– log(Exception, String)– log(String)

Page 34: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory
Page 35: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Redirection

• Web Browser redirection– resp.sendRedirect(String url)– resp.sendError(int code, String message)

• Server-Side – RequestDispatcher rd =

getServletContext().getRequestDispatcher(urlString);– rd.forward();

Page 36: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Request Dispatcher

Page 37: Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory

Resources

• Main Servlets Page– http://java.sun.com/products/servlet/

• Java Servlet Specification v2.2– http://java.sun.com/products/servlet/2.2/index.html

• Marty Hall’s servlet tutorial– http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/