Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

Similar documents
Session 9. Introduction to Servlets. Lecture Objectives

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

Session 8. Introduction to Servlets. Semester Project

Servlet Fudamentals. Celsina Bignoli

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

JAVA SERVLET. Server-side Programming INTRODUCTION

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Fast Track to Java EE 5 with Servlets, JSP & JDBC

JSP. Common patterns

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Contents at a Glance

Advanced Internet Technology Lab # 4 Servlets

Questions and Answers

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

Developing Applications with Java EE 6 on WebLogic Server 12c

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

Web based Applications, Tomcat and Servlets - Lab 3 -

Vision of J2EE. Why J2EE? Need for. J2EE Suite. J2EE Based Distributed Application Architecture Overview. Umair Javed 1

Servlet Basics. Agenda

UNIT-V. Web Servers: Tomcat Server Installation:

Stateless -Session Bean

Java- EE Web Application Development with Enterprise JavaBeans and Web Services

Fast Track to Java EE

Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand)

Advanced Web Technology

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

Introduction to JSP and Servlets Training 5-days

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

The Servlet Life Cycle

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

Deccansoft Software Services. J2EE Syllabus

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA

Table of Contents. Introduction... xxi

Problems in Scaling an Application Client

Distributed Multitiered Application

Servlets and JSP (Java Server Pages)

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

ive JAVA EE C u r r i c u l u m

Introduction. Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve

Java EE 7: Back-End Server Application Development

SERVLETS INTERVIEW QUESTIONS

CMP 436/774. Introduction to Java Enterprise Edition. Java Enterprise Edition

Java Servlets. Preparing your System

Introduction to Servlets. After which you will doget it

COMP9321 Web Application Engineering

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

COURSE 9 DESIGN PATTERNS

Enterprise Java Unit 1-Chapter 2 Prof. Sujata Rizal Java EE 6 Architecture, Server and Containers

Appendix A - Glossary(of OO software term s)

Module 3 Web Component

1Z Oracle. Java Enterprise Edition 5 Enterprise Architect Certified Master

CO Java EE 7: Back-End Server Application Development

Component-Based Software Engineering. ECE493-Topic 5 Winter Lecture 26 Java Enterprise (Part D)

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

Java J Course Outline

Java SE7 Fundamentals

J2EE Interview Questions

LearningPatterns, Inc. Courseware Student Guide

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

Servlets. An extension of a web server runs inside a servlet container

Oracle 10g: Build J2EE Applications

Java 2 Platform, Enterprise Edition: Platform and Component Specifications

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java

Hands-on Development of Web Applications with Java EE 6

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Table of Contents Fast Track to Java EE 5 with Servlets/JSP and JDBC

COMP9321 Web Application Engineering

JavaServer Pages (JSP)

Outline. Project Goal. Overview of J2EE. J2EE Architecture. J2EE Container. San H. Aung 26 September, 2003

Enterprise JavaBeans, Version 3 (EJB3) Programming

Java Training Center, Noida - Java Expert Program

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX

Java SE 8 Fundamentals

open source community experience distilled

Java EE 6 - Update Harpreet Singh GlassFish Portfolio Product Manager

Advanced Topics in Operating Systems. Manual for Lab Practices. Enterprise JavaBeans

WHAT IS EJB. Security. life cycle management.

INTRODUCTION TO COMPONENT DESIGN IN JAVA EE COMPONENT VS. OBJECT, JAVA EE JAVA EE DEMO. Tomas Cerny, Software Engineering, FEE, CTU in Prague,

/ / JAVA TRAINING

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

Java EE 5 Development for WebSphere Application Server V7

Courses For Event Java Advanced Summer Training 2018

Module 4: SERVLET and JSP

Oracle Corporation

Ch04 JavaServer Pages (JSP)

Java EE 6 & GlassFish v3 Paving the path for future. Arun Gupta Sun Microsystems, Inc.

DOC // JAVA TOMCAT WEB SERVICES TUTORIAL EBOOK

Oracle Containers for J2EE

