Introduction to J2EE Web Technologies



Similar documents
Web Container Components Servlet JSP Tag Libraries

ACM Crossroads Student Magazine The ACM's First Electronic Publication

Controlling Web Application Behavior

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

Building Web Applications, Servlets, JSP and JDBC

Pure server-side Web Applications with Java, JSP. Application Servers: the Essential Tool of Server-Side Programming. Install and Check Tomcat

Servlet 3.0. Alexis Moussine-Pouchkine. mercredi 13 avril 2011

DTS Web Developers Guide

Java Servlet 3.0. Rajiv Mordani Spec Lead

Web Application Programmer's Guide

Class Focus: Web Applications that provide Dynamic Content

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

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

Ch-03 Web Applications

Glassfish, JAVA EE, Servlets, JSP, EJB

JSP Java Server Pages

Complete Java Web Development

Exam Prep. Sun Certified Web Component Developer (SCWCD) for J2EE Platform

Outline. CS 112 Introduction to Programming. Recap: HTML/CSS/Javascript. Admin. Outline

Principles and Techniques of DBMS 5 Servlet

Creating Java EE Applications and Servlets with IntelliJ IDEA

Arjun V. Bala Page 20

Agenda. Summary of Previous Session. Application Servers G Session 3 - Main Theme Page-Based Application Servers (Part II)

Java Web Programming. Student Workbook

Java and Web. WebWork

CONTROLLING WEB APPLICATION BEHAVIOR WITH

SSC - Web applications and development Introduction and Java Servlet (II)

J2EE Web Development. Agenda. Application servers. What is J2EE? Main component types Application Scenarios J2EE APIs and Services.

Java 2 Web Developer Certification Study Guide Natalie Levi

Web Application Architecture (based J2EE 1.4 Tutorial)

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Course Name: Course in JSP Course Code: P5

Hello World Portlet Rendered with JSP for WebSphere Portal Version 4.1

In this chapter, we lay the foundation for all our further discussions. We start

Oracle WebLogic Server

INSIDE SERVLETS. Server-Side Programming for the Java Platform. An Imprint of Addison Wesley Longman, Inc.

CHAPTER 9: SERVLET AND JSP FILTERS

Developing Web Applications using JavaServer Pages and Servlets

Piotr Nowicki's Homepage. Java EE 6 SCWCD Mock Exam. "Simplicity is the ultimate sophistication." Important!

Outline. Lecture 9: Java Servlet and JSP. Servlet API. HTTP Servlet Basics

JSP. Common patterns

SSC - Web development Model-View-Controller for Java web application development

Java Servlet Tutorial. Java Servlet Tutorial

Getting Started with Web Applications

CIS 455/555: Internet and Web Systems

Java Server Pages combined with servlets in action. Generals. Java Servlets

Managing Data on the World Wide-Web

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, Java Servlets

How to program Java Card3.0 platforms?

Web Applications. For live Java training, please see training courses at

Please send your comments to:

An introduction to web programming with Java

INTRODUCTION TO WEB TECHNOLOGY

2.8. Session management

Server-Side Web Development JSP. Today. Web Servers. Static HTML Directives. Actions Comments Tag Libraries Implicit Objects. Apache.

Web Programming with Java Servlets

Services. Custom Tag Libraries. Today. Web Development. Role-Based. Development. Code Reuse. Tag Libraries Custom Tags. Tag Lifecycle.

Servlet and JSP Filters

A Guide to Understanding Web Application Development Corey Benson, SAS Institute, Inc., Cary, NC Robert Girardin, SAS Institute, Inc.

PowerTier Web Development Tools 4

CS506 Web Design and Development Solved Online Quiz No. 01

11.1 Web Server Operation

Java Servlet Specification Version 2.3

In this chapter the concept of Servlets, not the entire Servlet specification, is

BAPI. Business Application Programming Interface. Compiled by Y R Nagesh 1

Core Java+ J2EE+Struts+Hibernate+Spring

Web Development in Java Live Demonstrations (Live demonstrations done using Eclipse for Java EE 4.3 and WildFly 8)

Developing a J2EE Application. Web Auction. Gerald Mo

Java Enterprise Edition The Web Tier

Università degli Studi di Napoli Federico II. Corsi di Laurea Specialistica in Ingegneria Informatica ed Ingegneria delle Telecomunicazioni

Web Programming II JSP (Java Server Pages) ASP request processing. The Problem. The Problem. Enterprise Application Development using J2EE

Model-View-Controller. and. Struts 2

Client-Server Architecture & J2EE Platform Technologies Overview Ahmed K. Ezzat

Web Application Developer s Guide

Web Applications and Struts 2

