01 An Introduction To J2ee

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View 01 An Introduction To J2ee as PDF for free.

More details

  • Words: 7,243
  • Pages: 43
An Introduction To j2EE There is a great demand for experienced J2EE professionals now in the market and students and programmers from other languages want to know whether J2EE is Java atall or something else. This tutorial is a conceptual presentation of what & why of J2EE. (It is better for aspiring Java professionals to be forewarned that the Industry expects sound knowledge of EJB, JAX and Struts ..as well as hands on experience in Application servers like WebLogic /WebSphere as a MINIMUM! .It is also important to remember that jdk1.4 is the current version with a lot of new features and jdk1.5 is expected shortly. Moreover, Security in computing is assuming great importance and the candidate should have sound knowledge about java security.) J2EE is not the Java , that comprises of topics like Applets, Console- mode programs, Standalone GUI, Multithreading, Graphics,Exception-handling, String processing, IO Streams, Java Beans in BDK, Swing etc.( topics covered in great detail by books on Core Java , such as 'Java2 -complete reference' by Schildt.,with not a word anywhere on that staple of Computing world of any type (ie) DataBase access!) The title of the book was appropriate some 7 years back! That is why we are puzzled and dismayed that the Java that we studied so 'completely' is so basic and so incomplete!..To be fair, even with the arrival of jdk1.1,some authors like Bill McCarty ('Java ..Distributed Objects') and Jaworsky ('Java2 Unleashed') had a better perspective about the Enterprise potential & orientation of Java and wrote accordingly. However, they are being mentioned only now in curricular circles. after what they wrote so well has sadly become , partly outpaced..This is not to say that Core Java is useless. As the name suggests, it is the core and absolutely essential . But, Java has always been a language for the Web and Enterprise. Without that essential paradigm shift from desktop/LAN to the sprawling WEB & huge enterprise data, it is very difficult to appreciate the modern trends and why there is so much clamour for J2EE (despite the supposed challenge from DotNet). The only topics that could bridge the Core and Enterprise Java are Sockets & Beans. (Among web-professionals, there is a fancy for JavaScript, which is mostly used in Client-side webpages ..It's only use should be 'client-side' validation and no gymnastics. JavaScript is in no way connected with Java . It is unfortunate that this 'script' originally known as 'Live Script' from Netscape , got mixed up with Java . When any one talks about Java Script in the same breath as Java, he is missing Enterprise Java, the true essence of Java language. For aspiring J2EE professionals, ' the less javascript, the better' should be the motto.). We will begin with what Javabean is and also see how beans can be used in Socket programming. Then we will bring out the difference between invoking the method on a bean in a remote server by passing arguments & the Distributed Object paradigm. We will also explain why Distributed Object Technology is not just Client-server or Web-

server technology and why it is superior. Finally, we will see why Distributed Object Technologies like EJB ,CORBA & DCOM were found to be wanting in true interoperability and how the problem is being sought to be tackled by the latest approach (ie) XML WEBSERVICE. This, however, is pretty long journey and this 'short' tutorial cannot cover all the details. The readers are equested to refer to the books mentioned towards the end to get more details. J2EE ( Java 2 -Enterprise Edition) is a basket of 12 inter-related technologies , which can be grouped as follows for convenience.: Group-1 (Web-Server & support Technologies ) ===================================== 1) JDBC ( Java Database Connectivity) 2) Servlets 3) JSP

(Java Server Pages)

4) Java Mail Group-2 ( Distributed-Objects Technologies) ===================================== 5) RMI

(Remote Method Invocation)

6) Corba-IDL ( Corba-using Java with OMG-IDL) 7) RMI-IIOP 8) EJB

(Corba in Java without OMG-IDL) (Enterprise Java Beans)

Group-3 ( Supporting & Advanced Enterprise technologies) ============================================= 9) JNDI

( Java Naming & Directory Interfaces)

10) JMS

( Java Messaging Service)

11) JAVA-XML ( such as JAXP, JAXM, JAXR, JAX-RPC, JAXB, and XML-WEB SERVICE) 12) Connectors ( for ERP and Legacy systems).

