Servlets JSP EJB. Part III. Java Platform, Enterprise Edition (Java EE)

Similar documents
Fast Track to EJB 3.0 and the JPA Using JBoss

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

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

Oracle 10g: Build J2EE Applications

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module

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

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

JavaServer Pages (JSP)

Advanced Java Programming

EJB 3 Entity Relationships

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

Web Application Development Using JEE, Enterprise JavaBeans and JPA

EJB 3 Entity Relationships

Developing Applications with Java EE 6 on WebLogic Server 12c

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Java EE Architecture, Part Three. Java EE architecture, part three 1(69)

IBD Intergiciels et Bases de Données

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

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

Basics of programming 3. Java Enterprise Edition

Course Content for Java J2EE

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

Fast Track to Java EE

Chapter 1 Introducing EJB 1. What is Java EE Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7

Deccansoft Software Services. J2EE Syllabus

Java Enterprise Edition

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

Problems in Scaling an Application Client

Java 2 Platform, Enterprise Edition: Platform and Component Specifications

J2EE - Version: 25. Developing Enterprise Applications with J2EE Enterprise Technologies

ADVANCED JAVA TRAINING IN BANGALORE

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

ADVANCED JAVA COURSE CURRICULUM

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

Table of Contents. Introduction... xxi

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

Enterprise JavaBeans, Version 3 (EJB3) Programming

Lightweight J2EE Framework

COMP9321 Web Application Engineering

Java EE Architecture, Part Three. Java EE architecture, part three 1(57)

Introduction to Java Enterprise Edition For Database Application Developer

index_ qxd 7/18/02 11:48 AM Page 259 Index

Module 8 The Java Persistence API

Servlets and JSP (Java Server Pages)

object/relational persistence What is persistence? 5

A COMPONENT BASED ONLINE ORDERING SYSTEM USING ENTERPRISE JAVABEANS 3.0

A Gentle Introduction to Java Server Pages

Introduction to JSP and Servlets Training 5-days

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation

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

/ / JAVA TRAINING

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

DVS WEB INFOTECH DEVELOPMENT TRAINING RESEARCH CENTER

COURSE DETAILS: CORE AND ADVANCE JAVA Core Java

JAVA. Duration: 2 Months

Stateless -Session Bean

Session 9. Introduction to Servlets. Lecture Objectives

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

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

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP

J2EE Interview Questions

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

SUN Sun Cert Bus Component Developer Java EE Platform 5, Upgrade. Download Full Version :

LTBP INDUSTRIAL TRAINING INSTITUTE

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

Courses For Event Java Advanced Summer Training 2018

Borland Application Server Certification. Study Guide. Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved.

IBM WebSphere Application Server. J2EE Programming Model Best Practices

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, JSPs 1

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

MARATHWADA INSTITUTE OF TECHNOLOGY, AURANGABAD DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS ADVANCE JAVA QUESTION BANK

The Good, the Bad and the Ugly

Contents at a Glance

Module 3 Web Component

1Z Java SE 5 and 6, Certified Associate Exam Summary Syllabus Questions

COMP9321 Web Application Engineering

Session 8. Introduction to Servlets. Semester Project

CE212 Web Application Programming Part 3

Java EE 7: Back-End Server Application Development

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

In the most general sense, a server is a program that provides information

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Chapter 6 Enterprise Java Beans

Java SE7 Fundamentals

Appendix A - Glossary(of OO software term s)

Shale and the Java Persistence Architecture. Craig McClanahan Gary Van Matre. ApacheCon US 2006 Austin, TX

CO Java EE 7: Back-End Server Application Development

JVA-163. Enterprise JavaBeans

EJB 3 Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule

Distributed Multitiered Application

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

Component Based Software Engineering

Exam Actual. Higher Quality. Better Service! QUESTION & ANSWER

CO Java EE 6: Develop Database Applications with JPA

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

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

Building the Enterprise

What data persistence means? We manipulate data (represented as object state) that need to be stored

ITdumpsFree. Get free valid exam dumps and pass your exam test with confidence

NetBeans IDE Field Guide

Transcription:

Part III Java Platform, Enterprise Edition (Java EE) 65

Java Platform, Enterprise Edition (Java EE) Java Servlets and JSP pages in web access layer Enterprise JavaBeans 3.0 for implementing business logic 66

1. Java Servlets executed by Java runtime environment, which is integrated into the web server (e.g. Apache) enable the dynamic generation of HTML pages for each request: new thread in JVM Client Internet Web Server HTML DB API response request JVM Servlet 68

Java Servlets (continued) servlets are (e.g.) collected in a special directory the server is configured, such that an access to a corresponding file causes it to be executed as a servlet request to a servlet via HTTP, e.g.: http://servername/servlets/welcome?name=bob+king parameter passing and result comfortably via request and response objects (as arguments of doget) rather than via environment variables or standard input 69