The Server.xml File. Containers APPENDIX A. The Server Container

2. Follow the installation directions and install the server on ccc

Oracle Fusion Middleware

CHAPTER 5. Java Servlets

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

What Is the Java TM 2 Platform, Enterprise Edition?

Building Web Applications with Servlets and JavaServer Pages

Oracle WebLogic Foundation of Oracle Fusion Middleware. Lawrence Manickam Toyork Systems Inc

Supplement IV.E: Tutorial for Tomcat. For Introduction to Java Programming By Y. Daniel Liang

Mastering Tomcat Development

AN OVERVIEW OF SERVLET AND JSP TECHNOLOGY

Developing XML Solutions with JavaServer Pages Technology

Web Frameworks and WebWork

Volume 1: Core Technologies Marty Hall Larry Brown. An Overview of Servlet & JSP Technology

Web Applications. Originals of Slides and Source Code for Examples:

Servers, Dynamic Web Projects, and Servlets

White Paper March 1, Integrating AR System with Single Sign-On (SSO) authentication systems

Transcription:

Introduction to J2EE Web Technologies Kyle Brown Senior Technical Staff Member IBM WebSphere Services RTP, NC brownkyl@us.ibm.com Overview What is J2EE? What are Servlets? What are JSP's? How do you use them? 1-2

What is J2EE? Java 2 Enterprise Edition (J2EE) Set of standard API's for Server-side Java Programming Comprehensive support for Web Programming Transactions Distributed Objects A direct competitor to Microsoft's.NET Containers and Components Containers provide the environment in which components execute Containers provide the implementation of the J2EE API's All containers look the same to components Give vendors the freedom to innovate internally and to differentiate themselves by providing different tools, quality of service, etc. Provide control by providing the calling framework Containers handle Concurrency, Consistency, Security, Availability, Scalability, Administration, Integration, Distribution, Data Access Components handle Presentation, Business Logic, Data Access Servlet (component) Web Container Resource Managers (Database Driver) Standard Services (Logging, etc.) 3-4

J2EE Application Components Four types Application Clients Applets Servlets and JavaServer Pages Enterprise JavaBeans Three categories deployed, managed and executed on a J2EE server (EJB, JSP and Servlet) deployed and managed on a J2EE server but loaded and executed on a client machine (applets) not covered by J2EE spec (Application Clients) J2EE Architecture 5-6

Java and the Web Java Servlets are server-side Java classes that respond (typically) to client HTTP requests similar to a CGI program but faster Java Server Pages are a way for embedding Java code into server-side HTML pages A template language for Java Beans and server-side HTML processing Java Servlets A Java class that represents a single URL to the client Defines a service() method that handles HTTP requests HttpServletRequest -- access request data HttpServletResponse -- reply to the client An instance of each class is a shared resource used by multiple threads Each thread handles an HTTP request 7-8

Generic Servlet Invocation Client makes a request of a Servlet through an URL (Optional) Web Server forwards request to Web container Web Container locates an instance of a Servlet class Servlet engine calls Servlet's service method Browser (client) URL request or URL request Web Server Servlet Instance Web Container The Java Servlet API The Servlet API includes two packages: javax.servlet javax.servlet.http javax.servlet.servlet implements javax.servlet.genericservlet A extends javax.servlet.http.httpservlet A 9-10

Servlet Represents a service Usually requested via URL Servlets are loaded by a Web Container At initialization of Server (if preload) At first client request Upon servlet reload Servlet Lifecycle The init() method is called at load time One time behavior The service() method is invoked for each client request The destroy() method is called when it is unloaded init() service() destroy() 11-12

HttpServlet An HTTP-specific request handler Adds two HTTP specific methods: doget () -- handle a GET request (URL) dopost() -- handle a POST request (HTML form) Subclasses override these two messages and may override init() and destroy() doget() and dopost() do the work and are called by service() Requests and Responses The service(), doget() and dopost() methods each have two parameters: HttpServletRequest -- provides access to request data (parameters), HttpSession information, etc. HttpServletResponse -- provides services to allow the servlet to supply a reply to the requesting client Most servlet programming amounts to reading a request and writing a response 13-14

HttpServletResponse Represents communication channel back to client Allows servlet to return content and/or errors Set content header (type, length,...) Redirect server to return a particular URL Response Protocol getwriter() Returns a PrintWriter for output setcontenttype(string type) Set the content type for this response Type is a MIME type sendredirect(string anurl) Redirect the browser to a new URL 15-16