J2EE is essentially about Distributed Objects Technology, which is defined as invoking a method on an object residing in a remote machine as if it were local to the invoking program. The Distributed Object may be based on RMI or IDL or RMI-IIOP or EJB. The invoking program can be a standalone mode java program. But , if this were so, it presents two problems. The first problem is that it requires JDK to have been installed in each end-user's machine.This is not a correct assumption because, the only thing that we can be sure of is that the end-user has a browser. Secondly, even with JDK installed in the end-user machine, the java program has to be distributed to each client personally.. This is hardly a practical proposition, if we want our program to be useful to lakhs of end-users out there. Applets, are a possible solution. An applet is a java class file embedded in HTML document, downloaded from the web server and executed in the end-user's browser.( The browser should be java-enabled). With built-in sandbox security, Applets made program distribution very easy and elegant. However, Applets also had two problems. First, standard browsers like InternetExplorer(Microsoft) and NetscapeNavigator (NetscapeCorporation) did not implement JDK fully. This required a java-plug in from Sun.This was clumsy. Secondly, java applets, except in very simple cases, downloaded the classes from the server and though this is a remarkably powerful feature, it also meant that the process was a heavy one and entailed delay in downloading. For these reasons, Applets also ceased to be the recommended method. That is why Sun developed the Servlets technology. Servlets are java class files , execeuted in server and the resulting html sent to the end-user's browser. Now, at one stroke , it solved many problems. 1) We no longer had to instal JDK in end-user's machine. 2) We need not have a java-enabled browser at the user's end. 3) As the result was sent as html only to the browser, it is lightweight & very fast. But, this creates a different problem! A WebServer is just for delivering documents as requested by the user. It need not have any scripting features. Various Webservers have built in facilities for executing CGI and CGI like programs. For instance, Personal WebServer has built in feature for executing ASP which uses VBScript. Apache server provides PERL & PHP. Similarly , JavaWebServer provides Servlet engine and JSP engine. Realising that Apache is the leading WebServer in Internet world, Sun collaborated with Apache Foundation and created the Tomcat engine. We must remember that not any web server can execute a servlet.. So, the correct method of invoking the

function on a remote object in remote server is through a servlet. The modern practice is to have a thin client.(ie) the end user has just a browser like InternetExplorer or Netscape Navigator. He downloads an HTML form and invokes a servlet or JSP through the form. If Distributed Objects are not involved, the servlet/jsp does the processing in web server itself and sends the result to the browser. For Distributed Computing , however, the servlet program in the web-server is the client-side for the Distributed Object computing.It invokes the method of the remote object in the Remote Server. ( it may be RMI/IDL/RMI-IIOP/EJB).The result is sent to the end-user's browser. . All this may be very dense fog right now but will clearup as we progress. With these introductory remarks, let us now take up the technologies one by one. Group1 ======== Servlets & JSP are Web-server technologies.( Distributed Objects Technologies are the more advanced stage...covered in second group) In most of the cases the requirement is that a database is to be accessed either for queries or for modifications . So we use a jdbc program in the webserver and access the database & send the result to the user's browser. Apart from this , it is also very useful to be able to send email through the server. These two opeartions (ie) database operation & mailing are essential applications in webserver. That is why JDBC & JavaMail have found a prominent place in the first group of J2EE technologies. JSP , is a technology which tries to separate the code from the presentation.( However, new developments like JSTL (Java Standard Template Library) & Struts have appeared which insist on much higher degree of separation between code & presentation.JSP-2 is awaited and it aims at total elimination of java code anywhere in the JSP page!..something that ASP.NET has already achieved!). A simple html form('dbdemo.htm') which invokes dbdemo.jsp follows: dbdemo.htm
method=post

type the selectquery here

action=dbdemo.jsp>


name='text1'>


dbdemo.jsp <%@page import="java.sql.*" %> <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String

url = "jdbc:odbc:telephone";

// an access database registered

in odbc Connection

con = DriverManager.getConnection(url);

Statement

stm = con.createStatement();

// container for sql

String

sql = request.getParameter('text1'); // sql

ResultSet

rs = stm.executeQuery ( sql);

while(rs.next()) { out.println(rs.getString(1)+"
");

// name

out.println(rs.getString(2)+"
");

// telephone number

out.println("========"); } %>

------------------------------------------------------------------------------------------------------------------------As for sending mail from webserver, using JavaMail API, the following code shows how the required data such as 'from', 'to', 'subject' and 'message' are collected by the servlet and then processed for sending the mail. ----------------------------------------------------------------------------------------------------------------mailservlet.htm
sender




Reciever




Subject




Message


type=submit>



mailservlet.java

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import javax.mail.*; import javax.mail.internet.*; // important import javax.mail.event.*;

// important

import java.net.*; import java.util.*; public class servletmail extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); response.setContentType("text/html"); try { Properties props=new Properties(); props.put("mail.smtp.host","localhost"); // 'localhost' for testing Session session1 = Session.getDefaultInstance(props,null); String s1 = request.getParameter("text1"); //sender (from) String s2 = request.getParameter("text2");

String s3 = request.getParameter("text3"); String s4 = request.getParameter("area1"); Message message =new MimeMessage(session1); message.setFrom(new InternetAddress(s1)); message.setRecipients (Message.RecipientType.TO,InternetAddress.parse(s2,false)); message.setSubject(s3); message.setText(s4); Transport.send(message); out.println("mail has been sent"); } catch(Exception ex) { System.out.println("ERROR....."+ex); } } }