Example: Java Servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Welcome extends HttpServlet{ public void doget( HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String name = req.getparameter("name"); if ((name==null) (name.length()==0)) name = "Unknown"; res.setcontenttype("text/html"); PrintWriter out =res.getwriter(); out.println("<html> \n <HEAD> \n <TITLE>Hello </TITLE> \n </HEAD>"); out.println("<body> \n <H1>Hello "+name+".</h1>"); out.println("</body> \n </HTML>"); out.close();} } 70

Advantages of Servlets more efficient than conventional CGI scripts (thread rather than process) servlets in main memory across several requests servlet and applet can communicate continuously using an arbitrary protocol servlets can communicate via common objects synchronized by monitors servlets offer comfortable means to maintain a session (based on cookies internally) thus, database connections can be kept open during a session 71

2. JavaServer Pages (JSP) disadvantages of servlets: for web pages mainly consisting of static HTML and little dynamically computed parts, servlets mainly consist of output statements then better: logic (Java) included in HTML page thus: JSP JSP code in internally transformed into a servlet (own) tag libraries allow to separate web design and logic 73

JSP Example 1: Hello <HTML> <HEAD><TITLE>Hello</TITLE> <BODY> <H2>JSP Example</H2> <% if (request.getparameter("name") == null) out.println("hello!"); else out.println("hello " + request.getparameter("name")+"!"); %> <it>welcome! </it> </BODY></HTML> 74

JSP Example 2: Square <HTML> <HEAD><TITLE>Square</TITLE> <BODY> <%@ include file = "/head.html" %> <H2>JSP Example</H2> <%@ page session="false" %> <%@ page errorpage = "/error.jsp" %> <% String firstname = request.getparameter("firstname"); String lastname = request.getparameter("lastname"); int z = Integer.parseInt(request.getParameter("number")); if ((firstname == null) (lastname == null)) throw new Exception("Please enter your name!"); else out.println("hello "+firstname+" "+lastname+"!"); %> The square of <%= z %> is <font color=red><%= square(z) %></font>. <%@ include file = "/foot.html" %> </BODY></HTML> <%! private int square(int x){return x*x;} %> 75

Predefined Variables available in the Java code contained in a JSP page HttpServletRequest request HttpServletResponse response javax.servlet.jsp.jspwriter out HttpSession session ServletContext application javax.servlet.jsp.pagecontext pagecontext 76

JSP Features <% c %> Java code c will be executed <%= e %> Java expression e is evaluated; the result is inserted as a String <%! d %> Java declaration d is inserted before doget in the generated servlet <%@ d %> directive d will be executed when transforming JSP to a servlet; e.g. switch off cookies, determine error page, insert file <jsp:usebean... > insert JavaBean ( EJB) </jsp:usebean> <jsp:include page ="/my.jsp" > insert file at execution time </jsp:include> <jsp:forward page="login.jsp"> redirect to other page </jsp:foward> 77

Frameworks for User Interfaces of Web Applications Servlet Container Model EJB, JavaBeans,... Request 1. post Controller 2. dispatch ActionServlet Action Business Logic 3. update 4. forward Bean Bean Response 6. response View JSP TagLibs 5. extract FormBean Struts is based on the design pattern model-view-controller (MVC) (e.g.) servlets for controller, EJBs for model, JSP for view especially suited for complex systems alternative: JavaServer Faces 78

3. Enterprise JavaBeans Java-based middleware for distributed OO applications components (beans) are provided in EJB container (on server) EJB containers: e.g. BEA WebLogic, IBM WebSphere, Sun J2EE, JBoss... the container offers frequently needed services for ISs advantage: basic services for free disadvantage: overhead; no OS calls (due to transactions) 80

Services provided by the Container managing and searching beans (name service based on JNDI) transactions (based on JTS and JTA) persistence accessing remote objects (based on RMI/IIOP or JMS) resource management (instance pooling, loading and unloading of of beans) authorization and authentication (based on JAAS) 81

Where are EJBs used? typical 4-Layer-Architecture: client tier (HTML+JavaScript) web tier (JSP,Servlets) business tier (EJB) EIS tier (DB) 82

Kinds of Beans Entity (Bean): encapsulates persistent data accessed via session bean (or other entity) Session Bean: implements business logic (e.g. use case) not persistent accessed from e.g. servlet or Java client (possibly via RMI) variants: stateless and stateful Message-driven Bean: processes asynchronous message see chapter on message-oriented middleware for details 83

Variants of Session Beans Variant 1: stateless efficiently and jointly used by several clients (successively, pool) state (local variables) available during method call no continuous assignment to a client across a session each request during a session is typically processed by a different bean Variant 2: stateful exclusive for one client state is maintained during a session (consisting of several requests) state lost, if system crashes 84