Simple Servlet public class MyServlet extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { // get stream to output HTML on! res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); // send out a simple banner out.println("<html><body>"); out.println("<h1>hello World!</h1>"); out.println("</body></html>"); } } HttpServletRequest Represents client's request "Getters" for aspects of request, e.g., Request header, content type, length, method... Request URL as a String Servlet "path" Client security type Access request parameters (by name) Scope for data sharing among participant objects in the request 17-18

Request Protocol getparameternames() Returns an Enumeration of parameters on the HTML page getparametervalues(string name) Returns the value of a multi-valued parameter getparameter (String name) Returns the value of a specific named parameter getreader() Returns a BufferedReader to view input Example HTML Form <P>Please fill out this form with your name. Thanks! <FORM METHOD="POST" ACTION="/servlet/NameServlet"> <P>Please enter your name: <P>First name: <INPUT NAME="first" TYPE="TEXT" SIZE="12" MAXLENGTH="20"> Surname: <INPUT NAME="surname" TYPE="TEXT" SIZE="15" MAXLENGTH="25"> <P>Thank you! <INPUT TYPE="SUBMIT"> <INPUT TYPE="RESET"> </FORM> 19-20

Reading a Post public void dopost(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { Enumeration enum = req.getparameternames(); while (enum.hasmoreelements()) { String name = (String) enum.nextelement(); String value = req.getparameter(name); // do something with each pair... } } JavaServer Pages JavaServer Pages (JSP) is a standard HTML "template" language Embed standard JSP tags into an HTML page Embed Java code (scriptlets) JSPs are converted to servlets at runtime Page compilation triggered by changes in the JSP, or on first invocation JSP Source is parsed Java servlet code is generated This "JSP Servlet" is compiled, loaded and run 2. compile 1. first request 4. all succceeding requests 3. invoke Web Container JSP (text) JSP servlet (compiled) 21-22

JSP Servlet Structure JSP file contents loaded into a buffer Subclass of HttpServlet created with overridden service method Service method is interleaving of: HTML copied to Response OutputStream Execution of Java equivalent of JSP notation <HTML> <%= new java.util.date() %> </HTML> compiled into outstream.writebytes(buf, 0, frontlen); outstream.print(new java.util.date()); outstream.writebytes(buf, cntindx, rest); JSP 1.1 Specification JSP elements Directives Scripting Actions Scripting language support 23-24

JSP Directives JSP directives are messages to the JSP engine syntax in the form.. <%@ directive {attribute="value"}* %> 1.1 defines page, include, and taglib <%@ page language="java" %> <%@ include file="companybanner.html"%> <%@ taglib uri="taglibraryuri" prefix="tagprefix" %> The <%@ page %> Directive Defines page-specific attributes Apply to complete translation unit <%@ page page_directive_attr_list %> where page_directive_attr_list := language="scriptinglanguage" extends="classname" import="packagelist" session="true false" buffer="none sizekb" autoflush="true false" isthreadsafe="true false" info="info_text" errorpage="error_url" iserrorpage="true false" contenttype="type Type; charset=charset" 25-26

Scripting Declarations <%! declaration %> jspinit() and jspdestroy() methods may be defined here Scriptlets <% valid_code_fragment %> Java code makes up body of generated "method" Expressions <%= expression %> Semantics: The expression is evaluated Result is converted to a String and displayed JSP Scriptlet Within both Scriptlets and Expressions there are certain "implicit objects" available for use (without being declared first) Implicit objects request -- HttpServletRequest object response -- HttpServletResponse object session -- the current HttpSession out -- the JspWriter which writes into the output stream pagecontext, application (ServletContext), config (ServletConfig), page exception -- Instance of Throwable (available to Error Pages) 27-28

JavaServer Pages and JavaBeans Servlet and "back-end" supply dynamic content in a JavaBean JSP accesses object via <jsp:usebean> tag <jsp:usebean> tag specifies how to find or create a Bean A Bean can be: instantiated from serialized file or class file retrieved from HttpSession, ServletRequest context or Application context JSP Sample <HTML><HEAD>...</HEAD> <jsp:usebean id="usr" scope = "request" type="com.ibm.demo.userinfo"/> <BODY> If this were a real application, you would confirm your information below and finalize your transaction. <p> <jsp:getproperty name="usr" property="firstname" /> <br> <jsp:getproperty name="usr" property="lastname" /> <br> <jsp:getproperty name="usr" property="street" /> <br> <jsp:getproperty name="usr" property="city" />, <jsp:getproperty name="usr" property="state" /> <jsp:getproperty name="usr" property="zip" /> <br> Data valid as of <%= new java.util.date() %> </BODY></HTML> 29-30

Enterprise Java and MVC The MVC Pattern is at the heart of Enterprise Java Model -- Represent the business logic View -- Represent a way of interacting with the model Controller -- Mediate between the two, and manage application flow Cleanly separates presentation (View) code from content (Model) code MVC Program Flow 1 clients make HTTP requests 2 servlet (controller) processes inputs and calls business logic (model) 3 business logic can be anything: beans, EJBs, JDBC, etc. output page processing produces HTML 5 4 servlet calls the output jsp page (view) 31-32

Calling JSPs From Servlets Use a standard "RequestDispatcher" to forward requests to another web object. RequestDispatcher disp; request.setattribute("beanname", thebean); disp = getservletcontext().getrequestdispatcher("/ajsp.jsp"); disp.forward(request, response); MVC Example register.jsp <<link>> index.html <<link>> ListAttendeesServlet void doget() <<post>> ProcessRegistrationServlet void dopost() Collection parseattendee() <<forward>> <<link>> Attendee String name String company String title String streetaddress AttendeeBroker void createattendee(attendee) void updateattendee(attendee) void deleteattendee(attendee) Collection getallattendees() list attendees. jsp 33-34

WebApps A Webapp is a repository for application files. A web application may consist of: Servlets, JSP's, Utility Classes, Static html document,s Applets,etc. Descriptive meta information to tie all of the above together A special subdirectory named WEB-INF contains /WEB-INF/web.xml deployment descriptor /WEB-INF/classes/* directory for Java classes. /WEB-INF/lib/*.jar area for Java ARchive files Packaged using JAR into a.war (Web Archive) file Web.XML file <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app id="webapp"> <display-name>ncsudemoproject</display-name> <servlet> <servlet-name>processregistrationservlet</servlet-name> <display-name></display-name> <servlet-class>com.ibm.ncsu.demo.servlet.processregistrationservlet</servlet-class> </servlet> <servlet> <servlet-name>showattendeelistservlet</servlet-name> <display-name></display-name> <servlet-class>com.ibm.ncsu.demo.servlet.showattendeelistservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>showattendeelistservlet</servlet-name> <url-pattern>showattendeelistservlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>processregistrationservlet</servlet-name> <url-pattern>processregistrationservlet</url-pattern> </servlet-mapping> </web-app> 35-36

Example WAR Structure /web-inf /classes /com/ibm/ncsu/demo/domain/attendee.class /com/ibm/ncsu/demo/domain/attendeebroker.class /com/ibm/ncsu/demo/servlet/processregistrationservlet.class /com/ibm/ncsu/demo/domain/listattendeesservlet.class web.xml /index.html /listattendees.jsp /register.jsp The Session Problem Servlets must be stateless They should not have instance variables Are shared by multiple threads Temporary application state specific to a user must be stored outside the servlet This is called Session State Can be stored in an HttpSession object 37-38

HttpSession Ask for a Session from a HttpRequest anhttprequest.getsession(boolean create) Returns an HttpSession If create is false, use a previously created session HttpSessions store user-specific information void putvalue(string, Object) Object getvalue(string) Session Lookup Application Server Browser id value 12345 asession Cookie List cookie name value "sesessionid" 12345 asession key "Customer" "Name" value acustomer "Bob" 39-40

Scaling HttpSessions While the previous (default) implementation works for one application server, it fails in a clustered environment where requests from a single user could be dispatched to more than one JVM over the course of a user session There are several standard solutions to this Store the HttpSession information in a shared database "Pin" each user to a specific JVM Use a distributed notification mechanism to transfer session information between JVM's Each application server vendor will choose one or more of these solutions for clustered session state maintainance Advanced Topic: Servlet Filters One of the more interesting features added in the Servlet 2.3 specification was the notion of a Servlet Filter Filters are similar to, but not the same as a servlet A Filter modifies a servlet request or response Does not represent a user end-point The Filter interface defines a dofilter() method, which Examines the request headers Customizes the request or response as needed Passes control onto the next filter in the chain or blocks the response Filter Filter Servlet Filter 41-42

Using Filters There are a number of different ways that filters can be used to change output or make general decisions based on input Logging and billing -- a logging or billing filter could be attached to all servlets (regardless of whether or not you have the source code) to log incoming HTTP requests and outgoing responses for audit purposes, or to record the userid and invocation information for later billing XSL -- an XSL Translation filter can take output formatted as XML and apply XSL Stylesheets to the output to translate it into HTML or some other format (like WML) Internationalization -- an Internationalization filter could take abstract message ID's and replace them in the output with the proper national-language output text Content-filtering -- a content-filtering servlet could mask or remove output that a user is not authorized to see Summary We've seen: What Servlets and JSP's How they are used What they are defined in J2EE 43-44