Using javamail requires that we provide classpath to mail.jar & activation.jar. These should have been already installed in our machine. Otherwise, we will not be able to compile the servlet. For testing the servlet, we should have installed some mail server in our machine. For compiling the servlet, we have to set classpath to c:\jsdk2.0\src (java servlet development kit).

(We are using Tomcat server. The TOMCAT server is a webserver especially created for executing servlets and JSP . It is a joint effort by SunMicroSystems & Apache

Foundation. Tomcat can be run on Apache server or independently. Tomcat will work in Windows platform also. The current version is Tomcat 4. Tomcat 5 is expected shortly).

We can move dbdemo.htm and dbdemo.jsp to : c:\tomcat\webapps\root directory. In another dos window, c:\tomcat\bin>SET TOMCAT_HOME=C:\TOMCAT >SET JAVA_HOME=C:\JDK1.3 >startup ( this will start the tomcat server in port 8080) Start InternetExplorer and type the url as 'http://localhost:8080/dbdemo.htm. We will get the form. Type the sql and submit the form. We will get the resultset sent by the server. We need not compile the jsp file. It is automatically compiled at the server. For running a servlet, copy the servlet's class file to: c:\tomcat\webapps\root\webinf\classes directory. For javamail , we have to copy mail.jar & activation.jar to classes folder. copy the invoking html file to: c:\tomcat\webapps\root

directory.

In the browser type the URL as 'http://localhost:8080/mailservlet.htm'. Enter the required data and submit the form to the server. The mail will be sent as specified by us. That is as brief a tour as possible of the first group of technologies in the J2EE basket. This is an essential foundation because , even when we use RMI/EJB , the correct practice is to invoke the RMI through a servlet. In the JSP example seen above, the code was exposed to the web-administarator. The better method is to encapsulate the code as a bean and invoke it. This way, only the class file will be seen by the server-administaror. The JSP page also will be easier to read and maintain.In the following example , we will adopt that method. To bring out the differences between the different appraoaches, we will consider a simple case where the user types his name in the textbox(text1) in the html form and submits it to the webserver. The JSP then invokes the greeter bean in the webserver . The greeter bean encapsulates the 'Business Logic' ,and so it appends a greeting message to the name thus submitted and sends it back to the user.

What is a Javabean? A Javabean is just a java class with the following requirements. i) It has a public no-args constructor ii) It has 'set' and 'get' methods for its properties. iii) It may have any general functions. iv) If required it must be Serializable. However, It is not necessary always that a bean should have properties. If there are no properties, we need not provide 'set' & 'get' methods either. ( Even the no-args constructor is provided by the compiler by default!) If the bean uses library classes alone, it is automatically serializable. In that case, it becomes just a class for encapsulating some functionality (ie) business logic.

Such a bean , may or may not have a visual representation. As the field has moved away from the desktop, to webserver, there is no point in providing a visual represenation for a component which works in server side as the user cannot interact with it directly. (Such a bean used by jsp in webserver, is exactly similar to ASP component). ( So no worry about jar file ,BDK, BeanBox etc traditionally associated with JavaBean) Let us now create such a bean. The Tomcat server searches for any classes in c:\tomcat\webapps\root\web-inf\classes folder. We create a subfolder under classes folder and name it 'ourbeans'. Therefore, we specify the package information in the first line of our jspbean as : package

ourbeans;

************************* package ourbeans; public class greeterbean

{ public greeterbean() { } public String greetme(String s) { return "How are you?...."+s; } } ***************************************************************** To compile the above file : > javac greeterbean.java We get greeterbean.class We move this class file to: c:\tomcat\webapps\root\web-inf\classes\ourbeans ***************************************************************** We will now create greeter.htm & greeter.jsp and place them in: c:\tomcat\webapps\root greeter.htm
method=post


name='text1'>



action=greeter.jsp>

greeter.jsp <jsp:useBean id="greeter1" class="ourbeans.greeterbean"

/>