Set-up of Enterprise JavaBeans Remote Interface (or Local Interface, if only locally accessed) for business methods (for session beans only) management operations (until EJB 2.X in Home Interface) now transparent (e.g. generation, deletion, activation, passivation) Bean Class: implements the business methods from EJB 3.0 on: POJO (plain old Java object) optional deployment descriptor: XML document for the configuration of a bean w.r.t. persistence, associations ( relations ), transactions, primary key,... from EJB 3.0 on typically replaced by annotations in bean class all together assembled in.jar-archive (packaging) 85

EJB 3.0 Programming Model EJB Container JVM Remote Client Local Client Middleware Services: Life cycle Management Persistence Access Protection Business Interface Container generated Wrapper Class Transactions... EJB Class 86

Deployment a bean is configured according to its annotations (or its deployment descriptor) and provided in a container auxiliary classes for integrating a bean class are automatically provided alternatively: comfortable, container-managed persistence or more flexible bean-managed persistence (with explicit JDBC calls) alternatively: container- or bean-managed transactions 87

Example Application: Library date Loan 0..1 Copy 1 inventoryno * 1 name Medium * 1 User name address author isbn Book asin CD interpreter 88

package library; Entity Class User import java.util.arraylist; import java.util.collection; import javax.persistence.*; @Entity public class User implements java.io.serializable { protected int uid; /** primary key */ protected String name; protected String address; protected Collection<Loan> loans = new ArrayList<Loan>(); @Id @GeneratedValue(strategy=GenerationType.AUTO) public int getuid(){return uid;} public void setuid(int id){uid = id;} public String getname(){return name;} public void setname(string name){this.name = name;} public String getaddress(){return address;} public void setaddress(string address){this.address = address;} 89

Entity Class User (continued) } @OneToMany(cascade = CascadeType.ALL, mappedby="user") public Collection<Loan> getloans(){return loans;} public void setloans(collection<loan> coll){loans = coll;} public void addloan(loan loan){loans.add(loan);} public void removeloan(loan loan){loans.remove(loan);} 90

... @Entity Entity Class Loan public class Loan implements java.io.serializable { protected int id; protected Date date; protected User user; protected Copy copy; @Id @GeneratedValue(strategy=GenerationType.AUTO) public int getid(){return id;} public void setid(int id){this.id = id;} public Date getdate(){return date;} public void setdate(date d){date = d;} @ManyToOne @JoinColumn(name = "user") public User getuser(){return user;} public void setuser(user u){user = u; u.addloan(this);} @OneToOne @JoinColumn(name = "copy") public Copy getcopy(){return copy;} public void setcopy(copy c){copy = c; c.setloan(this);} } 91

Entity Class Copy... @Entity public class Copy implements java.io.serializable{ protected int inventoryno; protected Medium medium; protected Loan loan; @Id @GeneratedValue(strategy=GenerationType.AUTO) public int getinventoryno(){return inventoryno;} public void setinventoryno(int no){inventoryno = no;} @ManyToOne @JoinColumn(name = "medium") public Medium getmedium(){return medium;} public void setmedium(medium m){medium = m; m.addcopy(this);} } @OneToOne(cascade = CascadeType.ALL, mappedby="copy") public Loan getloan(){return loan;} public void setloan(loan lo){loan = lo;} 92

... @Entity Entity Class Medium @Inheritance(strategy=InheritanceType.SINGLE_TABLE) public abstract class Medium implements java.io.serializable{ protected int id; protected String name; protected Collection<Copy> copies; @Id @GeneratedValue(strategy=GenerationType.AUTO) public int getid(){return id;} public void setid(int id){this.id = id;} public String getname(){return name;} public void setname(string n){name = n;} } @OneToMany(cascade = CascadeType.ALL, mappedby="medium") public Collection<Copy> getcopies(){return copies;} public void setcopies(collection<copy> coll){copies = coll;} public void addcopy(copy c){copies.add(c);} public void removecopy(copy c){copies.remove(c);} 93

Entity Class Book... @Entity public class Book extends Medium implements java.io.serializable{ protected String isbn; protected String author; public String getisbn(){return isbn;} public void setisbn(string no){isbn = no;} } public String getauthor(){return author;} public void setauthor(string a){author = a;} class CD analogously 94

Example: Session Bean: Remote Interface... @Remote public interface UserFacade { public void createuser(string name, String address) throws Exception; } 95