(9A05803) WEB SERVICES (ELECTIVE - III)

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

OCP JavaEE 6 EJB Developer Study Notes

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return:

Enterprise Java Unit 1- Chapter 3 Prof. Sujata Rizal Introduction to Servlets

Java EE 7 is ready What to do next? Peter Doschkinow Senior Java Architect

Transcription:

ID2212 Network Programming with Java Lecture 10 Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets Leif Lindbäck, Vladimir Vlassov KTH/ICT/SCS HT 2015

Outline Component Architecture Overview of the Java Platform Enterprise Edition, Java EE Java Servlets Lecture 10: Overview of Java EE; Servlets 2

Component Architecture Component Architecture: Why and How

Component Architecture Consists of components that live in containers. A component is a piece of code, in Java EE usually a class, that solves some of the application's functional requirements. The work done by a component is application specific. A container is a framework that solves some of the application's non-functional requirements. The work done by a container is independent of the application. The same container is used for different applications. Lecture 10: Overview of Java EE; Servlets 4

The Three-Tier Model The three -tier architecture allows maintaining state information, improving security, performance, scalability and availability. Also gives higher cohesion (bettter separation of concern), since business logic and data storage are separated. Client in the first tier - presentation layer Business logic in 2nd tier - security and personalization of the client System services (and databases) in 3rd tier services and storage 1st tier Client GUI 2nd tier Business logic 3rd tier DBMS Data Services 5

Why Component Architecture Not using an existing framework means writing new code which means introducing new bugs. Decrease of the need for in-house expertise Existing frameworks are thoroughly tested and proven to work well. It is easy to get help with frequently used frameworks. Lecture 10: Overview of Java EE; Servlets 6