<% String s = request.getParameter("text1"); String a = greeter1.greetme(s); out.println(a); %> In the above example, the business logic was invoked through an instance of 'greeter' bean class. So, it is object-oriented approach. Where was the method invoked? It was invoked in the Webserver.Where was the object available? The object was available in webserver itself.(ie) 'locally'. This point is worth noting carefully. For this reason, the jspbean method cannot be classified as 'Distributed Object ' Technology. Because, in Distributed Object Technology, the object on which the method is invoked locally, should be available in a remote server and not locally .( Why is this distinction so important? Is it important atall? If we are able to answer these questions to ourselves convincingly, we have truly grasped the essence of Enterprise computing but not otherwise. That is why this point is being laboured. Let us now consider a case where the object is not available in the webserver but in another remote machine. This is a typical case of MULTI-TIER Client-Server computing. The client here is a servlet program.Let us call it 'socketservlet.java'. This program accepts the data from the form as before but passes the data to the remote server. The bean in the remote server uses this data as parameter for its business logic, creates the result and then sends the result to the servlet. The servlet then forwards the result to the client's browser. We will use the standard Socket method.

It is evident that we are now introducing one more layer.( we have 3 layers now). 1) The user's browser 2) The servlet in web-server 3) The Remote Server housing the bean encapsulating the business logic. In this case, no processing is done at the web-server. The servlet simply accepts the data from the user, forwards it to the remote server where the data is processed by the bean at the remote server and the program sends the result to the servlet , which in turn sends it to the user's browser. import java.io.*; import java.net.*; public class socketgreetserver { public static void main(String args[]) { try { ServerSocket server= new ServerSocket(1234); System.out.println("server ready..listeneing for client in port 1234!"); while(true) { Socket sock = server.accept(); System.out.println("client connected"); DataInputStream ins=new DataInputStream(sock.getInputStream()); String s = ins.readLine(); System.out.println("data received");

greeter greeter1 = new greeter();

// create instance of local bean

String s1 = greeter1.greetme(s); PrintStream ps= new PrintStream(sock.getOutputStream()); ps.println(s1); } }catch(Exception e1)

{System.out.println(""+e1);}

}//main } //======================== Edit the above file in a dos window. >set path=c:\windows\command;c:\jdk1.3\bin >javac socketgreetserver.java >java socketgreetserver Now the remoteserver is running and is waiting for connection request from the client. (ensure that the bean class is available in the same folder). ---------------------------We now see the corresponding servlet. // socketgreetservlet.java import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*;

public class socketgreetservlet extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); //======================================== try { String s1=request.getParameter("text1");// get data from browser Socket client= new Socket("localhost",1234); // for testing System.out.println("server connected!"); PrintStream ps= new PrintStream(client.getOutputStream()); ps.println(s1); // send data to remote server DataInputStream ins=new DataInputStream(client.getInputStream()); String s = ins.readLine();

// get the data sent by the remote server

System.out.println("result obtained from remote server"); out.println(""); out.println(""); out.println(s);

// send it to browser

out.println(""); out.println(""); }catch(Exception e1)

{System.out.println(""+e1);}

}//main } //======================== (Compilation & deployment in Tomcat , as before) Can we call this 'Distributed Object 'Technology? Though , this indeed is a case of Distributed Computing, it does not qualify for being classified as 'Distributed Objects' technology, because the method on the bean was invoked in the Remote Server and the bean also resided in the Remote Server. -------In the example considered , we assume that at both ends we are having JVM and the remote object also is a java object. What if the remote object is not a java object? what if the remote object is wriiten in C++ and the author of that code does not care to provide a java wrapper? Such cases are covered by CORBA which Sun emulated in graded steps through RMI, IDL, RMI-IIOP & finally EJB. -----Another important feature required by most web-applications is Session-Tracking. HTTP is a stateless protocol. (ie) In a multiform application, the data sent through the first form will not be remembered and cannot be used in a subsequent form. , unless we make some arrangement. The usual illustration of this problem is the 'Shopping Cart'. The following methods have been proposed. a) Hidden FormFields b) URL-rewriting

c) Cookies d) Session object e) Application Object But , due to various reasons, it is the 'Session ' object method , that is found to be the best solution. Basically, Session-tracking means that any data pertaining to a browser session is retained for about 20 minutes by default, unless the user closes the session earlier. The data is retained in the webserver's memory and not in the server's hard disk.( This point is important because, EJB entity bean is stored in Enterprise-server's hard-disk., as we shall see shortly). JSP makes it very easy to do session-tracking if we use a bean. We simply declare the scope of the jspbean as 'Session' and we get sessiontracking. The following example shows a typical ' shoppingcart' bean. We will call it cart.java (' Shopping Cart' is a generic term used for describing session-tracking apps.) package ourbeans;

// THIS IS A JAVA BEAN.

import java.util.*; public class cart { Vector vector1; public cart() { vector1= new Vector(); } public void add(String s) { vector1.addElement(s); } public Vector showitems() {

return vector1; } }

carter.htm
method=post action=carter.jsp >

WHICH PLACES DO YOU WANT TO VISIT?
<select name=combo1>

Related Documents