... @PermitAll @Stateless Example: Session Bean Class public class UserManagement implements UserFacade{ @PersistenceContext private EntityManager em; @TransactionAttribute(TransactionAttributeType.REQUIRED) public void createuser(string name, String address) throws Exception{ Query q = em.createquery("select COUNT(*) FROM User u WHERE u.name = :n"); q.setparameter("n",name); if (((Long) q.getsingleresult()).intvalue() == 0){ User user = new User(); user.setname(name); user.setaddress(address); em.persist(user);} else throw new Exception("Name previously used!"); } } 96

Annotations annotations determine the kind of bean: entity (@Entity) or session bean (@Stateless,@Stateful) Annotations for Entities: @Id determines the primary key @Inheritance determines, how a class hierarchy is mapped to a relational database (SINGLE_TABLE, TABLE_PER_CLASS, JOINED) (Details later!) 97

Annotations for Session-Beans annotations for controlling the access to classes and methods: @PermitAll, @DenyAll (only for methods), @RolesAllowed( Role ), @RunAs( Role ) @TransactionManagement(BEAN) replaces the (preset) container-managed transaction handling to a bean-managed one @TransactionAttribute allows to determine, how a method is integrated into a transaction (options: MANDATORY, NOT_SUPPORTED, REQUIRED (default!), REQUIRES_NEW, SUPPORTS) 98

Associations for?:1-relationships, the considered class gets an attribute of the type of the neighborclass (and corresponding getters and setters) for?:n-relationships, the class gets an attribute of type Collection<NeighborClass> (e.g. ArrayList) the multiplicity (@OneToOne, @OneToMany, @ManyToOne, @ManyToMany) is annotated before the getter of the corresponding attribute in case of a bidirectional association, one of both classes is responsible for the consistency for?:n-relationships, the/a N-site shall be responsible for it the responsible site uses friend methods of the other site in order to ensure consistency 99

Parameters of Multiplicity Annotations parameter cascade specifies, whether the neighbor objects shall be updated, (persistently) changed, and/or deleted together with the considered object (@ALL, @MERGE, @REMOVE, @PERSIST, @REFRESH) for @ManyToMany, a table with a database mapping is used the annotation @JoinTable allows to fix details of the mapping table 100

Parameters of Multiplicity Annotations (continued) the parameter fetch specifies, whether the neighbor objects shall be loaded from the DB together with the considered object (default for?:1: EAGER, default for?:n: LAZY) the parameter optional determines, whether null values are allowed the non-responsible site of an association uses parameter mappedby to specify the foreign key of the opposite site 101

Features of Entities container-managed entities are not directly accessible from outside (from other JVM) however, they can be delivered as a result to clients this causes them to be detached, i.e. the container does not manage them any longer special result classes (data transfer objects) are no longer needed from EJB 3.0 on entities have to be serializable for transmission after transmission, entities loose their connection to lazily loaded neighbor objects entities and their attributes mus not be final 102

Life Cycle of an Entity find() Queries refresh() flush() new() new persist() merge() remove() managed persist() clear() close() merge() serialize() commit rollback detached flush() commit removed 103

Transforming Classes to Relations Person No Name OID Person No FirstName LastName mapping of attribute type to create table Person ( OID number(8) not null, No number(8) not null, FirstName char(20), LastName char(20) not null, primary key (No) ); create secondary index PersonIndex on Person(LastName); SQL type; possibly via embedded relation (@Embeddable,@Embedded) (possibly) add OID column fix primary key (@Id) fix optional attributes optional: create 2 nd index 104

Handling Associations for 1 : m-association/composition (m 1): foreign key K1 K2 K1 K2 OID1 A1 A2 OID2 A3 A4 OID1 A1 A2 1 * A3 A4 for n : m-association/composition (n, m > 1): associative table K1 K2 K1 2 K1 A1 A2 * * A3 A4 K2 OID1 A1 A2 OID2 A3 A4 OID1 OID2 105

Transforming Inheritance a) own table per class all tables contain primary key small schemata, but scattered information (overhead for ) 3NF JavaEE annotation @Inheritance(strategy = InheritanceType.JOINED) Person Name Person Client Employee Client Employee OID 27 42 Name Smith Miller OID Sales 27 3212 OID Salary 42 4619 Sales Salary 106

Transforming Inheritance (2) b) completed tables OID 27 Client Name Smith Employee Sales OID Name Salary 3212 42 Miller 4619 for each concrete class, there is an own table with all attributes (including inherited ones) all superclass attributes are moved to the subclass tables overhead due to unions when accessing the superclass reasonable, if few superclass attributes 3NF annotation @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 107

Transforming Inheritance (3) c) one table for whole class hierarchy OID 27 42 Person Name Group Sales Salary Smith Client 3212 NULL Miller Employee NULL 4619 move all subclass attributes to superclass table reasonale, if few subclasses with few attributes null values for missing attribute values violates 3NF JavaEE annotation @Inheritance(strategy = InheritanceType.SINGLE_TABLE) 108