Why Component Architecture (cont'd) Code handling non-functional requirements is very similar in different applications. Non-functional requirements include scalability, performance, availability, etc. Also, non-functional requirements are difficult to code. Callback style makes sure all calls to non-functional requirements code are made at the right time. Lecture 10: Overview of Java EE; Servlets 7

How Component Architecture Component a program building block for an application; presents a manageable, discrete chunk of logic (functionality); implements a set of well-defined interfaces. Examples: pricing component, billing component Container an application program or a subsystem in which the component lives; Component s context; creates, manages and glues components; provides life cycle management, security, deployment, and runtime services for components it contains (component contract). Examples: Web container (for JSF pages and servlets), EJB container (for EJBs) Lecture 10: Overview of Java EE; Servlets 8

How Component Architecture (cont d) Specifications For components, containers (hosts), and tools (development, deployment) Set of conventions (standards) for Container (Context) Services APIs (classes, interfaces, methods, constructors) Names Semantics A well-defined component architecture is a set of standards (specifications) allowing different vendors to write compatible components, containers and tools Lecture 10: Overview of Java EE; Servlets 9

Development and Deployment Development tools for developing components. The most used Java EE IDEs are: NetBeans (netbeans.org) Eclipse (eclipse.org ) Deployment tools for configuring and deploying components. The GlassFish server has the following tools: Asant (GlassFish command line interface) NetBeans (Integrated with GlassFish) Admin console (GlassFish web interface) Lecture 10: Overview of Java EE; Servlets 10

An Application Server Run time environment for component-based applications Applications are deployed and run on an application server Provides containers and services for applications made of components. Services: security, management, naming, thread pools, persistence, transactions, etc. Some Java EE Application Servers: GlassFish (Oracle, Java EE reference implementation) WebSphere (IBM) WebLogic (Oracle) Jboss (Red Hat) Lecture 10: Overview of Java EE; Servlets 11

Client-Side Components May provide some type of user interface (GUI) Get user input and direct to a server Present (display) a server response to the user Perform client-side (pre- and post-) processing Run in browsers or as standalone applications HTML pages, using HTTP Andriod/iOS apps, using web services Standalone programs (Java or other language), using for example web services. Lecture 10: Overview of Java EE; Servlets 12

Server-Side Components Offer services (server-side operations) Provide dynamic-content web documents, accessing databases, authentication, transactions, etc. Java Servlets, JavaServer Faces (JSF), JavaServer Pages (JSP) Provides HTTP interface Deployed in a Servlet container Enterprise JavaBeans (EJB) Provides transaction management and persistence Deployed in an EJB container Lecture 10: Overview of Java EE; Servlets 13

Component Architectures, Some Existing Approaches Component Architectures from Microsoft.NET, COM, DCOM and COM++ Common Object Request Broker Architecture (CORBA) from the Object Management Group (OMG) Java Enterprise Edition (Java EE) from Oracle PHP-based servers like Apache and NGINX Python-based servers like Zope and Django Lecture 10: Overview of Java EE; Servlets 14

Java Platform, Enterprise Edition (Java EE) http://www.oracle.com/technetwork/ java/javaee/overview/index.html

Some Useful Links Java Platform, Enterprise Edition (Java EE) http://www.oracle.com/technetwork/java/javaee/overview/index.html Java EE Training & Tutorials http://www.oracle.com/technetwork/java/javaee/documentation/ index.html The Java EE 7 Tutorial: http://download.oracle.com/javaee/7/tutorial/ Lecture 10: Overview of Java EE; Servlets 16

Java Platform EE: Enterprise Java Targeted at the development of three-tier architectures: Business Logic components are reusable and portable Application server must follow the Java EE specification and provide specified set of services Presentation layer Business Logic Layer (on Application Server) Component Presentation Logic Database Connection Component Data layer Database Lecture 10: Overview of Java EE; Servlets 17

Multi-Tiered Java EE Applications Java EE Application Java EE Application Application Client Client Dynamic HTML HTML pages pages Client tier Client Machine Enterprise Beans Beans Servlets JSF JSF Enterprise Beans Beans Web tier Business tier Application Server Machine Database(s) Database(s) EIS tier DBMS Machine Lecture 10: Overview of Java EE; Servlets 18

The Java EE Technologies Four groups: Enterprise Application Technologies Web Application Technologies Management and Security Technologies Web Services Technologies Lecture 10: Overview of Java EE; Servlets 19

Enterprise Application Technologies Enterprise JavaBeans (EJB) EJBs are the standard building blocks for business logic. Java EE Connector Architecture An architecture for connecting the J2EE platform to heterogeneous Enterprise Information Systems. Java Message Service API (JMS) A specification of an API for message based communication. To create, send, receive, and read messages. Java Persistence API (JPA) Provides object-relational mapping. Java Transaction API (JTA) An API for resource managers and transactional applications. Also used in writing JDBC drivers, EJB containers and hosts. JavaMail Provides an interface to a mail system. Lecture 10: Overview of Java EE; Servlets 20

Web Application Technologies Java Servlets Process requests and construct responses, usually for HTML pages Provides a gateway between Web clients and EJBs JavaServer Faces (JSF) An API for representing UI components (elements of HTML pages) and managing their state; handling events from components; server-side data validation and conversion. JavaServer Pages Standard Tag Library (JSTL) Encapsulates core functionality common to many JSF applications, e.g. iterator and conditional tags for handling flow control, tags for manipulating XML documents, internationalization tags, tags for accessing databases using SQL, and commonly used functions. Lecture 10: Overview of Java EE; Servlets 21

Web Services Technologies Java API for RESTful Services (JAX-RS) Java API for XML-Based Web Services (JAX-WS) Java Architecture for XML Binding (JAXB) Provides a convenient way to bind an XML schema to a representation in Java code. SOAP with Attachments API for Java (SAAJ) Provides a standard way to send XML documents over the Internet from the Java platform. Lecture 10: Overview of Java EE; Servlets 22

Java EE Containers HTML Clients HTTP HTTPS Web container JavaServer Faces Servlet EJB container EJB Web Service Clients Database Lecture 10: Overview of Java EE; Servlets 23

Java EE Servlet Container APIs Lecture 10: Overview of Java EE; Servlets 24

Java EE EJB Container APIs Lecture 10: Overview of Java EE; Servlets 25

A Java EE Application Server Hosts components in the middle tier of a three-tier architecture. Has containers for server-side components Servlet container for Web components: JSF, Servlets, etc. EJB container for EJBs, etc. Provides services for the components, such as naming, transactions. Connectivity with other tiers (client, databases) Provides access to the components from clients Provides access to the third tier (system services, databases) Lecture 10: Overview of Java EE; Servlets 26

Java Servlets javax.servlet javax.servlet.http home page: http://www.oracle.com/technetwork/java/javaee/overview/index.html

Java Servlets A Java Servlet is a component in a Java EE servlet container that interacts with clients using a Web protocol, such as HTTP. Executes in server's JVM, Allow providing dynamic Web pages, Main usage is as Controller, calls the model component that shall handle the request and forwards request to the next view, Thus acts as gateway between Web clients and other services, such as databases, EJBs, and JMS, Generates HTTP response. Lecture 10: Overview of Java EE; Servlets 29

Java Servlets (cont d) javax.servlet.servlet interface can be used as a generic interface for any service, not just HTTP. Should be a request-response interaction A javax.servlet.http.httpservlet interacts with a client using HTTP protocol. Lecture 10: Overview of Java EE; Servlets 30

How an HTTP Servlet Executes The user submits an HTML form or clicks an HTML link. The browser sends the user s query in a GET (POST) request to a servlet pointed to by URL in the request GET /someresource?inputstring=3 HTTP/1.1 The Web container instantiates the servlet if it does not exist and invokes the service method, passing request and response objects as parameters. The servlet handles the request and writes a result to the output stream of the response object The output stream is directed to the client. Lecture 10: Overview of Java EE; Servlets 31

Executing Servlets Client HTML Page 1. Send HTTP request 4. Return servlet output Server 2. Call servlet 3. Servlet output Servlet Container Servlet Lecture 10: Overview of Java EE; Servlets 32

Include and Forward A servlet can include an output of another servlet: RequestDispatcher dispatcher = getservletcontext().getrequestdispatcher("/banner"); if (dispatcher!= null) dispatcher.include(request, response); A servlet can forward the request (with additional attributes) to another servlet: request.setattribute("message", message); request.setattribute("account",cashier.readaccount(acctno)); request.getrequestdispatcher("/account").forward(request, response); Lecture 10: Overview of Java EE; Servlets 33

The Life Cycle of a Servlet Controlled by the container in which the servlet is deployed. When a request is mapped to a servlet, the container: Loads the servlet class (if not loaded yet). Creates an instance of the servlet class (if it does not exist) and invokes the init method to initialize the servlet instance. Invokes the service method, passing request and response objects. If the container needs to remove the servlet, it calls the servlet's destroy method. Lecture 10: Overview of Java EE; Servlets 34

Implementing the Servlet Interface. Extending the HTTPServlet Class A servlet class implements the Servlet interface either directly, or more commonly, by extending the class HTTPServlet The Servlet interface init(servletconfig config) Initializes the servlet and places it into service. The servlet can get a value of a named init parameter (if any) by name using the ServletConfig object. The init parameters for the servlet are specified in the deployment descriptor (i.e., web.xml file). service(servletrequest req, ServletResponse res) Allows the servlet to respond to a request after the servlet has been initialized by the init method. destroy() Removes the servlet from service after all its threads have exited or a timeout period has passed. Lecture 10: Overview of Java EE; Servlets 35

Extending the HTTPServlet Class Used to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one of the following methods: doget if the servlet supports HTTP GET requests dopost if the servlet supports POST requests doput if the servlet supports PUT requests dodelete if the servlet supports DELETE requests init and destroy to manage resources that are held for the life of the servlet getservletinfo provides information about the servlet Lecture 10: Overview of Java EE; Servlets 36

Servlet s Request and Response A Web container creates and passes to the servlet s service methods (doget, dopost, etc.) two objects: An HTTPServletRequest object, An HTTPServletResponse object. The HTTPServletRequest interface allows to inspect the request: getters (getheader, getquerystring, getparameter, etc.), checkers (isrequestedsessionidvalid, etc.) methods to pass information between the servlet container and a servlet or between interacting servlets The HTTPServletResponse interface provides functionality for creating and sending a response (e.g. output stream). Lecture 10: Overview of Java EE; Servlets 37

package se. kth. id2212.lecture10; import java.io. IOException; import java.io. PrintWriter; import javax. servlet. ServletException; import javax. servlet. annotation.webservlet; import javax. servlet. http. HttpServlet; import javax. servlet. http. HttpServletRequest; import javax. servlet. http. HttpServletResponse; Example: Hello World @ WebServlet(name = " HelloServlet", urlpatterns = {"/HelloServlet"}) public class HelloServlet extends HttpServlet { @Override protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { response.setcontenttype(" text/html; charset=utf- 8"); PrintWriter out = response. getwriter(); try { out. println(" <html>"); out. println(" <head>"); out.println("<title>servlet HelloServlet at " + request.getcontextpath() + "</title>"); out.println("</head>"); out. println(" <body>"); out. println(" <h1>never ever write HTML code in a Servlet!</h1>" ); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } } @Override public String getservletinfo() { return " This is the HelloWorld Servlet example. ID2212 course. KTH" ; } Lecture 10: Overview of Java EE; Servlets 38

Example, Cont d The generated HTML code: <html> <head> <title>servlet HelloServlet at /lecture10 </title> </head> <body> <h1>never ever write HTML code in a Servlet! </h1> </body> </html> Lecture 10: Overview of Java EE; Servlets 39

Monitor and React to Servlet's Life Cycle Events Define listeners to receive and handle life-cycle events issued by the Servlet container (context, session or request events). For example, a context listener: } @WebListener public final class ContextListener implements ServletContextListener { } private ServletContext context = null; public void contextinitialized(servletcontextevent event) { } context = event.getservletcontext(); try { BookDAO bookdb = new BookDAO(); context.setattribute("bookdb", bookdb); } catch (Exception ex) { e.printstacktrace();} public void contextdestroyed(servletcontextevent event) { context = event.getservletcontext(); BookDAO bookdb = (BookDAO)context.getAttribute("bookDB"); bookdb.remove(); context.removeattribute("bookdb"); Lecture 10: Overview of Java EE; Servlets 45

Servlet Life-Cycle Events and Listeners Source Event Listener Interface Web context Session Initialization and destruction Attribute added, removed, or replaced Creation, invalidation, activation, passivation, and timeout Attribute added, removed, or replaced A servlet request has started being processed by web components javax.servlet.servletcontextlistener javax.servlet. ServletContextAttributeListener javax.servlet.http.httpsessionlisten er, javax.servlet.http. HttpSessionActivationListener javax.servlet.http. HttpSessionAttributeListener javax.servlet.servletrequestlistener Attribute added, removed, or replaced javax.servlet. ServletRequestAttributeListener

Filtering Requests and Responses A web resource can be filtered by a chain of filters in a specific order specified on deployment. A filter is an object that can transform the header and content (or both) of a request or response: Query the request and act accordingly; Block the request-and-response pair from passing any further; Modify the request headers and data; Modify the response headers and data. A filter class is defined by implementing the Filter interface. See the javax.servlet package. Lecture 10: Overview of Java EE; Servlets 47

Accessing the Web Context The context in which web components execute, i.e. the servlet container To get the context, call the getservletcontext method on the servlet. The context object implements the ServletContext interface. Lecture 10: Overview of Java EE; Servlets 48

Accessing the Web Context (cont d) The web context provides methods for accessing: Initialization parameters Resources associated with the web context, For example (see Slide 45), retrieving an object attribute (set by the Context listener): public class CatalogServlet extends HttpServlet { private BookDBAO bookdb; puvblic void init() throws ServletException { bookdb = (BookDBAO)getServletContext().getAttribute("bookDB"); if (bookdb == null) throw new UnavailableException("Couldn't get database."); } } Lecture 10: Overview of Java EE; Servlets 49