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

Slides:



Advertisements
Similar presentations
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Advertisements

J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
Introduction to Servlet & JSP
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Michael Brockway Application Integration Servlets l Introduction & Overview l HTTP Servlets l HTTP get Requests l HTTP post Requests l Multi-tier Applications.
Java Servlets and JSP.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.
Java Servlet Technology. Introduction Servlets are Java programs that run on a Web server, handle HTTP requests and build Web pages Servlet specification.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
AN OVERVIEW OF SERVLET TECHNOLOGY SERVER SETUP AND CONFIGURATION WEB APPLICATION STRUCTURE BASIC SERVLET EXAMPLE Java Servlets - Compiled By Nitin Pai.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Servlet Lifecycle Lec 28. Servlet Life Cycle  Initialize  Service  Destroy Time.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Java Servlets & Java Server Pages Lecture July 2013.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Chapter 2 Web app architecture. High-level web app architecture  When a client request coming in and needs servlet to serve dynamic web content, what.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
A seminar on j2ee by saritha. s. What is J2EE J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing.
@2008 Huynh Ngoc Tin Chapter #2 JAVA SERVLET PRGRAMMING.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
Java Servlets and Java Server Pages Norman White Stern School of Business.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
Servlets.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
ORIGINAL BY WENDY LIU CURRENT API: Java Servlet and JSP 1.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
J2EE T ECHNOLOGIES These are the technologies required to build large scale distributed applications, can be divided into – Component Technologies eg.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Java Servlets and Java Server Pages
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
1 Lecture 8 George Koutsogiannakis/Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
1 Web Programming with Servlets & JSPs WEB APPLICATIONS – AN OVERVIEW.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
Java Servlets References: Karen Anewalt, Mary Washington College.
CS3220 Web and Internet Programming Introduction to Java Servlets
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Pre-assessment Questions
Chapter 26 Servlets.
Servlets and Java Server Pages
Servlets and JSP 20-Nov-18 servletsJSP.ppt.
Servlets CEN /28/2018 Copyright 2001 Ege Consulting, Inc.
Cookies Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the.
CS3220 Web and Internet Programming Introduction to Java Servlets
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Introduction to Java Servlets
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Web Applications

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

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

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.

Deployment Descriptor (web.xml) HTML Basics weblogic.httpd.servlet.reloadCheckSecs 1 PurchaseServlet ejava.servlets.webbasics.PurchaseServlet param1 value1 BonusServlet ejava.servlets.webbasics.BonusServlet...

Mapping Servlets to URLs (web.xml) … PurchaseServlet PurchaseAlias BonusServlet BonusAlias...

Declaring Default Pages (web.xml) … /welcome.html...

Creating the.war file %cd c:\\weblogic/myserver/public_html/webbasics; \ %//c/jdk1.3/bin/jar cvf /webbasics.war * added manifest adding: 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%)

Summary The web application format should be used for all web deployments Standardized mechanism for web tier deployments

Java Servlets

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

Architecture Web Server Web Browser Servlet Container Servlet Get/Post Request HTML Page Request Reply

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

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

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”); }

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 

Key Servlet Classes

Another Example 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 { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); out.println(“ \n” + “ Hello WWW \n” + “ \n” + “ Hello World! \n” + “ ”); }

Requests and Responses

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()

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

Servlet Implementation package 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)"); }

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(" "); out.println("Purchase Servlet"); out.println(" "); if (request.getParameter("BUYCMD") != null) { String product = request.getParameter("Product"); out.println(" purchased product: "+product); } out.println(" "); out.close(); }

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

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

Headers and CGI variables Request object has methods to access –String value getHeader(String name) –Others PrintEnv code – ostServlet.htmlhttp://localhost:8080/ServletsAndJSP/TestGetP ostServlet.html

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)

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()

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

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()

Example: Toy Shop hop.htmlhttp://localhost:8080/ServletsAndJSP/ToyS hop.html

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

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)

Redirection Web Browser redirection –resp.sendRedirect(String url) –resp.sendError(int code, String message) Server-Side –RequestDispatcher rd = getServletContext().getRequestDispatcher(urlString); –rd.forward();

Request Dispatcher

Resources Main Servlets Page – Java Servlet Specification v2.2 – Marty Hall’s servlet tutorial –