0% found this document useful (0 votes)
461 views

Adv Java Notes For College

Advanced java notes for student. It will help student to learn programming code.

Uploaded by

Santhosh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
461 views

Adv Java Notes For College

Advanced java notes for student. It will help student to learn programming code.

Uploaded by

Santhosh
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 192

SRM ARTS AND SCIENCE COLLEGE

SRM NAGAR, KATTANKULATHUR – 603203


DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-2018)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2017.

Subject Name : Advanced Java Programming Subject Code : CTC7A

Faculty Name : V. S. Padmavathy

Session : 1 / 45

Topic (Lecture Notes Per Hour) 40 Minutes

Servlets

Definition:

A servlet is a server-side components,written in java, that dynamically extends the functionality of a


server. Similar to the manner in with applets run inside a java-enabled web browser on the client,
servlets execute on a java enabled server

Overview of Servlets

Unlike applets, servlets do not display a graphical interface to the user. A servlet’s work is done
“behind the scenes: on the server and only the results of the servlet’s processing are returned to the
client(usually in the form of HTML).

Servlets are java classes that confirm to a specific interfaces that can be invoked from the server.

Servlets provide a framework for creating applications that implements request/response paradigm.
For example, when a browswer sends a request to the server, the server may forward the request to a
servlet. At this point the servlet can process the request and construct an appropriate response to the
client.

Advantages of servlets:

The advantages of servlets are discussed below.

1. Portability
2. Powerful
3. Efficiency
4. Safety
5. Integration
6. Extensibility
7. Inexpensive
8. Secure
9. Performance

1
Portability

Servlets are highly portable crosswise operating systems and server implementations because
the servlets are written in java and follow well known standardized APIs. Servlets are writing
once, run anywhere (WORA) program, because we can develop a servlet on Windows
machine running the toMCA/MSC(CS&CST)t server or any other server and later we can
deploy that servlet simply on any other operating system like Unix. Servlets are extremely
portable so we can run in any platform. So we can call servlets are platform independent one.
Servlets are written entirely in java.

Powerful

We can handle several things with the servlets which were difficult or sometimes impossible
to do with CGI. For example the CGI programs can’t talk directly to the web server but the
servlets can directly talk to the web server.  Servlets can share data among each other, they
make the database connection pools easy to implement. By using the session tracking
mechanism servlets can maintain the session which helps them to maintain information from
request to request. Servlets can do many things which are difficult to implement in the CGI
programs.

Efficiency

The servlets invocation is highly efficient as compared to CGI programs. The servlet remains
in the server’s memory as a single object instance, when the servlet get loaded in the server.
The servlets are highly scalable because multiple concurrent requests are handled by separate
threads. That is we can handle N number of threads by using a single servlet class

Safety

As servlets are written in java, servlets inherit the strong type safety of java language. In java
automatic garbage collection mechanism and a lack of pointers protect the servlets from
memory management problems. In servlets we can easily handle the errors due to the
exception handling mechanism. If any exception occurs then it will throw an exception by
using the throw statement.

Integration

Servlets are tightly integrated with the server. Servlet can use the server to translate the file
paths, perform logging, check authorization, and MIME type mapping etc.

Extensibility

The servlet API is designed in such a way that it can be easily extensible. As it stands today,
the servlet API support Http Servlets, but in later date it can be extended for another type of
servlets. Java Servlets are developed in java which is robust, well-designed and object
oriented language which can be extended or polymorphed into new objects. So the java
servlets take all these advantages and can be extended from existing class to provide the ideal
solutions. So servlets are more extensible and reliable.

Inexpensive

There are number of free web servers available for personal use or for commercial purpose.
Web servers are relatively expensive. So by using the free available web servers you can add
servlet support to it.

2
Secure

Servlets are server side components, so it inherits the security provided by the web server.
Servlets are also benefited with Java Security Manager.

Performance

Servlets are faster than CGI programs because each scripts in CGI produces a new process
and these processes takes a lot of time for execution. But in case of servlets it creates only
new thread. Due to interpreted nature of java, programs written in java are slow. But the java
servlets runs very fast. These are due to the way servlets run on web server. For any program
initialization takes significant amount of time. But in case of servlets initialization takes place
first time it receives a request and remains in memory till times out or server shut downs.
After servlet is loaded, to handle a new request it simply creates a new thread and runs
service method of servlet. In comparison to traditional CGI scripts which creates a new
process to serve the request.

What do you need to write servlets?

1)j2sdk1.4 kit or later

What do you need to run servlets?

1)Any web server(Apache web server,jboss,jrun,resin,glassfish server,etc)

Servlets life cycle


This process can be broken down into nine steps

1. The server loads the servlet when it is first requested by a client or. If configured to do so, at
server startup.
2. The server creates one or more instances of the servlet class. Depending upon on the
implementation, the server may create a single instance that services all requests through
multiple threads or create a pool of instances from which one is chosen to service each new
request.
3. The server constructs a servletconfig object that provides initialization information to the
servlet.
4. The server calls the servlet’s init() method, passing the object constructed in step 3 as a
parameter. The init() method is guaranteed to finish execution prior to the servlet processing
the first request.
5. The server constructs a ServletRequest or HttpServletRequest object from the data included in
the client’s request. It also constructs ServletResponse or HttpServletResponse object that
provides method for customizing the server’s response.
6. The server calls the servlet’s service() method, passing the object constructed in step5 as
parameter.
7. The service() method processes the client request by evaluating the ServletRequest or
HttpServletRequest object and responds using the ServletResponse or HttpServletResponse
object
8. If the server receives another request for this servlet, the process begins at step 5
9. When instructed to unload the servlet, perhaps by the server administrator or
programmatically by the server itself, the server calls the servlet’s destroy object.

3
FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define Servlet.APR 14,15


2. What is the role of servlet in J2EE?APR 14
Section : B

1)Explain about Servlets in detail.

2)Discuss servlet life cycle.

Section : C

1)What are the advantages of Servlets programming?

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD


Note:
Lecture Notes Minimum 2 Pages

4
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-2018)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 2 / 45

ic (Lecture Notes Per Hour) 40 Minutes

The Java Web Server:


The Java server architecture defines services, the server process and the servlet API.

1)The service framework

It defines a set of interfaces for implementing services that interact with clients using
multiple thread handler. A service is defined as an implementation of an individual protocol
such as http or ftp.

The core service classes provided by the javaserver architecture include


administration, thread management,connection management, session management and
security.When a server is initiated, it will acquire a specific server socket. After acquiring a
server socket, the service will create a pool of handler threads.Each thread will idle waiting
for a connection request. Once a connection request has been received, a handler thread will
perform all protocol interactions on that connections.

2)The server framework

A server is one instance of a java virtual machine. One server can support multiple
concurrent services, are configured to start when the server process is initiated.

A server, such as the javaserver, will most likely start and administrative service, an
HttpService ,a web proxy services can be addedmremore or configured while the server is
running.

3)The servlet framework

A servlet is a java object that conforms to a specific interface, as defined by the


javaserver architecture. Servlets are loaded and invoked by services and a service can utilize
multiple servlets.

Servlets as an easy way to extend the functionality of a server either with internal
servlets, which are provided with the server or with user-written servlets, which function as.

5
As with services,servlets, servlets can be added,removed or configured while the server is
running.

Your first Sevlet:

The basic structure of servlets

A Servlet is an Java application programming interface (API) running on the server, which
intercepts requests made by the client and generates/sends a response. The javax.servlet and
javax.servlet.http packages provide interfaces and classes for writing servlets.

A simple servlet that generates plain text

example - (HelloWorld.java)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

@WebServlet("/hello")
public class hello extends HttpServlet
{
@Override
public void init()
{
To initialize here
}
public void service()
{
Meaningful work happens here
}
public void destroy()
{
To free your resources here
}
}

Example program:

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;

public class first extends HttpServlet{  

public void service(ServletRequest req,ServletResponse res)  

throws IOException,ServletException{  

res.setContentType("text/html");  

 PrintWriter out=res.getWriter();  

out.print("<html><body>");  

out.print("<b>Hello World!</b>");  
6
out.print("</body></html>");  

out.close();

}  

}  

Program 2 (Addition of 2 Nos)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet(name="login", urlPatterns={"/login"})
public class addition extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Out.println(“ <h1>To add any two numbers</h1>”);
int a=5,b=10,c;
c=a+b;
out.println(“c=”+c);
out.close();
} }
FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are the different framework services supported by Java Web Server?
2. What is the role of servlet in J2EE?APR 14
Section : B

1)Write a servlet program to display Hello world Message

2). Write the ways in which a servlet program is developed

Section : C

1)What are the advantages of Servlets programming?

2)What are the advantages of using servlets than using CGI?APR 14

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages
7
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-2018)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 3 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Servlet Chaining

Servlet Chaining means the output of one servlet act as a input to another servlet. Servlet
Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with
a common servlet alias. The output from first Servlet is sent as input to other Servlet and so
on. The Output from the last Servlet is sent back to the browser. The entire process is called
Servlet Chaining.

//firstservlet
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {
  String name ;
  ServletConfig config;
  
  public void doGet(HttpServletRequest request , 
    HttpServletResponse response)
    throws ServletException , IOException {
  
    response.setContentType("text/plain");
    

8
    PrintWriter out = response.getWriter();
    name = request.getParameter("name");
    RequestDispatcher rd = config.
     getServletContext().getRequestDispatcher("SecondServlet");
    
    if(name!=null) {
    
      request.setAttribute("UserName",name);
      rd.forward(request , response);
      // Forward the value to another Secondservlet
    } else {
      response.sendError(response.SC_BAD_REQUEST, 
        "UserName Required");
    }
  }
}

//secondservlet

import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
  public void doGet(HttpServletRequest request , 
    HttpServletResponse response)
    throws ServletException , IOException {
    
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    String UserName = (String)request.getAttribute("UserName")
;
        out.println("The UserName is "+ UserName);
  }
}

Sample Programs:

//To display ip address,Host Name,System date,etc.

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="login", urlPatterns={"/login"})
public class login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

9
out.println(“ <h1>To display System Date,IP Address,Port No, Host Name and Address of
computer</h1>”);
Date d=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yy");
String da=sdf.format(d);
out.println(“ IP Address:”+request.getRemoteAddr());
out.println(“ System Name:”+<%=request.getRemoteHost());
out.println(“ Host Name:”+request.getLocalName());
out.println(“ Port No:”+request.getServerPort());
out.println(“ Session ID:”+request.getSession());
}
}

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What is servlet chaining?Nov 15

Section : B

1)Discuss the importance of Servlet Chaining.

Section : C

1)How to connect two different servlet program with the help of Servlet Chaining mechanism?Explain.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

10
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 4 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Servlet Packages(Servlet classes)


It provides the flexibility to container vendor to implement the API the way they want so
long as they follow the specification.

The servlet classes are

1) The HttpServlet class – It extends the GenericServlet class and implements Serializable interface.
It provides http specific methods such as doGet, doPost, doHead, doTrace etc.

2) GenericServlet  -Defines a generic, protocol-independent servlet. 

3) ServletInputStream -Provides an input stream for reading binary data from a client request,
including an efficient readLine method for reading data one line at a time. 

4) ServletOutputStream  -Provides an output stream for sending binary data to the client

HttpServlet class

It is an abstract class that resides in javax.servlet.http package. Because it is an abstract, it cannot be


instantiated. When building an HTTPServer, you should exend the HttpServlet class and implement
atleast one of its methods

Methods of HttpServlet class

There are many methods in HttpServlet class. They are as follows:

1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the


protected service method by converting the request and response object into http type.
11
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request
from the service method, and dispatches the request to the doXXX() method depending on the
incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET
request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST
request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD
request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the
OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT
request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the
TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the
DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.

Example:

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;
public class first extends HttpServlet{  
public void service(ServletRequest req,ServletResponse res)  
throws IOException,ServletException{  
 res.setContentType("text/html");  
PrintWriter out=res.getWriter();  
out.print("<html><body>");  
out.print("<b>Hello World!</b>");  
out.print("</body></html>");  
out.close();
}  
}  

GenericServlet class

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It


provides the implementaion of all the methods of these interfaces except the service method.

GenericServlet class can handle any type of request so it is protocol-independent.

You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.

Methods of GenericServlet class

There are many methods in GenericServlet class. They are as follows:

1. public void init(ServletConfig config) is used to initialize the servlet.


2. public abstract void service(ServletRequest request, ServletResponse response) provides
service for the incoming request. It is invoked at each time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet
is being destroyed.

12
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no need
to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file
and a stack trace.

Example Program

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;

public class first extends GenericServlet{  

public void service(ServletRequest req,ServletResponse res)  

throws IOException,ServletException{  

  res.setContentType("text/html");  

  PrintWriter out=res.getWriter();  

out.print("<html><body>");  

out.print("<b>hello generic servlet</b>");  

out.print("</body></html>");  

out.close();

}  

}  

3) The ServletInputStream class- It extends InputStream. It is implemented by the server and


provides an input stream that a servlet developer can use to read the data from a client
request. It defines the default constructor. 

       It provides an efficient readLine method. This is an abstract class, to be implemented by


a network services writer. For some application protocols, such as the HTTP POST and PUT
methods, servlet writers use the input stream to get data from clients. They access the input
stream via the ServletRequest's getInputStream method, available from within the servlet's
service method. Subclasses of ServletInputStream must provide an implementation of the
read() method. 

13
        ServletInputStream object is normally retrieved via the ServletRequest.getInputStream()
method. 
 

Constructor:

protected ServletInputStream()

Does nothing, because this is an abstract class.

Method:

public int readLine(byte[] b,  int off, int len) throws java.io.IOException

Reads the input stream, one line at a time. Starting at an offset, reads bytes into an array, until
it reads a certain number of bytes or reaches a newline character, which it reads into the array
as well. This method returns -1 if it reaches the end of the input stream before reading the
maximum number of bytes.

4) ServletOutputStream Class

        The ServletOutputStream class extends OutputStream.It is implemented by the server


and provides an output stream that a servlet developer can use to write data to a client
response. A default constructor is defined.

        A ServletOutputStream object is normally retrieved via the


ServletResponse.getOutputStream() method. 

Methods

1. public void print(datatype value) throws java.io.IOException

Writes the value to the client, without a carriage return-line feed (CRLF) character at the end.

 The datatype can be Sting, char, Boolean, int, long, float or double.

2. public void println(datatype value )throws java.io.IOException

Writes the value to the client, with a carriage return-line feed (CRLF) character at the end.

 The datatype can be Sting, char, Boolean, int, long, float or double.

14
FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define the term HTTPServlet.


2. What is GenericServlet?
3. What is the different between generic servlet and HTTP servlet?apr 14

Section : B

1)Write a note on HTTPServlet.

Section : C

1)What are the different classes supported by Servlet?Explain

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

15
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 5 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Cookies

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.

How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the
user as the old user.

Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

16
Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

Advantage of Cookies

1. Simplest technique of maintaining the state.


2. Cookies are maintained at client side.

Disadvantage of Cookies

1. It will not work if cookie is disabled from the browser.


2. Only textual information can be set in Cookie object.

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of


useful methods for cookies.

Constructor of Cookie class


Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

Returns the name of the cookie. The name cannot be changed after
public String getName()
creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add


17
cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the
cookies from the browser.

import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
  
public class FirstServlet extends HttpServlet {  
  
 public void doPost(HttpServletRequest request, HttpServletResponse response){  
    try{  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
          
    String n=request.getParameter("userName");  
    out.print("Welcome "+n);  
  
    Cookie ck=new Cookie("uname",n);//creating cookie object  
    response.addCookie(ck);//adding cookie in the response  
  
    //creating submit button  
    out.print("<form action='servlet2'>");  
    out.print("<input type='submit' value='go'>");  
    out.print("</form>");  
          
    out.close();  
  
        }catch(Exception e){System.out.println(e);}  
  }  
}  

Second program:

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;  

  

public class SecondServlet extends HttpServlet {  

  

public void doPost(HttpServletRequest request, HttpServletResponse response){  

    try{  

    response.setContentType("text/html");  

18
    PrintWriter out = response.getWriter();  

    Cookie ck[]=request.getCookies();  

    out.print("Hello "+ck[0].getValue());  

    out.close();  

        }catch(Exception e){System.out.println(e);}  

    }  

}  

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are cookies?


2. What are the different types of Cookies?
Section : B

1)How cookies work?

Section : C

1)Explain about cookies with example.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


19
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 6 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Session Tracking

HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the
client opens a separate connection to the Web server and the server automatically does not
keep any record of previous client request.

Still there are following three ways to maintain session between web client and web server:

Cookies:

A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the recieved cookie.

This may not be an effective way because many time browser does not support a cookie, so I
would not recommend to use this procedure to maintain the sessions.

Hidden Form Fields:

A web server can send a hidden HTML form field along with a unique session ID as follows:

<input type="hidden" name="sessionid" value="12345">

This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.

This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also
cannot support general session tracking.

URL Rewriting:

20
You can append some extra data on the end of each URL that identifies the session, and the
server can associate that session identifier with data it has stored about that session.

For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is


attached as sessionid=12345 which can be accessed at the web server to identify the client.

URL rewriting is a better way to maintain sessions and works for the browsers when they
don't support cookies but here drawback is that you would have generate every URL
dynamically to assign a session ID though page is simple static HTML page.

The HttpSession Object:

Apart from the above mentioned three ways, servlet provides HttpSession Interface which
provides a way to identify a user across more than one page request or visit to a Web site and
to store information about that user.

The servlet container uses this interface to create a session between an HTTP client and an
HTTP server. The session persists for a specified time period, across more than one
connection or page request from the user.

You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below:

HttpSession session = request.getSession();

You need to call request.getSession() before you send any document content to the client.
Here is a summary of the important methods available through HttpSession object:

S.N. Method & Description


public Object getAttribute(String name)
1
This method returns the object bound with the specified name in this session, or null if
no object is bound under the name.
public Enumeration getAttributeNames()
2
This method returns an Enumeration of String objects containing the names of all the
objects bound to this session.
public long getCreationTime()
3
This method returns the time when this session was created, measured in milliseconds
since midnight January 1, 1970 GMT.
public String getId()
4
This method returns a string containing the unique identifier assigned to this session.
public long getLastAccessedTime()
5
This method returns the last time the client sent a request associated with this session, as
the number of milliseconds since midnight January 1, 1970 GMT.
public int getMaxInactiveInterval()
6
This method returns the maximum time interval, in seconds, that the servlet container
will keep this session open between client accesses.
7 public void invalidate()

21
This method invalidates this session and unbinds any objects bound to it.
public boolean isNew()
8
This method returns true if the client does not yet know about the session or if the client
chooses not to join the session.
public void removeAttribute(String name)
9
This method removes the object bound with the specified name from this session.
public void setAttribute(String name, Object value)
10
This method binds an object to this session, using the name specified.
public void setMaxInactiveInterval(int interval)
11
This method specifies the time, in seconds, between client requests before the servlet
container will invalidate this session.

Session Tracking Example:

This example describes how to use the HttpSession object to find out the creation time and
the last-accessed time for a session. We would associate a new session with the request if one
does not already exist.

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class SessionTrack extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime =
new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your web page.


if (session.isNew()){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
22
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();

String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}

23
FAQ( As in Question Bank) 10 Minutes

Section : A

1. What is a session tracking?Nov 11,15


2. Define URL Rewriting.
Section : B

1) Write short notes on session management.NOV 11,15,apr 14

2) Write a program to implement page hit problem.

Section : C

1)What are the different methods supported by HttpSession class?Explain.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

24
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 7 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Security Issues(JAAS- Java authorization and authentication service)

There are four types of security.

1)HTTP Authentication:

It is to use the built-in authentication features of HTTP. When a client makes a


request for a protected resource from the server, the server responds with a special
request header and status code,which cause the browser to create a prompt for the
username and password. This is known as challenge and response, ther server
challenge the client(browser) to respond with authentication information. Once the
client responds, the server can validate the user against its own database of users and
either grant or deny access.

response.setHeader(“expires”,”Tues,01,Jan 2014 00:00:00”);

String user=request.getRemoteUser();

out.println(user);

2)Custom authentication:

Custom authentication uses the challenge and response scheme of the HTTP
authentication,but instead of the web server validating the user, that now becomes
your responsibility. It uses Base64 encoding to transmit data,so that this method is no
more secure than basic authentication.

static final string user_key=”customlogin.user”;

response.setHeader(“www-authenticate”,BASIC realm=\”custom’””);

It will force the web browser to prompt for the username and username if the
user has not yet logged in.

25
III)HTML form authentication:

Gathering information from the user with the html form. It can control type of
information that is gathered but it can also customize the form appearance such
including graphics or additional(information)instructions.

HttpSession s=request.getSession(true);

String user=(String)s.getValue(user_key);

if(user==null)

String uname=request.getParameter(FIELD_USER);

String pass=request.getParameter(FIELD_PASSWORD);

if(!validuser(uname,pass))

out.println(“<html>”);

out.println(“<head><title>Invalid user</title>”);

out.println(“<body>Invalid user</body>”);

out.println(“</html>”);

out.flush();

return;

IV)Applet authentication:

By using an applet in the web browser that communicates with a servlet, it is


to control the format of the user data being transmitted. In essence the applet will
open a URLConnection to a servlet,create a standard output stream, write data to the
stream and wait for a response from the servlet. The servlet on the other hand side of
the URLConnection will open an input stream to read the data sent from the applet,
validate the data, and return a response to the applet containing the results of the
validation.

String codebase=””+getCodeBase();

String servlet=getParameter(“servlet”);

if(servlet!=null){

if(servlet.startsWith(“/”)&&codebase.endsWith(“/”)){

codebase=codebase.substring(0,codebase.length()-1);

{
26
}

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Expand the term SAAS.


2. What is Applet authentication?
Section : B

1)Discuss the importance of SAAS.

Section : C

1) How are the security issues dealt with in servlets?APR 15

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

27
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 8 / 45

ic (Lecture Notes Per Hour) 40 Minutes

JDBC Driver:

JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.

For example, using JDBC drivers enable you to open database connections and to interact
with it by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementaions are done in third-party drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.

JDBC Drivers Types

JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into
four categories, Types 1, 2, 3, and 4, which is explained below −

Type 1: JDBC-ODBC Bridge Driver

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
no other alternative is available.

28
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors and used
in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed
on each client machine.

If we change the Database, we have to change the native API, as it is specific to a database
and they are mostly obsolete now, but you may realize some speed increase with a Type 2
driver, because it eliminates ODBC's overhead.

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java

In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format
required by the DBMS, and forwarded to the database server.
29
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

You can think of the application server as a JDBC "proxy," meaning that it makes calls for
the client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type 4: 100% Pure Java

In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database
and is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the
client or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
30
Database access with JDBC

The basic process of connecting to a database via jdbc looks like this

1)Register the JDBC driver with the driver manager.


2)establish a database connection
3)execute an sql statement
4)process the results
5)close the database connection.

1)Register the JDBC driver with the driver manager:


A JDBC driver facilitates communication with the dabase. This translation provides JDBC
applications with data independence.A JDBC driver automatically registers with driver manager when
it is loaded. A driver manager’s job is to maintain driver objects that are available to JDBC clients. To
load a JDBC driver, use the class.forName() method.

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

2)Establish a database connection:


Once a valid server is loaded, you can use it to establish a connection to the database. A
JDBC connection is identified by “database url” that tells the driver manager which driver and
database to use.
A database connection is established by using getConnection() method.
Connection con=DriverManager.getConnection(“jdbc:odbc:empdsn”,”scott”,”tiger”);

3)Execute an sql statement:


Once establish, the database connection can be used to submit the sql statements to the
database. An sql statement performs some operation on the database,such inserting,deleting and
updating. To execute an sql statement, a statement object must be created using the connection object
is createStatement() method.
Statement st=con.createStatement()

Using the statement object’s executeQuery() method,information can be retrieved from the
database.
ResultSet rs=st.executeQuery(“select * from emp”);

4)Process the results


To process the results, you can iterate through thr rows of the ResultSet using ResultSet
object’s next() method and previous() method.
while(rs.next())
{
System.out.println(rs.getInt(“empid”));
System.out.println(rs.getString(“empname”);
}

5)Close the database connection


You should always close the connection when processing is complete. The connection object
provides a simple close() method for this purpose.
st.close();
con.close();

31
HTML:

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="http://localhost:8080/WebApplication1/login">
<p align="center">Login Details</p>
<p align="center">Login Name:<input type="text" name="lname"></p>
<p align="center">Password:<input type="password" name="lpass"></p>
<p align="center"><input type="submit" name="submit" value="insert">
<input type="submit" name="submit" value="delete">
<input type="submit" name="submit" value="modify">
<input type="submit" name="submit" value="display"></p>
</form></body> </html>

SERVLET
:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="login", urlPatterns={"/login"})
public class login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s=request.getParameter("submit");
String lname="",lpass="";
out.println("<html>");
out.println("<body>");
out.println("<form action=\"http://localhost:19533/WebApplication4/newhtml.html\">");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:ins","system","tiger");
Statement st=con.createStatement();
if(s.equals("insert") {
lname=request.getParameter("lname");
lpass=request.getParameter("lpass");
st.executeUpdate("insert into loginsemp values('"+lname+"','"+lpass+"')");
out.println("inserted");
}
else if(s.equals("delete"))
{
32
lname=request.getParameter("lname");
st.executeUpdate("delete from loginsemp where lname='"+lname+"'");
out.println("deleted");
}
else if(s.equals("modify"))
{
lname=request.getParameter("lname");
lpass=request.getParameter("lpass");
st.executeUpdate("update loginsemp set lpass='"+lpass+"' where lname='"+lname+"'");
out.println("updated");
}
else
{
ResultSet rs=st.executeQuery("select * from loginsemp");
out.println("<p align=\"center\">Login Details</p>");
out.println("<table border=\"1\" align=\"center\">");
while(rs.next())
{ out.println("<tr>");
out.println("<td>");
out.print(rs.getString("lname"));
out.println("</td>");
out.println("<td>");
out.print(rs.getString("lpass"));
out.println("</td>");
out.println("</tr>");

}
out.println("</table>");

}
} catch(Exception e){out.println(e);}
out.println("<p align=\"center\"><input type=\"submit\" value=\"go main page\"></p>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
out.close();
}
}

33
FAQ( As in Question Bank) 10 Minutes

Section : A

1. List out different JDBC drivers.


2. Expand the term JDBC.
Section : B

1)Explain various JDBC drivers in detail.

2) How to use JDBC in servlets? Explain with example. NOV 15


Section : C

1) Write a servlet program to implement student details using JDBC

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

34
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 9 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Server side includes


It allows you to embed objects calls within an http documents using a special <servlet> tag.
By convention, these documents should use the .shtml file extension. This extension indicat3es to the
server that the html documents includes SSI directives and, therefore, should be passed to a
specialized SSI servlet for processing.

When a <servlet> tag is encountered, SSI include servlet loads the servlet specified by the
<servlet> tag. Executes it and includes the servlet’s output in the html page returned to the client.

The following sequence of events may help clarify the SSI process.

1)The server receives a request for the index.shtml

2)the java enables server maps all .shtml files to the SSI servlet by default.

3)SSI include servlet parses the required html document searching for <servlet> tag.

4) The servlet specified by the <servlet> tag generates data that is included in the html page returned
to the client.

<SERVLET CODE=ServletName CODEBASE=http://server:port/dir


initParam1=initValue1 initParam2=initValue2>
<PARAM NAME=param1 VALUE=value1>
<PARAM NAME=param2 VALUE=value2>
If you see this text, it means that the web server
providing this page does not support the SERVLET tag.
</SERVLET>

The following html servlet program explain the concept of server side includes.

35
Html program:
<HTML>
<HEAD><TITLE>Times!</TITLE></HEAD>
<BODY>
The current time here is:
<SERVLET CODE=CurrentTime>
</SERVLET>
<P>
The current time in London is:
<SERVLET CODE=CurrentTime>
<PARAM NAME=zone VALUE=GMT>
</SERVLET>
<P>
And the current time in New York is:
<SERVLET CODE=CurrentTime>
<PARAM NAME=zone VALUE=EST>
</SERVLET>
<P>
</BODY>
</HTML>

Servlet Program

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CurrentTime extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {

PrintWriter out = res.getWriter();

Date date = new Date();


DateFormat df = DateFormat.getInstance();

String zone = req.getParameter("zone");


if (zone != null) {
TimeZone tz = TimeZone.getTimeZone(zone);
df.setTimeZone(tz);
}

out.println(df.format(date));
}
}

36
FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define SSI.
Section : B

1)Give the general syntax of SSI directive.

Section : C

1) With an example, explain about SSI directives.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

37
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 10 / 45

ic (Lecture Notes Per Hour) 40 Minutes

HTML FORM:

HTML Forms are required when you want to collect some data from the site visitor. For
example during user registration you would like to collect information such as name, email
address, credit card, etc.

A form will take input from the site visitor and then will post it to a back-end application
such as CGI, ASP Script or PHP script etc. The back-end application will perform required
processing on the passed data based on defined business logic inside the application.

There are various form elements available like text fields, textarea fields, drop-down menus,
radio buttons, checkboxes, etc.

The HTML <form> tag is used to create an HTML form and it has following syntax:

<form action="Script URL" method="GET|POST">


form elements like input, textarea etc.
</form>

HTML Form Controls

There are different types of form controls that you can use to collect data using HTML form:

 Text Input Controls

 Checkboxes Controls

 Radio Box Controls

 Select Box Controls

 File Select boxes

38
 Hidden Controls

 Clickable Buttons

 Submit and Reset Button

Text Input Controls

There are three types of text input used on forms:

 Single-line text input controls - This control is used for items that require only one
line of user input, such as search boxes or names. They are created using HTML
<input> tag.

 Password input controls - This is also a single-line text input but it masks the
character as soon as a user enters it. They are also created using HTMl <input> tag.

 Multi-line text input controls - This is used when the user is required to give details
that may be longer than a single sentence. Multi-line input controls are created using
HTML <textarea> tag.

Single-line text input controls

This control is used for items that require only one line of user input, such as search boxes or
names. They are created using HTML <input> tag.

Example

Here is a basic example of a single-line text input used to take first name and last name:

<!DOCTYPE html>
<html>
<head>
<title>Text Input Control</title>
</head>
<body>
<form >
First name: <input type="text" name="first_name" />
<br>
Last name: <input type="text" name="last_name" />
</form>
</body>
</html>

Password input controls

This is also a single-line text input but it masks the character as soon as a user enters it. They
are also created using HTML <input> tag but type attribute is set to password.

Example

Here is a basic example of a single-line password input used to take user password:

<!DOCTYPE html>
<html>
<head>
<title>Password Input Control</title>
39
</head>
<body>
<form >
User ID : <input type="text" name="user_id" />
<br>
Password: <input type="password" name="password" />
</form>
</body>
</html>

Multiple-Line Text Input Controls

This is used when the user is required to give details that may be longer than a single
sentence. Multi-line input controls are created using HTML <textarea> tag.

Example

Here is a basic example of a multi-line text input used to take item description:

<!DOCTYPE html>
<html>
<head>
<title>Multiple-Line Input Control</title>
</head>
<body>
<form>
Description : <br />
<textarea rows="5" cols="50" name="description">
Enter description here...
</textarea>
</form>
</body>
</html>

Checkbox Control

Checkboxes are used when more than one option is required to be selected. They are also
created using HTML <input> tag but type attribute is set to checkbox.

Example

Here is an example HTML code for a form with two checkboxes:

<!DOCTYPE html>
<html>
<head>
<title>Checkbox Control</title>
</head>
<body>
<form>
<input type="checkbox" name="maths" value="on"> Maths
<input type="checkbox" name="physics" value="on"> Physics
</form>
</body>
</html>

Radio Button Control

Radio buttons are used when out of many options, just one option is required to be selected.
They are also created using HTML <input> tag but type attribute is set to radio.
40
Example

Here is example HTML code for a form with two radio buttons:

<!DOCTYPE html>
<html>
<head>
<title>Radio Box Control</title>
</head>
<body>
<form>
<input type="radio" name="subject" value="maths"> Maths
<input type="radio" name="subject" value="physics"> Physics
</form>
</body>
</html>

Select Box Control

A select box, also called drop down box which provides option to list down various options
in the form of drop down list, from where a user can select one or more options.

Example

Here is example HTML code for a form with one drop down box

<!DOCTYPE html>
<html>
<head>
<title>Select Box Control</title>
</head>
<body>
<form>
<select name="dropdown">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
</form>
</body>
</html>

File Upload Box

If you want to allow a user to upload a file to your web site, you will need to use a file upload
box, also known as a file select box. This is also created using the <input> element but type
attribute is set to file.

Example

Here is example HTML code for a form with one file upload box:

<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type="file" name="fileupload" accept="image/*" />
</form>
</body>
41
</html>

Button Controls

There are various ways in HTML to create clickable buttons. You can also create a clickable
button using <input> tag by setting its type attribute to button. The type attribute can take the
following values:

Type Description

Submit This creates a button that automatically submits a form.

Reset This creates a button that automatically resets form controls to their initial values.

This creates a button that is used to trigger a client-side script when the user clicks that
Button
button.

Image This creates a clickable button but we can use an image as background of the button.

Example

Here is example HTML code for a form with three types of buttons:

<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" />
<input type="button" name="ok" value="OK" />
<input type="image" name="imagebutton" src="/html/images/logo.png" />
</form>
</body>
</html>

Hidden Form Controls

Hidden form controls are used to hide data inside the page which later on can be pushed to
the server. This control hides inside the code and does not appear on the actual page. For
example, following hidden form is being used to keep current page number. When a user will
click next page then the value of hidden control will be sent to the web server and there it will
decide which page has be displayed next based on the passed current page.

Example

Here is example HTML code to show the usage of hidden control:

<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<p>This is page 10</p>
<input type="hidden" name="pagename" value="10" />

42
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" />
</form>
</body>
</html>

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Expand the term HTML


2. What are HTML forms?APR 14
3. What are the attributes of FORM?NOV 11
4. State the rules for designing a HTML form
Section : B

1)Explain Multiple-Line Text Input Controls

Section : C

1)Write a note on HTML forms

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

43
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 11/ 45

ic (Lecture Notes Per Hour) 40 Minutes

Applet to Servlet Communication


Tunneling: To use an existing need of communication and create a subprotocol within it to perform
specific tasks.

The basic flow:

1. Open the httpconnection ie)to open a new connection for each request. All http connection
uses 8 bit characters.
2. Format the method request that describes which method to invoke and any parameters
required by the method.
3. Set the http request headers. This includes the type of data being sent and total length of the
data.
4. Send the request. Write the binary stream to the server.
5. Read the request. The target servlet will be invoked and given the http request data.
6. Invoke the method. The method will be called on the server object.
7. Format the method response. If the invoked method throws and exception, the error message
will be sent to the client.
8. Set the http response headers. As with the request headers, the type and the length of the data
being must be set.
9. Send the request. The binary stream will be send to the web servers and in turn, will be
returned to the client.
10. Close the connection.

44
Applet program:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
public class ap extends Applet implements ActionListener
{
Button b1=new Button(“Load”);
TextArea ta=new TextArea(5,20);
public void init()
{
add(b1);
add(ta);
B1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1){
try
{
URL u=new url(http://localhost:8080/examples/servlet/tunn);
InputStream in=u.openStream();
byte b[]=new byte[300];
in.read(b);
ta.setText(new String(b));
In.close();
}catch(Exception e){System.out.println(e);}
}
}
//<applet code=”ap” width=”300” height=”300”></applet>

Servlet Program

import java.io.*;  

import javax.servlet.*;  

import javax.servlet.http.*;

public class tunn extends HttpServlet{  

public void service(ServletRequest req,ServletResponse res)  

throws IOException,ServletException{  

  res.setContentType("text/html");  

  PrintWriter out=res.getWriter();  

try{

out.print("<html><body>");  

out.print("<b>Hello World!</b>");  

out.print("<b>Welcome to tunning!</b>");  
45
out.print("</body></html>");  

}catch(Exception e){System.out.println(e);}

out.close();

}  

}  

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What is Tunneling?
2. What is the role of servlet in J2EE?APR 14
Section : B

1)Explain the flow of APPLET to Servlet communication.

2)Discuss the structure of a Servlet Program.

Section : C

1) Write a program to implement applet to servlet communication.NOV 15

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

46
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 12 / 45

ic (Lecture Notes Per Hour) 40 Minutes

JavaBean
A javabean is a software component written in the java programming language.Lets you build
reusable applications or building blocks called components that can be deployed in a network or any
major as platform.This standard defines the mechanisms by which components perform common
tasks such as communication with each other, interacting with tools and saving/restoring their
configuration. It allows you to efficiently construct applications by configuring and connecting
components called beans.

The software component assembly model

Software components:
The situation is represented in figure 1.1 that diagram shows a system that is
composed of parts x,y&z. These process interact with each other by using proprietary mechanisms.
They are tightly joined. The connections among them are shown as this lines to symbolize that these
links are very difficult to change or enchance.

A system constructed with software component is represented in figure 1.2. Here the system
is composed of components c1 through c5. The arrows that originate from a component represents
events that in generates. These are objects that depict some state change in that component. Events are
the standard mechanism by which object interact. The arrows are shown as thin to indicate that is easy
to add additional components that should receive events. Components that should receive an event are
loosly coupled with the source of that event.

47
Components and Containers

JavaBeans are Java software components that are designed for maximum reuse. This model
focuses on the use of components and containers.

Components are specialized, self-contained software entities that can be replicated,


customized, and inserted into applications and applets. Containers are simply components
that contain other components. A container is used as a framework for visually organizing
components. Visual development tools allow components to be dragged and dropped into a
container, resized, and positioned.

The components and containers of the JavaBeans component model are similar in many ways
to the Component and Container classes of the AWT.

 Components come in a variety of different implementations and support a wide range


of functions.
 Numerous individual components can be created and tailored for different
applications.
 Components are contained within containers.
 Components can also be containers and contain other components.
 Interaction with components occurs through event handling and method invocation.

In other ways, the components and containers of JavaBeans extend beyond the Component
and Container classes of the AWT.

 JavaBeans components and containers are not restricted to the AWT. Almost any kind
of Java object can be implemented as a JavaBean.
 Components written in other programming languages can be reused in Java software
development via special Java interface code.
 Components written in Java can be used in other component implementations, such as
ActiveX, via special interfaces referred to as bridges.
 The important point to remember about JavaBeans components and containers is that
they support a hierarchical software development approach where simple components
can be assembled within containers to produce more complex components. This
capability allows software developers to make maximum reuse of existing software
components when creating new software or improving existing software.

Introspection and Discovery

Introspection allows visual programming tools to drag and drop a component onto an
application or applet design and dynamically determine what component interface methods
and properties are available. Interface methods are public methods of a bean that are available
for use by other components. Properties are attributes of a bean that are implemented by the
bean class's field variables and accessed via accessor methods.

JavaBeans support introspection at multiple levels. At a low level, introspection can be


accomplished using the reflection capabilities of the java.lang.reflect package. These
capabilities allow Java objects to discover information about the public methods, fields, and
constructors of loaded classes during program execution. Reflection allows introspection to
be accomplished for all beans. All you have to do is declare a method or variable as public
and it can be discovered using reflection.

48
Interface Methods and Properties

Properties determine the appearance or behavior of a component. A component's properties


can be modified during the visual design of an application. Most visual design tools provide
property sheets to facilitate the setting of a component's properties. Property sheets identify
all of the properties of a component and often provide help information related to specific
properties. The properties and help information are discovered by visual design tools using
introspection. Figure 24.3 provides an example of a property sheet.

In JavaBeans, all properties are accessed through special interface methods, referred to as
accessor methods. There are two types of accessor methods: getter methods and setter
methods. Getter methods retrieve the values of properties, and setter methods set property
values.

Interface methods are methods that are used to modify the behavior or state of a component
or to retrieve information about the state of a component. These methods are often used to
support event handling.

Persistence
Persistence allows components to be customized for later use. For example, during design,
you can create two button beans--one with a blue background color and a yellow foreground
color and another with a red background color and a white foreground color. The color
modifications are stored along with instances of each bean object. When the beans are
displayed during a program's execution, they are displayed using the modified colors.

JavaBeans supports persistence through object serialization. Object serialization is the


capability to write a Java object to a stream in such a way that the definition and current state
of the object are preserved. When a serialized object is read from a stream, the object is
initialized and in exactly the same state it was in when it was written to the stream.

Events
Visual development tools allow components to be dragged and dropped into a container,
resized, and positioned. The visual nature of these tools greatly simplifies the development of
user interfaces.They also allow component event handling to be described in a visual manner.

Events are generated in response to certain actions, such as the user clicking or moving the
mouse or pressing a keyboard key. The event is handled by an event handler. Beans can
handle events that occur local to them. For example, a button-based bean is required to
handle the clicking of a button. Beans can also call upon other beans to complete the handling
of an event.

Introspectional and Builder tools:

1)Builder tools

It is to configure a set of beans and visually connect them to construct a working system. Also
it tells you about the properties, events and methods provided by each of those beans.

49
2)Introspection

It is the ability to obtain information about the properties, events and methods of a bean. This
feature is used by builder tool. It provides the data that is needed so developers who are using beans
can configure and connect components.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are events?


2. Write a note on JavaBean.
3. Write a short on Method.
4. What are components?
5. What is introspection?
Section : B

1)List out diffetent tools supported by JavaBean with neat explanation.

Section : C

1)Explain the software component assembly model.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

50
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 13 / 45

ic (Lecture Notes Per Hour) 40 Minutes

The bean development kit


It allows you to configure and interconnect a set of beans. Using it, you change the properties
of a bean.link two or more beans and watch bean execute.Therefore, the bdk provides an easy way for
you to test beans that you write and to explore the capabilities of beans by others.

The bdk also includes a set of demonstration components and their source code. The bdk is a
java application. Therefore, it is necessary that you also install the java developer kit on your
computer.

Run the bdk as

D:/bdk1.4/beanbox/run

51
Types of Bean

1)jugglerbean

It represents an animation that shows the java mascot doing a juggling act.

2)ourbuttonbean

It provides a push button.

3)moleculebean

It displays a visual representation of a molecule. The following substances are


available”:benzene,cyclohexance,ethane,water,etc.

4)ticktock bean

It generates an events at regular interval. These events can be mapped to method invocations
to other beans.

Benefits of Javabean
1)write once and run anywhere

2)a set of beans,supporting classes and associated resources can be packaged into java archieve file.
This provides a convenient mechanism to deliver software component to users.

3)a bean developer can explicitly control the properties,events and methods that are presented to the
user via builder tool.

4)property editors and customizers can be provided for users

5)standard mechanisms are used to save the state of a bean. This information can later be retrieved.

6)a components can be designed so it provides in different locales


52
7)it can be integrated with software built with other architecture such as corba,activex, etc.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define BDK
2. List any four types of JavaBean.
Section : B

1)What are the benefits of JavaBean?Explain.

Section : C

1)Explain in detail about the bean development kit.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

53
Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 14 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Developing beans
Creating a spectrum bean

1)create a new directory based on package name from z:

2)Write a bean program and store it in z:

package spectrum;

import java.awt.*;

public class spectrum extends Canvas

54
{

private Boolean vertical;

public spectrum()

vertical=true;

setsize(100,100);

public Boolean getvertical()

return vertical;

public void setvertical(Boolean vertical)

this.vertical=vertical;

repaint();

public void paint(Graphics g)

float sat=1.0f;

float bri=1.0f;

Dimension d=getSize();

if(vertical)

for(int y=0;y<d.height;y++)

float hue=(float)y/(d.length-1);

g.setColor(Color.getHSBColor(hue,sat,bri));

g.drawLine(0,y,d.width-1,y);

else

55
for(int x=0;x<d.width;x++)

float hue=(float)x/(d.width-1);

g.setColor(Color.getHSBColor(hue,sat,bri);

g.drawLine(x,0,x,d.height-1);

4)Create a manifest file from z:/spectrum

Z:/spectrum/edit spectrum.mft

Type

Name:spectrum\spectrum.class

Java-Bean:True

5)create a jar file

Z:/spectrum/jar cfm d:/bdk1.4/jar/spectrum.jar *.mft *.class

6)Run the bean program

Z:/bdk1.4/beanbox/run

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are jar files?


2. What is the manifest file?
Section : B

1)Write a note on Jar files

Section : C

1)List out the steps involved to create a simple bean with a simple program

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

56
Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 15 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Notable Beans or Persistence:


It is defining the serialization and deserialization mechanisms that allows you to save and
restore the state of objects.

1.Serailization

It is the ability to save the state of several objects to a stream. The stream is typically
associated with a file. This allows an application to start an execution,create a set of objects, save
their state in a file and terminate.

The serialization objects:

It provides several stream classes that aid in the specification of beans. Three are
objectoutputstream,objectinputstream and objectstream class.
57
1.1 ObjectoutputStream

It provides methods to serialize objects,arrays and simple types to an output stream. The methods
are

1)void close()-closes the stream

2)void flush()-flushes the stream

3)void reset()-resets the stream

4)void write(int i)-writes i to the ream

5)void write(byte b[])-writes the array b to the stream

6)void writeBoolean(Boolean b)-writes b to the stream

7)void writeByte(int b)-writes b to the stream

8)void writeDouble(float b)-write Boolean b to the stream

9)void writeLong(long l)-writes long l to the stream

10)void writeShort(short s)-writes s to the stream

1.2 ObjectStream Class:

It encapsulates information about a serialized object. It contains the name of the class and
long named serial version UID. Instances of this object are created and stored in the serial stream.
This is the mechanism by which type information is saved.

1.2 ObjectInputStream class


It provides method to describe objects arrays and simple types from an output stream.
Methods
1)void available()-returns the no of bytes that are available for reading.
2)void close()-closes the stream
3)int read()-returns a byte from the stream. Blocks if no data is available.
4)float readFloat()-reads a float from the stream
5)int readInt()-reads an int from the stream
6)long readLong()-reads a long from the stream
7)short readShort()-reads a short from the stream
8)char readChar()-reads a char from the stream
9)string readUTF()-reads a UTF format string from the stream
10)byte readByte()-reads a byte from the stream

Example program

package serial;

import java.awt.*;

import java.io.*;

import java.util.*;

public class save1

{
58
public static void main(String args[])

rry

Vector v=new Vector();

v.add(add Integer(-7);

v.addElement(new Rectangle(20,20,100,50));

v.addElement(“Hello”);

System.out.println(v);

FileOutputStream fos=new FileOutputStream(“save1.date”);

ObjectOutputStream oos=new ObjectOutputStream(fos);

oos.writeObject(v);

oos.flush();

oos.close();

}catch(Exception e){System.out.println(e);

To test this program,type the following on the command line

java serial.save1

The output from this program is shown here.

[-7,java.awt.rectangle[x=20,y=20,width=100,height=100,Hello]

2)Deserialization

It is the ability the restore the state of several objects from a stream. This allows an
application to start an execution, read a file,restore a set of objects from the data in that file and
continue.

It provides several stream classes that and in the deserialization of beans

2.1 ObjectoutputStream

It provides methods to serialize objects,arrays and simple types to an output stream. The methods
are

1)void close()-closes the stream

2)void flush()-flushes the stream

3)void reset()-resets the stream


59
4)void write(int i)-writes i to the ream

5)void write(byte b[])-writes the array b to the stream

6)void writeBoolean(Boolean b)-writes b to the stream

7)void writeByte(int b)-writes b to the stream

8)void writeDouble(float b)-write Boolean b to the stream

9)void writeLong(long l)-writes long l to the stream

10)void writeShort(short s)-writes s to the stream

2.2 ObjectStream Class:

It encapsulates information about a serialized object. It contains the name of the class and
long named serial version UID. Instances of this object are created and stored in the serial stream.
This is the mechanism by which type information is saved.

2.2 ObjectInputStream class


It provides method to describe objects arrays and simple types from an output stream.
Methods
1)void available()-returns the no of bytes that are available for reading.
2)void close()-closes the stream
3)int read()-returns a byte from the stream. Blocks if no data is available.
4)float readFloat()-reads a float from the stream
5)int readInt()-reads an int from the stream
6)long readLong()-reads a long from the stream
7)short readShort()-reads a short from the stream
8)char readChar()-reads a char from the stream
9)string readUTF()-reads a UTF format string from the stream
10)byte readByte()-reads a byte from the stream

Example program:

It is used to perform the deserialization . All of the other objects referenced by the vector are
automatically deserialized.

package serial;

import java.io.*;

public class restore

public static void main(String args[])

try {

FileInputStream fis=new FileInputStream(args[0]);

ObjectInputStream ois=new ObjectInputStream(fis);

Object obj=ois.readObject();

fis.close();
60
System.out.println(obj);

}catch(Exception e){System.out.println(e);}

To test the program,use the following the command

D:/jdk1.4/bin/java serial.restore save1.date

The output of the above program is

[-7 java.awt.rectangle[x=20,y=20,width=100,height=100,Hello]

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define the term serialization


2. What is deserialization?
Section : B

1)Discuss the importance of Serialization.

Section : C

1)What are the characteristics of Persistence?Explain in detail.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

61
Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 16 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Infobus
Two or more javabeans can dynamically exchange data through the information bus(infobus).
However, communicating beans must implement required interfaces defined by the infobus.
Communication beans can be located in a java application or on a web page.

62
There are 3 different roles in an infobus.

1)data producers

Beans mainly responsible for accessing data from their native store. Such as files,
dbms,etc.

2)data consumers

Beans responsible for retrieving data the bus for analysis or visualdisplay.

3)data controllers

An optional component that regulates or consumers. A javabean can be both a


consumer and producers.

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class demo extends Applet implements InfoBusMember, InfoBusDataProducer,


ActionListener {

private SimpleDataItem data;

private String bus=null,guest;

private Object available=new Object();

public infobus getInfoBus()

return IBMS.GetInfoBus();

63
}

public void init()

super.init();

IBMS=new InfoBusMemberSupport(this);

IBMS.addInfoBusPropertyListener(this);

bus=getParameter(“Infobusname”);

guest=getParameter(“DataItemName”);

If (guest==null) guest=”GUEST”;

if(bus!=null)

IBMS.joinInfoBus(bus);

else

IBMS.joinInfoBus(this);

Glassgow Developments:
Glassgow developments are the result of an upgrade program. The glassgow
specification documents the objectives,rationale,requirements and design of this upgrade. The
javabeans improvements resulting from glassgow can be grouped into the following the three
functional areas.

1)The extensible runtime containment and service protocol; a protocol that lets beans find out
information about their container and the services that it provides.

2)The javabeans activation framework: a framework for mapping data to beans based on the
data’s type.

3)the drag and drop subsystem.

Builder tools
It is to configure a set of beans and visually connect them to construct a working system. Also
it tells you about the properties, events and methods provided by each of those beans.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Write a note on Infobus.


2. Define customization.
Section : B

1)Discuss the importance of Customizers.


64
Section : C

1)With neat diagram, explain about Infobus.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 17 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Bound Properties
When a bound property is changed, a property change event is multicast to other beans to
inform them of this update. This provides a convenient mechanism to communicate a change in a
property among a set of components.

For example, the color property of jellybean is a bound property. Therefore a property change
event is generated whenever that property changes and it is multicast to any listener who previously
registered to receive such notifications.

65
The following classes and interfaces provides this functionality.

1)PropertyChangeEvent-It defines the event notifications that are multicast by a bean who one of its
bound properties are changed.

Methods

1)object getNewValue()-returns an object with the new value of the property.

2)object getOldValue()-returns an object with the old value of the property.

3)object getPropagationId()-returns the propagation ID.

2)PropertyChangeListener: it is used to receive propertychangeevent notification

Method

void propertyChange(PropertyChangeEvent pce)

3)PropertyVhangeSupport

It can be used to perform much of the work associated with bound properties.

Method

1)synchronized void addPropertyChangeListener(PropertyChangeListener pcl);

2)synchronized void removePropertyChangeListener(propertychangelistener pcl)-registers


and unregisters listener for property change events.

3)void fivePropertyChange(String pname,object oldvalue,object newvalue)-a property change


notification is multicast to the listener via this method

Example

1)start the bdk and create an instance of the circle,square and triangle beans

2)select the circle components

3)select the edit/bind property options from the beanbox. Observe that a dialogbox titled
propertyNameDialog appears. This allows you to select a source property.

4)select the color property from this dialog box and press the ok button. A red line extends
from the circle components to the cursor position.

5)position the mouse inside the square component and click the left mouse button. Observe
that a dialog box titled propertyNameDialog appears. This allows you to select a target property.

6)select the color property from the dialog box and press the ok button. Observe that the color
of square changes to that of the circle.

7)change the color of the circle and observe that the color of square also changes. This is
because the color property is bound to the color property of circle.

Constrained Properties

A constrained property is a special kind of bound property. For a constrained property, the bean keeps
track of a set of veto listeners. When a constrained property is about to change, the listeners are
66
consulted about the change. Any one of the listeners has a chance to veto the change, in which case
the property remains unchanged.

The veto listeners are separate from the property change listeners. Fortunately, the java.beans package
includes a VetoableChangeSupport class that greatly simplifies constrained properties.

Changes to the mouthWidth example are shown in bold:

import java.beans.*;

public class FaceBean {


private int mMouthWidth = 90;
private PropertyChangeSupport mPcs =
new PropertyChangeSupport(this);
private VetoableChangeSupport mVcs =
new VetoableChangeSupport(this);

public int getMouthWidth() {


return mMouthWidth;
}

public void
setMouthWidth(int mw) throws PropertyVetoException {
int oldMouthWidth = mMouthWidth;
mVcs.fireVetoableChange("mouthWidth",
oldMouthWidth, mw);
mMouthWidth = mw;
mPcs.firePropertyChange("mouthWidth",
oldMouthWidth, mw);
}

public void
addPropertyChangeListener(PropertyChangeListener listener) {
mPcs.addPropertyChangeListener(listener);
}

public void
removePropertyChangeListener(PropertyChangeListener listener) {
mPcs.removePropertyChangeListener(listener);
}

public void
addVetoableChangeListener(VetoableChangeListener listener) {
mVcs.addVetoableChangeListener(listener);
}

public void
removeVetoableChangeListener(VetoableChangeListener listener) {
mVcs.removeVetoableChangeListener(listener);
}
}
FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are properties?

Section : B

1)With neat example, explain about the bound properties.


67
Section : C

1)Write a note on constrained properties.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 18 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Jar files
It provide a standard mechanism to compress and package a set of files for distribution to
users. You can create a single jar files that contains several beans and any associated files.

The following files may be packaged into one jar file

 The bean
 Any supporting .class file
68
 .txt and .html files that provide help to the user
 Static images
 Audio and video clips
 Configuration data
 Any other files required for the software to operate.

It is easier for a user to receive and install one deliverable that to handle multiple files.

The elements in the JAR file are compressed by using the industry standard zip algorithms.

Each of the files in the archieve contains an associated digital signatures. It indicates that the
file was produced by a specific individual or organization.

The first element in the JAR file is always a manifest file. This is a plain text file that contains
information about all of the other files in the archieve. The manifest file indicates which of the .class
files are javabeans.

The jar utility:

It allows you to create and manage jar files. The command-line tool is located in the same
directory as the java compiler and other JDK tools. Its syntax is

Jar options files

Options are

c-create an archieve

f-the first element in files is the name of the achieve to be created.

m-the second element in files is the name of the manifest file

t-tabulate the contents of the archive

v-provide verbose output

x-extract files from the archive

o-do not compression

m-do not create a manifest file

Examples of jar utitlity

1)tabulating the contents of a JAR file

C:/bdk1.4/jars/jar tvf juggler.jar

2)extracting files from a JAR file

1)create a new directory and copy juggler.jar to the new directory.

2)change to the new directory

3)type c:/bdk1.4/jars/jar xvf juggler.jar

FAQ( As in Question Bank) 10 Minutes

Section : A

3. What are jar files?


69
4. What is the manifest file?
Section : B

1)Write a note on Jar files

Section : C

1)List out the steps involved to create a simple bean with a simple program

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 19 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Introspection:
It is the ability to obtain information about the properties,events and methods of a bean. This
feature is used by builder tool. It provides the date is needed so developers who are using beans can
configure and connect components.

It is necessary for building production quality beans

1)introspector

70
The introspector class in the java.beans package provides static methods that allows you to
obtain information about the properties,events and methods of a bean.

Methods

Static BeanInfo getBeanInfo(class beancls);

Static BeanInfo getBeanInfo(class beancls,class ignorecls)

The first form returns an object that implements the beaninfo interface. The second form also
returns an object that implements the beaninfo interface.

2)BeanInfo

It defines a set of constants and methods that are central to the process of introspection.

The int constants defined by BeanInfo are ICON-COLOR-16X16,ICON-COLOR-


32X32,ICON-MONO-16X16 AND ICON-MONO-32X32.

Methods are

1)BeanDescriptor getBeanDescriptor()-returns a beandescriptor object for a bean.

2)image getIcon(int iconsize)-returns an icon that can be displayed to represent a bean.

3)EventSetDescriptor getEventDescriptor()-returns an array of eventsetdescriptor objects for


the events.

3)FeatureDescriptor

It is the immediate superclass of the BeanDescriptor,EventSetDescriptor


,MethodDescriptor,ParameterDescriptor and PropertyDescriptor.

1)BeanDescriptor

It associates a customizes with a bean. A customizer provides a graphical user interface


through which a user may modify the properties of a bean.

Methods

1)class getBeanInfo()-returns the class object for a bean.

2)class getCustomizersClass()-returns the class object for a bean customizer

2)EventSetDescriptor

It describes a set of events generated by a bean.

Methods

1)method getAddListenerMethod()-returns a method object for the registration method.

2)methodDescriptor[] getListenerDescriptor()-returns an array of methoddescriptor object fro


the methods in the listener interface.

3)MethodDescriptor

It describes a method of a bean

Methods

71
1)method getMethod()-returns a method object for the associated method

2)parameterDescriptor[] getParameterDescriptor()-returns an array of parameterdescriptor object for


the parameter of this method.

4)ParameterDescriptor

It describes the parameter of a method. The class does not provide any additional fields or
method beyond those its FeatureDescriptor superclass.

5)PropertyDescriptor-it describes a property of a bean

Methods

1)class getPropertyType()-returns the class object for the property

2)method getReadMethod()-returns a method object for the reader

3)method getWriteMethod()-returns a method object for the writer.

6)IndexedPropertyDescriptor-it describes or indexed property of a bean

Methods:

1)class getIndexedPropertyType()-returns a class object for the indexed property.

2)method getIndexedReadMethod() and method getIndexedWriteMethod()-returns the method object


for the indexed read and write methods.

package spectrum;

import java.beans.*;

import java.awt.event.*;

import java.lang.reflect.*;

public class binfo extends SimpleBeanInfo

public propertyDescriptor[] getPropertyDescriptor()

try

class cls=spectrum.class;

PropertyDescriptor pd=new PropertyDescriptor(“vertical”,cls);

PropertyDescriptor pds[]={pd};

return pds;

}catch(Exception e){}

return null;

}
72
public methodDescriptor[] getMethodDescriptor()

MethodDescriptor mds[]={};

return mds;

Customizers:
It provide support for you to create your own property editors. When you use a bean
customizer, you have complete control over how to configure or edit a bean. A customizer is an
application that specifically targets a bean’s customization. Customizers are used where sophisticated
instructions would be needed to change a bean and where property editors are too primitives to
achieve bean customizers.

The customizer interface:

It is defined in the java.beans package. It specifies the three methods show below.

void add PropertyChangeListener(PropertyChangeListener pcl);

void remotePropertyChangeListener(propertychangeListener pcl);

void setObject(object bean);

The first two methods allow listeners to register and unregister for propertychangeevent
objects from this customizers. The last method is called by the builder tool to give the customizer a
reference to the bean whose properties are to be modified.

Example program

package harmonics;

import java.awt.*;

import java.util.*;

public class harm extends Canvas

public final static int nf=20;

private BitSet fre;

…………

Javabeans API

73
The javabeans functionality is provided by a set of classes and interfaces in the
java.beans package.

The following lists the classes in java.beans.

1)BeanDescriptor-this class provides informations about a bean. It also allows you to


associate a customizer with a bean

2)Beans-It is used to obtain information about a bean.

3)EventHandler-supports dynamic event listener creation.

4)EventSetDescriptor-instances of this class describe an event that can be generated by a


bean.

5)Introspector-analyzes a bean and constructs a BeanInfo object that describes the


component.

6)PropertyDescriptor-instances of this class describe a property of a bean

7)parameterDescriptor-Instances of this class describe a method parameter.

8)PropertyChangeEvent-This event is generated when bound or constrainted properties are


changed.

9)IntrospectionException-An exception of this type is generated if a problem occurs when


analysing a bean

10)IndexedPropertyDescriptor-instances of this class describe an indexed property of a bean

11)FeatureDescriptor-This is the superclass of the PropertyDescriptor ,EventSetDescriptor


and MethodDescriptor class.

12)MethodDescriptor-Instances of this class describe a method of a bean.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are Introspection?


Section : B

1)Explain the importance of introspector

Section : C

1)Discuss the characteristics of Introspection

Discussion 05 Minutes

74
Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 20 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Enterprise Java Bean

Overview of EJB

75
EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform. J2EE
platform have component based architecture to provide multi-tiered, distributed and highly
transactional features to enterprise level applications.

EJB provides an architecture to develop and deploy component based enterprise applications
considering robustness, high scalability and high performance. An EJB application can be
deployed on any of the application server compliant with J2EE 1.3 standard specification.

It is a rapid application development for the server side.

Applications of EJB

1)stock trading system

2)banking application

3)a customer call center

4)a procurement system

5)an insurance risk analysis application

Advantages of EJB

1)It is agreed upon by the industry

2)portability

3)interface/implementation separation

4)safe and secure

5)cross platform

6)rapid application development

EJB’S role:

1)EJB specifies an execution environment

EJB specification describes container. The container provides services such support
for transactions, support for persistence and management of multiple instances of a given
bean.

2)EJB exists in middle tier:

That are used to encapsulate business rules. A typical EJB consists of methods that
encapsulate business logic. A remote client can invoke these methods, which typically result
in the updating of a database.

3)EJB support transaction processing:


76
An EJB container must support transactions. At development time, the bean developer
can specify what type of transaction support is required.

4)EJB can maintain state:

It can maintainstate across several method invocations. The EJB container keep track
of any state information that a bean needs.

5)EJB is simple:

It must support the concurrent transaction execution of many beans, keep track of
their state, provide them with transaction support and so forth.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are the applications of EJB?


2. Define the term EJB.
Section : B

1)Discuss about Enterprise Java Bean.

Section : C

1)What are the roles of EJB?Explain

Discussion 05 Minutes

77
Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 21 / 45

ic (Lecture Notes Per Hour) 40 Minutes

EJB architecture:

78
The EJB architecture specifies the responsibilities and interactions among the following EJB
entities:

 EJB Servers
 EJB Containers
 Enterprise Beans

EJB server
The EJB Server is a vendor-specific implementation which is responsible for providing the services
necessary to host a container. Obviously, specialized containers require specialized EJB servers.

The EJB specification does not concern itself about how various services are implemented
and whether a certain service is supported by all operating systems or not. It merely outlines
what is expected of an EJB server and expects the implementation to provide that. In almost
all cases, the implementation is vendor specific and most likely proprietary. That is okay,
because Beans do not directly interact with the EJB server. They interact with the container.
As long as the container meets the specification, it should be able to deploy any EJB that also
conforms to the specification. The EJB server is typically implemented by extending an
existing product, although there are some vendors that have started from ground zero and
provide EJB servers.

EJB container
The Bean is wrapped in a container. A container can hold one or more Beans and is responsible for
providing the services required by the specification to each Bean requesting it. This is how EJB
achieves conformity. It requires a minimal set of services to be provided by a container. This way,
each Bean is guaranteed the same set of services regardless of the container in which it is running.

The specification allows for "specialized" containers. These are containers that provide more
services than what is required by the specification. Such additional services are required to
deploy specialized Beans. This is perfectly within the rules, but such Beans lose their
portability, since they will only run inside containers that provide the specialized service they
seek. This was a major compromise made by the designers of EJB so they could support a
large percentage of existing systems. Furthermore, if there is anything in the EJB that can
lead to implementation fragmentation and deviations, the specialized containers are it.
79
Enterprise JavaBeans
Enterprise JavaBeans are the components you write. They represent the business logic you need to
implement. The container and the EJB server take care of details of transaction integrity and
transaction control. Therefore, your EJB can focus mostly on the specific business function that it is
implementing. EJBs come in two flavors: session Beans and entity Beans.

Regardless of their flavor, EJB methods are never directly invoked by the client. There is an
intermediate EJBObject that intercepts method calls from the client and delegates them to the
EJB. An EJB must obviously implement the business logic and make this available via a
remote interface (again, the client does not call the EJB methods directly) . It must also
implement an

ejbCreate(...)

EJB requirements:-
The first step in any programming project is deciding what you want to do. This step is called
requirements analysis. On a large and complex project, requirement analysis can take several months
or even years and employ several analyst. The requirement are straightforward.

1)Illustrate the process of building,deploying and using an EJB

2)This example should be simple as possible, allowing us to focus on the architectural aspects of the
system,rather than on the complexities of the example itself.

3)following form these requirements,we want to build a simple client that calls a method on an
enterprise javabean.

4)to study the process of passing arguments and return values , the method that the client should take
an argument and return a value.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define EJB servers


2. What are EJB Containers?
Section : B

1)What are the requirements of EJB?Explain.

Section : C

1)Discuss the architecture of EJB.

Discussion 05 Minutes

80
Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 22 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Design and implementation of a EJB program:


There are several steps involved to create an EJB program.

1)create the remote interface for the bean

81
A remote interface is the interface with which the client interacts. The EJB container uses the
remote interface for your bean to generate both the client-side stub and server side proxy object that
passes client calls to your EJB object.

package book;

import java.rmi.*;

import javax.ejb.*;

public interface Hello extends EJBObject

String sayHello(String s) throws RemoteException;

2)create the beans home interface

The home interface is the client in initial point of connect with your EJB components. The
client obtains a reference to an object implementing the home interface via JNDI. After the client has
obtained this reference, it can use a create() to obtain a reference to an object that implements the
remote interface.

package book;

import javax.ejb.*;

public interface HelloHome extends EJBHome

public Hello create() throws java.rmi.RemoteException,javax.ejb.CreateException;

3)Create the bean implementation class

It is to implement the EJB bean itself.

package book;

import javax.ejb.*;

public class HelloBean implements SessionBean

SessionContext cts;

public String sayHello(String s)

return “Hello “+s;

public void ejbCreate()

{}
82
public void ejbRemote()

{}

public void ejbPassivate()

{}

public void ejbActivate()

{}

public void setSessionContext(SessionContext ctx)

this.ctx=ctx;

4)Compile the remote interface,home interface and bean implementation class

5)create a session descriptor

It passes information about your bean to the eventual deployment environment. At


development time, the bean developer creates an instances of the SessionDescriptor class, fills it in
with information and serialize it.

import javax.ejb.deployment.*;

import java.io.*;

import javax.util.properties;

public class DDWrite

public static void main(String args[])

SessionDescriptor sd=new SessionDescriptor();

sd.setEnterpriseBeanClassName(“Hello”);

sd.setHomeInterfaceClassName(“HelloHome”);

sd.setRemoteInterfaceClassName(“HelloRemote”);

Properties p=new Properties();

p.put(“myprop1”,”myval”);

sd.setEnvironmentProperties(p);

sd.setSessionTimeout(0);

sd.setStateManagementType(SessionDescriptor,STATELESS_SESSION);

83
try

FileOutputStream fos=new FileOutputStream(“foo.ser”);

ObjectOutputStream oos=new ObjectOutputStream(fos);

Oos.writeObject(sd);

oos.close();

}catch(Exception e){System.out.println(e);}

6)Create a manifest file

A manifest file is a text document that contains information about the contents of a jar file.

Name:HelloBeanDD.ser

Enterprise-Bean:True

7)Create an EJB-JAR file

Use the jar program that comes with the java JDK to generate your ejb-jar file.

jar cmf manifest hello.jar book;

where book-the directory to include in the jar file

manifest-the path from the current directory to the manifest.

8)Deploy the ejb-jar file

For specific information on how to deploy a bean in a particular EJB implementation, consuit
your vendors documentation. In weblogic, the tool used to deploy a bean is a java class called
weblogic.ejbc.

9)write a client

The bean is in place on the server, it’s time to write a client. EJB clients can be written using
RMI or CORBA.

import book.*;

import javax.ejb.*;

import java.rmi.*;

import javax.Naming.*;

public class HelloClient

public static void main(String args[])

{
84
try

InitialContext ic=new InitialContext();

HelloHome home=(HelloHome)ic.lookup(“HelloHome”);

Hello hel=home.create();

String retval=hel.sayHello(“hello world”);

System.out.println(“returned:”+retval);

hel.remove();

}catch(Exception e){System.out.println(e);}

10)Run the client

It is to pass a value for this property as a commandline argument.

java –Djava.Naming.factory.initial=weblogic.jndi.T3InitialContextFactory
HelloClient

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define Home Interface


2. Define the term remote Interface.
3. What is a manifest file?
Section : B

1)Explain the following with example 1)Remote Interface 2)Home Interface 3)Bean implementation
class

Section : C

1) Write the ways in which a EJB program is developed

Discussion 05 Minutes

85
Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 23 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Types of EJB

There are three different types of EJB that are suited to different purposes:

 Session EJB—A Session EJB is useful for mapping business process flow (or equivalent
application concepts). There are two sub-types of Session EJB — stateless and stateful— that
are discussed in more detail on Day 5. Session EJBs commonly represent "pure" functionality
that is created as it is needed.

86
 Entity EJB—An Entity EJB maps a combination of data (or equivalent application concept)
and associated functionality. Entity EJBs are usually based on an underlying data store and
will be created based on that data within it.

 Message-driven EJB—A Message-driven EJB is very similar in concept to a Session EJB,


but is only activated when an asynchronous message arrives.

Life cycle of stateless session bean

It has only two states

1)non-exitence

2)method-ready state

When you create a stateless session bean,the container calls the following methods on it.

1)newInstance()-which allocates space for the bean and brings it into existence

2)setSessonContext()-which gives the bean a sessionContext

3)ejbCreate()-which allow the bean to perform any necessary initializations.

Stateless session bean have no state, they can be reused by many clients in the course of their
existence. setSessionContext() is called only once, rather, it points to a dynamic object that the
container updates each time a stateless session bean’s methods are invoked.

At the end of the life cycle of a stateless session bean, the container invokes the ejbRemove()
method of the bean before destroying it.

Stateless session bean example

Listing 1 shows the code for the remote business interface, SimpleSession.java.
87
Listing 1. SimpleSession.java

package beans;

import javax.ejb.Remote;

@Remote

public interface SimpleSession

public String getEchoString(String clientString);

Listing 2 shows the code for the actual bean implementation, SimpleSessionBean.java.

Listing 2. SimpleSessionBean.java

package beans;

import javax.ejb.Stateless;

@Stateless

public class SimpleSessionBean implements SimpleSession {

public String getEchoString(String clientString) {

return clientString + " - from session bean";

Finally, Listing 3 shows the client code to test the session bean.

Listing 3. SimpleSessionClient.java

package client;

import beans.SimpleSession;

import javax.naming.InitialContext;

public class SimpleSessionClient {

88
public static void main(String[] args) throws Exception

InitialContext ctx = new InitialContext();

SimpleSession simpleSession

= (SimpleSession) ctx.lookup(SimpleSession.class.getName());

for (int i = 0; i < args.length; i++) {

String returnedString = simpleSession.getEchoString(args[i]);

System.out.println("sent string: " + args[i] +", received string: " + returnedString);

Organize the files in a directory called SimpleSessionApp, as shown in Figure 4.

Figure 4. The structure of the sample session bean files

Compiling the simple session bean application

After you've created and organized the sample session bean files as just described, follow
these steps to compile the application:

1. Open a command prompt in the SimpleSessionApp directory.


2. Compile the classes, ensuring that the CLASSPATH is set to contain all the necessary
JBoss libraries. These libraries contain all of the EJB functionality needed to make
your code interact with the application server, so it is extremely important that you get
this step right. At the command line, type the following (this should all be on one
line):

> set CLASSPATH=.;C:\jboss\lib\concurrent.jar;

C:\jboss\lib\jboss-common.jar;

c:\jboss\client\jboss-j2ee.jar;

c:\jboss\lib\commons-httpclient.jar;

C:\jboss\server\all\lib\jboss.jar;
89
C:\jboss\server\all\lib\jboss-remoting.jar;

C:\jboss\server\all\lib\jboss-transaction.jar;

C:\jboss\server\all\lib\jnpserver.jar;

C:\jboss\server\all\deploy\ejb3.deployer\jboss-ejb3.jar;

C:\jboss\server\all\deploy\ejb3.deployer\jboss-ejb3x.jar;

C:\jboss\server\all\deploy\jboss-aop.deployerjboss-aop.jar;

C:\jboss\server\all\deploy\jboss-aop.deployerjboss-aspect-library.jar

3. Within the SimpleSessionApp directory where the client and beans directories are located,
execute the following commands from the command prompt:
4. > javac -d . client/*.java
5. > javac -d . beans/*.java
6. The –d option tells the Java compiler to place the class files in subdirectories matching their
package structure, subordinate to the given directory. In this case, the given directory is the
current directory, signified by the period. As a result, the Java class files should end up in the
same directories as the source files.

Deploying the simple session bean application

Now we need to start the JBoss Server. Once the JBoss Server is up and running, you can deploy your
class files. In order to deploy your class files, you need to package your different application
components together in a compressed jar file. Make the extension of this file .ejb3, so that JBoss can
deploy it. To create the application EJB3 file, open a command prompt in the same directory that
SimpleSessionApp resides in and type in the following command:

>jar cf SimpleSessionApp.ejb3 beans\*.java

Now copy the resulting EJB3 file to the %JBOSS_HOME%/server/all/deploy directory. If your JBoss
installation is in C:\JBoss, for example, copy the file to C:\JBoss\server\all\deploy.

JBoss will automatically detect and deploy your code for you. The directory structure should now
have the files shown in Figure 5.

Figure 5. Structure of the deployed session bean application

Now for the last step: running your new bean!

Running the simple session bean application

To run the sample client, set the CLASSPATH to the same value you did earlier to compile the
application.

90
On a default Java EE 5 SDK Windows installation, ensure the CLASSPATH is set correctly by using
the following command:

> set CLASSPATH=.;C:\jboss\lib\concurrent.jar;


C:\jboss\lib\jboss-common.jar;
C:\jboss\server\all\lib\jboss.jar;
C:\jboss\server\all\lib\jboss-remoting.jar;
C:\jboss\server\all\lib\jboss-transaction.jar;
C:\jboss\server\all\lib\jnpserver.jar;
C:\jboss\server\all\deploy\ejb3.deployer\jboss-ejb3.jar;
C:\jboss\server\all\deploy\ejb3.deployer\jboss-ejb3x.jar;
C:\jboss\server\all\deploy\jboss-aop.deployer\jboss-aop.jar;
C:\jboss\server\all\deploy\jboss-aop.deployerjboss-aspect-library.jar

Next, with SimpleSessionApp as the current directory, execute the following command from the
command prompt (remember that this is all one line):

> java
-Djava.naming.factory.initial=
org.jnp.interfaces.NamingContextFactory
-Djava.naming.factory.url.pkgs=
org.jboss.naming:org.jnp.interfaces
-Djava.naming.provider.url=
localhost client.SimpleSessionClient
Now is the time for all good men

When you run the SimpleSession client program, it will produce the following output:

sent string: Now, received string: Now


sent string: is, received string: is
sent string: the, received string: the
sent string: time, received string: time
sent string: for, received string: for
sent string: all, received string: all
sent string: good, received string: good
sent string: men, received string: men

It may not seem very practical, but it makes you unbelievably popular at parties.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define entity bean


2. What is a session bean?
3. What is a message driven bean?
Section : B

1)Discss the life cycle of satelesss session bean

Section : C

1)Write a simple program to implement stateless session bean.

Discussion 05 Minutes

91
Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 24 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Stateful session session bean life cycle:

It has three states

1)non-exitence

2)method-ready state

3)method-ready in transaction

92
The container invokes the three methods that are invoked on a stateful session bean.

1)newInstance()-which allocates space for the bean and brings it into existence

2)setSessonContext()-which gives the bean a sessionContext

3)ejbCreate()-which allow the bean to perform any necessary initializations.

The statefull session bean can implement any of several ejbCreate() methods that take
different set of arguments. Within the ejbCreate() method, you set the various class available of your
EJB bean. Once the ejbCreate() executes, the bean enters the method-ready state.

Three transactions out of this states are possible.

1)the bean can enter a transaction

2)it can be passivated

3)it can be activated.

The bean enters a transaction if one of its transactional methods is invoked(TX-BEAN-


MANAGED,TX-REQUIRED,etc).

If the bean implements the sessionsynchronization interface, the container invokes its
afterbegin() to notify it that it is entering a transaction.

The bean then moves to the “method-ready in transaction” state,where it remains until the
transaction concludes. If the transaction was created specifically for the method invocation, the bean
will exit the “method ready in transaction” state immediately after the completion of the method. If
the client supplied to transaction, the bean remains in this state until a commit or rollback occurs.

If a commit occurs, the beforecompletion() is invoked, and then the aftercompletion() of


sessionsynchronization interface is invoked. With a Boolean value of true of the argument.

If, on the other hand, a rollback occurs while the bean is in the “method ready in transaction”
state, beforecompletion() is not invoked.

Stateful session bean example

Listing 4 shows the code for the bean interface, Calculator.java. It defines the business method
of the calculator.

93
Listing 4. Calculator.java

package beans;

import javax.ejb.Remote;

@Remote

public interface Calculator {

public void clearIt();

public void calculate(String operation, int value);

public int getValue();

Listing 5 shows the code for the bean class, CalculatorBean.java.

Listing 5. CalculatorBean.java

package beans;

import javax.ejb.Stateful;

@Stateful

public class CalculatorBean implements Calculator {

private int _value = 0;

public void clearIt() {

_value = 0;

public void calculate(String operation, int value) {

if (operation.equals("+")) {

_value = _value + value;

return;

if (operation.equals("-")) {

_value = _value - value;

94
return;

public int getValue() {

return _value;

Add these code files to a new application directory called SimpleCalculatorApp. Within the
directory add beans and client subdirectories. Place Calculator.java and CalculatorBean.java in the
beans directory, and CalculatorClient.java in the client directory.

Now compile the .java files following the same instructions as in the previous example. At the
command line, type the following (again, remember that this is all on one line):

> set CLASSPATH=.;C:\jboss\lib\concurrent.jar;C:\jboss\lib\jboss-common.jar;


C:\jboss\server\all\lib\jboss.jar;
C:\jboss\server\all\lib\jboss-remoting.jar;
C:\jboss\server\all\lib\jboss-transaction.jar;
C:\jboss\server\all\lib\jnpserver.jar;
C:\jboss\server\all\deploy\ejb3.deployer\jboss-ejb3.jar;
C:\jboss\server\all\deploy\ejb3.deployer\jboss-ejb3x.jar;
C:\jboss\server\all\deploy\jboss-aop.deployer\
jboss-aop.jar;
C:\jboss\server\all\deploy\jboss-aop.deployerjboss-aspect-library.jar

Next, within the SimpleCalculatorApp directory where the client and beans directories are located,
execute the following commands from the command prompt:

> javac -d . client/*.java


> javac -d . beans/*.java

Now enter the following command at the prompt:

>jar cf SimpleCalculatorApp.ejb3 SimpleCalculatorApp

Then copy the resulting EJB3 file to your JBoss deployment directory:

%JBOSS_HOME%\server\all\deploy.

Running the stateful session bean application

After deploying the application, you can now run it. On a default Java EE 5 SDK/JBoss
Windows installation, the CLASSPATH would be set correctly by using the following
command:

> set CLASSPATH=.;C:\jboss\lib\concurrent.jar;


C:\jboss\lib\jboss-common.jar;
C:\jboss\server\all\lib\jboss.jar;
C:\jboss\server\all\lib\jboss-remoting.jar;
C:\jboss\server\all\lib\jboss-transaction.jar;

95
C:\jboss\server\all\lib\jnpserver.jar;
C:\jboss\server\all\deploy\ejb3.deployer\jboss-ejb3.jar;
C:\jboss\server\all\deploy\ejb3.deployer\jboss-ejb3x.jar;
C:\jboss\server\all\deploy\jboss-aop.deployerjboss-aop.jar;
C:\jboss\server\all\deploy\jboss-aop.deployerjboss-aspect-library.jar

Next, with SimpleCalculatorApp as the current directory, execute the following command from
the operating system prompt:

> java
-Djava.naming.factory.initial=
org.jnp.interfaces.NamingContextFactory
-Djava.naming.factory.url.pkgs=
org.jboss.naming:org.jnp.interfaces
-Djava.naming.provider.url=
localhost client.CalculatorClient

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are stateful session beans?


Section : B

1)Discuss the life cycle of stateful session bean.

Section : C

1)With an example, explain about stateful session bean.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD


96
Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 25 / 45

ic (Lecture Notes Per Hour) 40 Minutes

EJB Transactions:

A transaction is a single unit of work items which follows the ACID properties. ACID stands
for Atomic, Consistent,Isolated and Durable.

 Atomic - If any of work item fails, the complete unit is considered failed. Success
meant all items executes successfully.

 Consistent - A transaction must keep the system in consistent state.

97
 Isolated - Each transaction executes independent of any other transaction.

 Durable - Transaction should survive system failure if it has been executed or


committed.

EJB Container/Servers are transaction servers and handles transactions context propagation
and distributed transactions. Transactions can be managed by the container or by custom code
handling in bean's code.

 TX_REQUIRED - Indicates that business method has to be executed within


transaction otherwise a new transaction will be started for that method.

 TX_REQUIRES_NEW - Indicates that a new transaction is to be started for the


business method.

 TX_SUPPORTS - Indicates that business method will execute as part of transaction.

 TX_NOT_SUPPORTED - Indicates that business method should not be executed as


part of transaction.

 TX-MANDATORY - Indicates that business method will execute as part of


transaction otherwise exception will be thrown.

 TX-NEVER - Indicates if business method executes as part of transaction then an


exception will be thrown.

 TX_BEAN_MANAGED-The bean-managed attribute value is the one that lets the


bean get access to the transaction service on its own behalf. Session beans get access
to the transaction service through the session context that is supplied to the bean at
initialization, as a parameter in the setSessionContext() call. The SessionContext
interface subclasses EJBContext.

Entity Beans

An entity bean is a remote object that manages persistent data, performs complex business logic,
potentially uses several dependent Java objects, and can be uniquely identified by a primary key.
Entity beans are normally coarse-grained persistent objects, in that they utilize persistent data stored
within several fine-grained persistent Java objects.

Need of entity beans:

1. When it is needed by multiple clients.

2. When any action from the database side.

3. When a transaction is to be performed from the client.

4. When the enforcement of accuracy and integrity is needed.

the lifecycle of the entity beans.

The time when the entity bean starts instantiating and till it takes the time for garbage collection is the
life cycle of an entity bean.

98
The life cycle has three states, namely

1. Does not exist state


2. Pooled state
3. Ready state

1.Doesnot Exist State :

- The life of a bean’s instance starts with a set of files. These files include remote interface, interface,
deployment descriptor, primary key and the needed files at the time of deployment.

- In this state, no instances of the bean exists.

2. Pooled State :

- At the time of starting the EJB server,with the help of the method Class.newInstance() , all the
instances are created and placed in a pool. The default values of the persistent fields are set. The bean
class should never contain the constructor. Therefore the default no-argument must be available in the
container.

- Before placing the instances in the pool, an instance EntityContext is assigned by the container
which assigns and implements the setEntityContext() method by the bean class, followed by entering
into the instance pool.

- Now the bean instance is available for the client requests and become active soon after receiving the
requests. The bean container provides different levels of access at every stage of the bean’s life cycle.

3. The Ready State:

- Once the bean reaches this state, it can accept the requests from the client. The state of a beans
instance reaches to ready state once the container assigns it to an EJB object.

99
- This assignment occurs in two different circumstances:

1. When the new entity bean is being created.


2. When the container is activating an entity bean.

4. End of the Life Cycle :

- The life of a bean’s instance comes to an end when the container decides to remove it from the pool
and allows it to be garbage collected.

- This may happen when the container decides to reduce the number of instances from the pool in
order to conserve the resources. So that the highest performance can be achieved.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are distributed transactions?


2. Define transactions.
3. Define ACID.
Section : B

1)Write a note on EJB Transactions.

Section : C

1)Dicuss entity bean life cycle.

Discussion 05 Minutes

100
Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 26 / 45

ic (Lecture Notes Per Hour) 40 Minutes

101
Types of Entity Beans

Container-managed persistence- A CMP bean is an entity bean whose state is


synchronized with the database automatically. In other words, the bean developer doesn't
need to write any explicit database calls into the bean code; the container will automatically
synchronize the persistent fields with the database as dictated by the deployer at deployment
time.

When a CMP bean is deployed, the deployer uses the EJB tools provided by the vendor to
map the persistent fields in the bean to the database. The persistence fields will be a subset of
the instance fields, called container-managed fields, as identified by the bean developer in
the deployment descriptor.

Bean-managed persistence- A BMP bean is an entity bean that synchronizes its state with
the database manually. In other words, the bean developer must code explicit database calls
into the bean itself. BMP provides the bean developer with more flexibility in the how the
bean reads and writes its data than a container-managed persistence (CMP) bean. CMP bean
is limited to the mapping facilities provided by the EJB vendor, BMP beans are only limited
by skill of the bean developer.

The ability to code an entity bean's persistence logic explicitly is important when the EJB
container's CMP features are insufficient to meet the needs of the entity bean. Entity beans
that need to synchronize their state with several data sources are excellent candidates for
BMP. So are beans that need to access to data sources (possibly legacy systems) that are not
supported by CMP. In addition, BMP bean are often employed when a vendors CMP
facilities are not sophisticated enough to handle complex Object-to-Relational mapping.

Creating Entity Beans(BMP)

The following steps are an overview of what you must do in creating an entity bean.

1. Create the home interfaces for the bean. The home interface defines the create and finder
methods, including findByPrimaryKey, for your bean.

2. Create the component interfaces for the bean. The component interfaces declare the methods
that a client can invoke.

3. Define the primary key for the bean. The primary key identifies each entity bean instance and
is a serializable class. You can use a simple data type class, such as java.lang.String, or
define a complex class, such as one with two or more objects as components of the primary
key.

4. Implement the bean..

5. Create the bean deployment descriptor. The deployment descriptor specifies properties for the
bean through XML elements. This step is where you identify the data within the bean that is
to be managed by the container..

If the persistent data is saved to or restored from a database and you are not using the
defaults provided by the container, then you must ensure that the correct tables exist
for the bean. In the default scenario, the container creates the table and columns for
your data based on deployment descriptor and datasource information.

6. Create an EJB JAR file containing the bean, component interface, home interface, and the
deployment descriptors. Once created, configure the application.xml file, create an EAR
file, and deploy the EJB to OC4J.
102
FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are entity beans?


2. Define BMP
Section : B

1)Discuss the different types of Entity bean.

Section : C

1)What are the stpes involved to create a BMP?Explain.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 27 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Example program of BMP

103
The following sections demonstrate a simple CMP entity bean. This example continues the
use of the employee example, as in other chapters--without adding complexity.

 Home Interface
 Component Interfaces
 Entity Bean Class

1)create the BMP entity bean Home Interface

import java.util.collection;

import java.rmi.RemoteException;

import javax.ejb.*;

public interface useraccounthome extends EJBHome

public useraccount create(String id,String name)throws RemoteException,CreateException;

public useraccount findByPrimaryKey(String id)throws RemoteException,FinderException;

public Collection findByName(String name)throws RemoteException,FinderException;

2) create the BMP entity bean Remote Interface


import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface UserAccount extends EJBObject
{
public String getName() throws RemoteException;
public String getAddress() throws RemoteException;

3) create the BMP entity bean class


import java.sql.*;
import javax.sql.*;
import java.util.*;
import java.math.*;
import javax.ejb.*;
import javax.naming.*;

public class UserAccountBean implements EntityBean


{
private String id;
private String name;
private EntityContext context;
private Connection con;
private final static String dbName = "java:comp/env/jdbc/UserAccountDB";
public String getName()
{
return name;
}
public String ejbCreate(String id, String name) throws CreateException
{

104
try {
insertRow(id, name);
} catch (Exception ex)
{
throw new EJBException("ejbCreate: " + ex.getMessage());
}
this.id = id;
this.name = name;
return id;
}
public String ejbFindByPrimaryKey(String primaryKey) throws FinderException
{
boolean result;
try {
result = selectByPrimaryKey(primaryKey);
} catch (Exception ex)
{
throw new EJBException("ejbFindByPrimaryKey: " + ex.getMessage());
}
if (result)
{
return primaryKey;
}
else
{
throw new ObjectNotFoundException ("Row for id " + primaryKey + " not found.");
}
}
public Collection ejbFindByName(String name) throws FinderException
{
Collection result;
try {
result = selectByName(name);
} catch (Exception ex)
{
throw new EJBException("ejbFindByName " + ex.getMessage());
}
return result;
}
public void ejbRemove()
{
try {
deleteRow(id);
} catch (Exception ex)
{
throw new EJBException("ejbRemove: " + ex.getMessage());
}
}
public void setEntityContext(EntityContext context)
{
this.context = context;
}
public void unsetEntityContext() {}
public void ejbActivate()
{
id = (String) context.getPrimaryKey();
}
public void ejbPassivate()
{
id = null;
}
105
public void ejbLoad()
{
try {
loadRow();
} catch (Exception ex)
{
throw new EJBException("ejbLoad: " + ex.getMessage());
}
}
public void ejbStore()
{
try {
storeRow();
} catch (Exception ex)
{
throw new EJBException("ejbStore: " + ex.getMessage());
}
}
public void ejbPostCreate(String id, String name) {}
private void makeConnection()
{
try {
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup(dbName);
con = ds.getConnection();
} catch (Exception ex)
{
throw new EJBException("Unable to connect to database. " + ex.getMessage());
}
}
private void releaseConnection()
{
try {
con.close();
} catch (SQLException ex)
{
throw new EJBException("releaseConnection: " + ex.getMessage());
}
}
private void insertRow(String id, String name) throws SQLException
{
makeConnection();
String insertStatement = "insert into useraccount values ( ? , ? )";
PreparedStatement prepStmt = con.prepareStatement(insertStatement);
prepStmt.setString(1, id);
prepStmt.setString(2, name);
prepStmt.executeUpdate();
prepStmt.close();
releaseConnection();
}
private void deleteRow(String id) throws SQLException
{
makeConnection();
String deleteStatement = "delete from savingsaccount where id = ? ";
PreparedStatement prepStmt = con.prepareStatement(deleteStatement);
prepStmt.setString(1, id);
prepStmt.executeUpdate();
prepStmt.close();
releaseConnection();
}
106
private boolean selectByPrimaryKey(String primaryKey) throws SQLException
{
makeConnection();
String selectStatement = "select id " + "from useraccount where id = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, primaryKey);
ResultSet rs = prepStmt.executeQuery();
boolean result = rs.next();
prepStmt.close();
releaseConnection();
return result;
}
private Collection selectByName(String name) throws SQLException
{
makeConnection();
String selectStatement = "select id " + "from useraccount where name = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, name);
ResultSet rs = prepStmt.executeQuery();
ArrayList a = new ArrayList();
while (rs.next())
{
String id = rs.getString(1);
a.add(id);
}
prepStmt.close();
releaseConnection();
return a;
}
private void loadRow() throws SQLException
{
makeConnection();
String selectStatement = "select name " + "from useraccount where id = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, id);
ResultSet rs = prepStmt.executeQuery();
if (rs.next())
{
this.name = rs.getString(1);
prepStmt.close();
}
else
{
prepStmt.close();
throw new NoSuchEntityException("Row for id " + id + " not found in database.");
}
releaseConnection();
}
private void storeRow() throws SQLException
{
makeConnection();
String updateStatement = "update useraccount set name = ? ," + "address = ?, phoneno = ?" + "
where id = ?";
PreparedStatement prepStmt = con.prepareStatement(updateStatement);
prepStmt.setString(1, name);
int rowCount = prepStmt.executeUpdate();
prepStmt.close();
if (rowCount == 0)
{
107
throw new EJBException("Storing row for id " + id + " failed.");
}
releaseConnection();
}

4) create the BMP entity bean to store the user information in the database
import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class UserAccountServlet extends HttpServlet
{
int id = 129;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String name = null;
String address = null;
String phoneNo = null;
name = request.getParameter("name");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
try {
Context initial = new InitialContext();
Object objref = initial.lookup("SimpleUserAccount");
UserAccountHome home = (UserAccountHome)PortableRemoteObject.narrow(objref,
UserAccountHome.class);
id++;
UserAccount userAcc = home.create(id + "", name);
out.flush();
} catch (Exception ex)
{
out.println("Caught an exception." + "</BR>");
out.println(ex.toString());
}
}
}

5)Create the web client


<HTML>
<FORM ACTION = "http://localhost:8080/BMPAccountctx/servlet/UserAccountServlet">
<TABLE>
<TR> <TD> Name </TD> <TD> <INPUT TYPE = TEXT NAME= "name"> </TD>
</TR>
<TR> <TD> Address </TD> <TD> <INPUT TYPE = TEXT NAME= "address"> </TD>
</TR>
<TR> <TD> Contact No </TD> <TD> <INPUT TYPE = TEXT NAME= "phoneNo">
</TD> </TR>
<TR> <TD> <INPUT TYPE = SUBMIT VALUE= "SUBMIT"> </TD> </TR>
</TABLE>
</FORM>
</HTML>

108
FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are Component interfaces?


Section : B

1)Discuss the entity bean class.

Section : C

1)With an example, explain about BMP.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 28 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Difference between CMP and BMP

109
Bean Managed Persistence container managed persistence

1)A BMP developer will have the 1)For a CMP bean developer, there is no need to

responsibility of the transaction and worry about JDBC code and transactions, as all

all databases databases are automatically handled by the container.

2)A BMP either writes the data code in 2)The CMP uss EJB query language.

EJB or in DAO format.

3)BMP offers a tactical approach 3)CMP offers a more strategic approach

4)BMP provides the bean developer with 4)No

more flexibility in the how the bean reads and

writes its data.

5)In BMP, it is the developer who handles 5)On the contrary,it is the vendor who takes care of

everything. Everything in the CMP.

EJB Clients
An EJB bean as a client to another bean

EJB beans use exactly the same API as any other client when they access in EJB.

110
1)The home interface

The client bean is a stateless session bean, so it needs only a single create() method that takes
no arguments. Session beans of any kind cannot declare finder methods, so the home interface for this
bean is quite simple.

package book;

import javax.ejb.*;

public interface clienthome extends EJBHome

public client create() throws java.rmi.RemoteException,javax.ejb.CreateException;

2)The remote interface

The client performs all of its interactions with the remote EJB in the run method.

package book;

import javax.ejb.*;

import java.rmi.*;

public interface client extends EJBObject

void run() throws RemoteException;

3)The EJB client bean

package book;
111
import javax.ejb.*;

import javax.naming.*;

import java.util.*;

public class clientbean implements SessionBean

SessionContext cts;

public void ejbCreate()

{}

public void run()

try

Properties p=new Properties();

p.put(Context.INITIAL_CONTEXT_FACTORY,”weblogic.jndi.TengahInitialFactory”);

InitialContext ic=new InitialContext();

orderHome oh=(orderhome)ic.lookup(“orderhome”);

order o1=oh.create(1,”1”,1);

ol.remote();

}catch(Exception e){System.out.println(e);}

public void ejbRemove()

{}

public void ejbActivate()

{}

public void ejbPassivate()

{}

public void setSessionContext(SessionContext ctx)

this.ctx=ctx;

112
4)The client

import book;

import book.client;

import javax.naming.InitialContext;

public class clientclient

public static void main(String args[]) throws Exception

InitialContext ic=newInitialContext();

clienthome ch=(clienthome)ic.lookup(“clienthome”);

client c=ch.create();

c.run();

c.remove();

System.out.println(“client is done”);

5)Run the client

java –Djava.Naming.factory.initial=weblogic.jndi.T3InitialContextFactory clientclient

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are EJB clients?


Section : B

113
1)Distinguish between CMP and BMP

Section : C

1)Write a note on EJB Clients.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
114
Lecture Notes – (2017-18)
Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 29 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Handle
Handle is a serializable reference to a bean; that is; you can obtain a handle from a bean’s
remote interface, write it out to persistent storage and then close the program down.

Metadata:
Data about data is called metadata. In jdbc, two metadata classes are used.

1)Database metadata:which allows the client to query for information about the database and
sorts of operations that it supports.

2)Resultset metadata: which allows the client to dynamically discover metadata about a
resultset, such as the number of columns that it contains, the name and type of each column, and so
forth.

Deployment Descriptor class:


It is the base class used by both the sessiondescriptor and entitydescriptor classes. It provides
functionality that is common to all types of deployment descriptor.

1.sessiondescriptor class

It is to contain information about sessionbeans.It inherits from deployment


descriptor ; each provides all the functionality of a deployment descriptor.

public class javax.ejb.deployment.SessionDescriptor extends


javax.ejb.deployment.DeploymentDescriptor

public final static int STATEFUL_SESSION;

public final static int STATELESS_SESSION;

public sessionDescriptor();

public int getSessionTimeout();

public int getStateManagementType(int values);

115
The sessionDescriptor class extends the deploymentdescriptor class. As a result, it provides
all the functionality of a deploymentdescriptor. It declares two constants.
Ie)STATEFUL_SESSION,STATELESS_SESSION. The statemanagement type property uses these
constant to convey whether the bean is stateful or stateless. getSessionTimeout() returns the value of
SessionTimeout property. The int value represents the no of seconds that a session canbe inactive
before the container is allowed to destroy it.

ii)EntityDescriptor class

public class javax.ejb.deployment.EntityDescriptor extends


javax.ejb.deployment.DeploymentDescriptor {

public EntityDescriptor();

public field[] getContainerManagedFields();

public field getContainerManagedFields(int index);

public String getPrimaryKeyClassName();

public void setContainerManagedFields(field value[]);

public void setContainerManagedFields(int index,field value);

public void setPrimaryKeyClassName(String value);

It inherits from the deploymentdescriptor class. Line 4 returns an array of java.lang.reflect.field()


methods that indicate the container managedfields. A bean with bean-managed persistence should not
specify any container managed fields. Line 5 is an indexed property accessor for the array of container
managed fields. It returns the appropriate field object from the array of field object is the class
contains. Line returns a string representation of the name of the class used as the primery key.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define metadata?
2. What is deployment descriptor?APR 14
3. Define Handle.
Section : B

116
1)Write a note on entity descriptor class

2)Discuss the session descriptor class.

Section : C

1)Discuss the deployment descriptor

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

117
Lecture Notes – (2017-18)
Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 30 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Tips,Tricks and Traps for building distributed and other systems


It is basically a “brain dump” of useful and/orimportant issues in developing sytems.

1)Expect your network connection to fail

It does occur:

 cables are cut,chewed by rats,or otherwise damaged.


 routers die
 Ethernet cards go bad
 fuses blow.
 People trip over power cords and knock out servers
 Janitors plug their vacuum cleaners into the wrong outlets.

2)Test catastrophic failure

Start a transaction and then yank the network cable out. Pull out the power cord on your EJB
servers. These sorts of failures happen, and you should know in advance how your system will
behave.

1)Avoid remote method invocations where possible

2)treat transactions and database connections as precious resources

3)monitor the granularity of objects

4)monitor the granularity of methods

5)isolate ventor-specific code

6)avoid making entity beans re-entrant

3)Observer programming restrictions on EJB Beans

The EJB specification places several restrictions on beans

1)Beans are not allowed to start new threads,terminate threads, or use thread
synchronization primitives.
2)Beans cannot have read/write static fields
3)Only beans with the TX_BEAN-MANAGED transaction specifier are allowed to
interact directly with transaction manager, and then only through the
javax.jts.userTransaction interface.
4)A bean cannot change its java.security.Identity.
118
5)Only beans using the TX_NOT_SUPPORTED transaction specifier are allowed to
invoke JDBC commit() or rollback() method.
 Don’t implement the Bean’s remote interface in its implementation class
 use relatively small and awell-defined queries
 don’t keep database cursors open
 minimize transactions
 Minimize distributed transactions
 Avoid indexing your tables.
 Remember that memory is cheap
 Build in upward-scalability
 wrap entity beans with session beans
 streamline your middleware methods
 put your business logic in the middle tier.
 understand the tradeoffs between isolation level and concurrency.
 avoid extensive object allocation and deallocation
 prototype,prototype,prototype
 do load testing

7)Have your development environment mirror your production environment

4)Monitor the size of Your user base when designing an architecture

5)Separate transaction processing tables from reporting tables

 If a databse query runs slowly,review its query plan


 Keep joins simple

6)Have a database administrator

 Use preparedstatements
 During load testing, use a sniffer to monitor network traffic
 Use the façade pattern for interfacing with legacy systems
 Use patterns
 Keep network topology in mind
 Design security in from the start
 Work closely with network personal
 Be aware of the inernal politics
 Be aware of the organization culture
 Be prepared for requirement changes
 Build one slice at a time
 Build the difficult components first
 Talk to your users
 Keep it simple
 Conduct walkthrougs
 Use version control
 Use a code profiler
 Establish your interfaces early
 Build early and often
 Perform regression testing.
 Choose appropriate test cases
 Generate test cases while implementing the application
 Automate everything
119
 Understand the role of testing

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define Network
2. Define distributed system.
Section : B

1)What are the Observer programming restrictions on EJB Beans

2) Explain about Test catastrophic failure in detail.

Section : C

1)What are Tips,Tricks and Traps for building distributed and other systems?Explain in details.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
120
Lecture Notes – (2017-18)
Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 31 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Application Server
An application server is a server program in a computer in a distributed network that provides the
business logic for an application program. The application server is frequently viewed as part of a
three-tier application, consisting of a graphical user interface (GUI) server, an application (business
logic) server, and a database and transaction server. More descriptively, it can be viewed as dividing
an application into:

1. A first-tier, front-end, Web browser-based graphical user interface, usually at a personal


computer or workstation
2. A middle-tier business logic application or set of applications, possibly on a local area
network or intranet server
3. A third-tier, back-end, database and transaction server, sometimes on a mainframe or large
server

Older, legacy application databases and transaction management applications are part of the back end
or third tier. The application server is the middleman between browser-based front-ends and back-end
databases and legacy systems.

In many usages, the application server combines or works with a Web (Hypertext Transfer Protocol)
server and is called a Web application server. The Web browser supports an easy-to-create HTML-
based front-end for the user. The Web server provides several different ways to forward a request to
121
an application server and to forward back a modified or new Web page to the user. These approaches
include the Common Gateway Interface (CGI), FastCGI, Microsoft's Active Server Page, and the Java
Server Page. In some cases, the Web application servers also support request "brokering" interfaces
such as CORBA Internet Inter-ORB Protocol (IIOP).

Web Server

A Web server is a program that uses HTTP (Hypertext Transfer Protocol) to serve the files that form
Web pages to users, in response to their requests, which are forwarded by their computers' HTTP
clients. Dedicated computers and appliances may be referred to as Web servers as well.

The process is an example of the client/server model. All computers that host Web sites must have
Web server programs.

Web servers often come as part of a larger package of Internet- and intranet-related programs for
serving email, downloading requests for File Transfer Protocol (FTP) files, and building and
publishing Web pages. Considerations in choosing a Web server include how well it works with the
operating system and other servers, its ability to handle server-side programming, security
characteristics, and  the particular publishing, search engine and site building tools that come with it.

Difference between application server and web server

 Web Server is designed to serve HTTP Content. App Server can also serve HTTP Content but
is not limited to just HTTP. It can be provided other protocol support such as RMI/RPC
 Web Server is mostly designed to serve static content, though most Web Servers have plugins
to support scripting languages like Perl, PHP, ASP, JSP etc. through which these servers can
generate dynamic HTTP content.
 Most of the application servers have Web Server as integral part of them, that means App
Server can do whatever Web Server is capable of. Additionally App Server have components
and features to support Application level services such as Connection Pooling, Object
Pooling, Transaction Support, Messaging services etc.
 As web servers are well suited for static content and app servers for dynamic content, most of
the production environments have web server acting as reverse proxy to app server. That
means while servicing a page request, static contents (such as images/Static HTML) are
served by web server that interprets the request. Using some kind of filtering technique
(mostly extension of requested resource) web server identifies dynamic content request and
transparently forwards to app server

FAQ( As in Question Bank) 10 Minutes

Section : A
122
1. Write a note on application server
2. Define web server.
Section : B

1)Discuss the importance of a web server.

2)Differentiate between application server and web server

Section : C

1)Write a note on application server

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
123
Lecture Notes – (2017-18)
Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 32 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Perl

Perl is a programming language developed by Larry Wall, especially designed for text
processing. Though Perl is not officially an acronym but many times it is used as it stands for
Practical Extraction and Report Language. It runs on a variety of platforms, such as
Windows, Mac OS, and the various versions of UNIX.

Perl Features

 Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC,
among others.
 Perls database integration interface DBI supports third-party databases including
Oracle, Sybase, Postgres, MySQL and others.
 Perl works with HTML, XML, and other mark-up languages.
 Perl supports Unicode.
 Perl is Y2K compliant.
 Perl supports both procedural and object-oriented programming.
 Perl interfaces with external C/C++ libraries through XS or SWIG.
 Perl is extensible. There are over 20,000 third party modules available from the
Comprehensive Perl Archive Network.
 The Perl interpreter can be embedded into other systems

Perl data types

so known as associative arrays. Here is a little detail about these data types.

S.N. Types and Description


1)Scalar −

Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a
number, a string, or a reference. A reference is actually an address of a variable, which
we will see in the upcoming chapters.
2)Arrays −

Arrays are ordered lists of scalars that you access with a numeric index which starts
with 0. They are preceded by an "at" sign (@).
3)Hashes −

Hashes are unordered sets of key/value pairs that you access using the keys as
subscripts. They are preceded by a percent sign (%)

124
4.Handles

Perl provides where the data will come from called a handle. If scalars,hashes and array
are perl’s data, then handles are perl’s method of getting that data. It provides two types
of handles.

1)file handle-you can use file handles to have perl read/write to files,but you can also
them read/wrie to sockets.

2)directory handle-the dirhandle method provide an alternative interface to the


opendir(),closeddir() and rewinddir() function.

First Perl Program

You can use Perl interpreter with -e option at command line, which lets you execute Perl
statements from the command line. Let's try something at $ prompt as follows −

$perl -e 'print "Hello World\n"'

This execution will produce the following result −

Hello, world

Numeric Literals

Perl stores all the numbers internally as either signed integers or double-precision floating-
point values. Numeric literals are specified in any of the following floating-point or integer
formats −

Type Value
Integer 1234
Negative integer -100
Floating point 2000
Scientific notation 16.12E14
Hexadecimal 0xffff
Octal 0577

String Literals

Strings are sequences of characters. They are usually alphanumeric values delimited by either
single (') or double (") quotes. They work much like UNIX shell quotes where you can use
single quoted strings and double quoted strings.

Double-quoted string literals allow variable interpolation, and single-quoted strings are not.
There are certain characters when they are proceeded by a back slash, have special meaning
and they are used to represent like newline (\n) or tab (\t).

125
You can embed newlines or any of the following Escape sequences directly in your double
quoted strings −

Escape sequence Meaning


\\ Backslash
\' Single quote
\" Double quote
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\0nn Creates Octal formatted numbers
\xnn Creates Hexideciamal formatted numbers
\cX Controls characters, x may be any character
\u Forces next character to uppercase
\l Forces next character to lowercase
\U Forces all following characters to uppercase
\L Forces all following characters to lowercase
\Q Backslash all following non-alphanumeric characters
\E End \U, \L, or \Q

Example

Let's see again how strings behave with single quotation and double quotation. Here we will
use string escapes mentioned in the above table and will make use of the scalar variable to
assign string values.

#!/usr/bin/perl

# This is case of interpolation.


$str = "Welcome to \ntutorialspoint.com!";
print "$str\n";

# This is case of non-interpolation.


$str = 'Welcome to \ntutorialspoint.com!';
print "$str\n";

# Only W will become upper case.


$str = "\uwelcome to tutorialspoint.com!";
print "$str\n";

# Whole line will become capital.


$str = "\UWelcome to tutorialspoint.com!";
print "$str\n";

# A portion of line will become capital.


$str = "Welcome to \Ututorialspoint\E.com!";
print "$str\n";

# Backsalash non alpha-numeric including spaces.


126
$str = "\QWelcome to tutorialspoint's family";
print "$str\n";

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define perl
2. What are handles?
3. What are hashes?
4. What are arrays?
Section : B

1)Write different escape sequences used by perl programming.

2)Discuss the feature of perl.

Section : C

1)Explain the following 1)String literals 2)Numeric Literals

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

127
Lecture Notes – (2017-18)
Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 33 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Control Structures

1)Conditional statements

Perl conditional statements helps in the decision making, which require that the programmer
specifies one or more conditions to be evaluated or tested by the program, along with a
statement or statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be false.

Following is the general from of a typical decision making structure found in most of the
programming languages

a)simple if statement

A Perl if statement consists of a boolean expression followed by one or more statements.

Syntax

The syntax of an if statement in Perl programming language is −

if(boolean_expression){
# statement(s) will execute if the given condition is true
128
}

If the boolean expression evaluates to true then the block of code inside the if statement will
be executed. If boolean expression evaluates to false then the first set of code after the end of
the if statement(after the closing curly brace) will be executed.

#!/usr/local/bin/perl

$a = 10;
# check the boolean condition using if statement
if( $a < 20 ){
# if condition is true then print the following
printf "a is less than 20\n";
}
print "value of a is : $a\n";

$a = "";
# check the boolean condition using if statement
if( $a ){
# if condition is true then print the following
printf "a has a true value\n";
}
print "value of a is : $a\n";

b)if.. else statement

A Perl if statement can be followed by an optional else statement, which executes when the
boolean expression is false.

Syntax

The syntax of an if...else statement in Perl programming language is −

if(boolean_expression){
# statement(s) will execute if the given condition is true
}else{
# statement(s) will execute if the given condition is false
}

If the boolean expression evaluates to true, then the if block of code will be executed
otherwise else block of code will be executed.

c)Nested if statement

An if statement can be followed by an optional elsif...else statement, which is very useful to


test the various conditions using single if...elsif statement.

When using if , elsif , else statements there are few points to keep in mind.

 An if can have zero or one else's and it must come after any elsif's.

 An if can have zero to many elsif's and they must come before the else.

129
 Once an elsif succeeds, none of the remaining elsif's or else's will be tested.

if(boolean_expression 1){
# Executes when the boolean expression 1 is true
}
elsif( boolean_expression 2){
# Executes when the boolean expression 2 is true
}
elsif( boolean_expression 3){
# Executes when the boolean expression 3 is true
}
else{
# Executes when the none of the above condition is true
}

Example
#!/usr/local/bin/perl

$a = 100;
# check the boolean condition using if statement
if( $a == 20 ){
# if condition is true then print the following
printf "a has a value which is 20\n";
}elsif( $a == 30 ){
# if condition is true then print the following
printf "a has a value which is 30\n";
}else{
# if none of the above conditions is true
printf "a has a value which is $a\n";
}

d)unless statement

A Perl unless statement consists of a boolean expression followed by one or more statements.

Syntax

The syntax of an unless statement in Perl programming language is −

unless(boolean_expression){
# statement(s) will execute if the given condition is false
}

If the boolean expression evaluates to false, then the block of code inside the unless statement
will be executed. If boolean expression evaluates to true then the first set of code after the
end of the unless statement (after the closing curly brace) will be executed.

e)Switch statement

A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.

130
A switch case implementation is dependent on Switch module and Switch module has been
implemented using Filter::Util::Call and Text::Balanced and requires both these modules to
be installed.

Syntax

The synopsis for a switch statement in Perl programming language is as follows −

use Switch;

switch(argument){
case 1 { print "number 1" }
case "a" { print "string a" }
case [1..10,42] { print "number in list" }
case (\@array) { print "number in list" }
case /\w+/ { print "pattern" }
case qr/\w+/ { print "pattern" }
case (\%hash) { print "entry in hash" }
case (\&sub) { print "arg to subroutine" }
else { print "previous case not true" }
}

f)Conditional statement

The ? : Operator

The conditional operator ? : which can be used to replace if...else statements. It has the
following general form −

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2
is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is
evaluated and its value becomes the value of the expression.

Example

#!/usr/local/bin/perl

$name = "Ali";
$age = 10;

$status = ($age > 60 )? "A senior citizen" : "Not a senior citizen";

print "$name is - $status\n";

2)Looping statements

here may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.

131
Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

a)while loop

A while loop statement in Perl programming language repeatedly executes a target statement
as long as a given condition is true.

Syntax

The syntax of a while loop in Perl programming language is −

while(condition)
{
statement(s);
}

Here statement(s) may be a single statement or a block of statements. The condition may be
any expression. The loop iterates while the condition is true. When the condition becomes
false, program control passes to the line immediately following the loop.

#!/usr/local/bin/perl

$a = 10;

# while loop execution


while( $a < 20 ){
printf "Value of a: $a\n";
$a = $a + 1;
}

132
b)until loop

An until loop statement in Perl programming language repeatedly executes a target statement
as long as a given condition is false.

Syntax

The syntax of an until loop in Perl programming language is −

until(condition)
{
statement(s);
}

Here statement(s) may be a single statement or a block of statements. The condition may be
any expression. The loop iterates until the condition becomes true. When the condition
becomes true, the program control passes to the line immediately following the loop.

#!/usr/local/bin/perl

$a = 5;

# until loop execution


until( $a > 10 ){
printf "Value of a: $a\n";
$a = $a + 1;
}

c)for loop

A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.

Syntax

The syntax of a for loop in Perl programming language is −

for ( init; condition; increment ){


statement(s);
}

Here is the flow of control in a for loop −

 The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.

 Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for loop.

 After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
 #!/usr/local/bin/perl
133

 # for loop execution
 for( $a = 10; $a < 20; $a = $a + 1 ){
 print "value of a: $a\n";
 }

d)do..while loop

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.

Syntax

The syntax of a do...while loop in Perl is −

do
{
statement(s);
}while( condition );

It should be noted that the conditional expression appears at the end of the loop, so the
statement(s) in the loop executes once before the condition is tested. If the condition is true,
the flow of control jumps back up to do, and the statement(s) in the loop executes again. This
process repeats until the given condition becomes false.

#!/usr/local/bin/perl

$a = 10;

# do...while loop execution


do{
printf "Value of a: $a\n";
$a = $a + 1;
}while( $a < 20 );

e)foreach loop

he foreach loop iterates over a list value and sets the control variable (var) to be each element
of the list in turn −

Syntax

The syntax of a foreach loop in Perl programming language is −

foreach var (list) {


...
}
#!/usr/local/bin/perl

@list = (2, 20, 30, 40, 50);

# foreach loop execution


foreach $a (@list){
print "value of a: $a\n";
}
134
FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are control stantements?


2. Write the general syntax of if statement.
Section : B

1)Write a perl program to find the factorial value of a given number

2)Discuss 1)while statement 2)do while statement.

3)With an example, explain about nested if statements.

Section : C

1)Explain about conditional statements in perl.

2)Discuss various looping statement in detail.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203

135
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 34 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Perl operators:

Perl operators are

 Arithmetic Operators
 Equality Operators
 Logical Operators
 Assignment Operators
 Bitwise Operators
 Logical Operators

 Quote-like Operators

Perl Arithmetic Operators

Assume variable $a holds 10 and variable $b holds 20 then −

Operator Description Example


Addition - Adds values on either side of the
+ $a + $b will give 30
operator
Subtraction - Subtracts right hand operand from
- $a - $b will give -10
left hand operand
Multiplication - Multiplies values on either side
* $a * $b will give 200
of the operator
Division - Divides left hand operand by right
/ $b / $a will give 2
hand operand
Modulus - Divides left hand operand by right
% $b % $a will give 0
hand operand and returns remainder
Exponent - Performs exponential (power) $a**$b will give 10 to the
**
calculation on operators power 20

Perl Equality Operators

These are also called relational operators. Assume variable $a holds 10 and variable $b holds
20 then, lets check the following numeric equality operators −

Operator Description Example


== Checks if the value of two operands are equal or ($a == $b) is not true.
136
not, if yes then condition becomes true.
Checks if the value of two operands are equal or
!= not, if values are not equal then condition ($a != $b) is true.
becomes true.
Checks if the value of two operands are equal or
not, and returns -1, 0, or 1 depending on whether
<=> ($a <=> $b) returns -1.
the left argument is numerically less than, equal
to, or greater than the right argument.
Checks if the value of left operand is greater
> than the value of right operand, if yes then ($a > $b) is not true.
condition becomes true.
Checks if the value of left operand is less than
< the value of right operand, if yes then condition ($a < $b) is true.
becomes true.
Checks if the value of left operand is greater
>= than or equal to the value of right operand, if yes ($a >= $b) is not true.
then condition becomes true.
Checks if the value of left operand is less than or
<= equal to the value of right operand, if yes then ($a <= $b) is true.
condition becomes true.

Perl Assignment Operators

Assume variable $a holds 10 and variable $b holds 20, then −

[ Show Example ]

Operator Description Example


Simple assignment operator, Assigns values from $c = $a + $b will assigned
=
right side operands to left side operand value of $a + $b into $c
Add AND assignment operator, It adds right
$c += $a is equivalent to $c =
+= operand to the left operand and assign the result to
$c + $a
left operand
Subtract AND assignment operator, It subtracts
$c -= $a is equivalent to $c = $c
-= right operand from the left operand and assign the
- $a
result to left operand
Multiply AND assignment operator, It multiplies
$c *= $a is equivalent to $c =
*= right operand with the left operand and assign the
$c * $a
result to left operand
Divide AND assignment operator, It divides left
$c /= $a is equivalent to $c = $c
/= operand with the right operand and assign the
/ $a
result to left operand
Modulus AND assignment operator, It takes
$c %= $a is equivalent to $c =
%= modulus using two operands and assign the result
$c % a
to left operand
Exponent AND assignment operator, Performs
$c **= $a is equivalent to $c =
**= exponential (power) calculation on operators and
$c ** $a
assign value to the left operand

Perl Bitwise Operators

Bitwise operator works on bits and perform bit by bit operation. Assume if $a = 60; and $b =
13; Now in binary format they will be as follows −

137
$a = 0011 1100

$b = 0000 1101

-----------------

$a&$b = 0000 1100

$a|$b = 0011 1101

$a^$b = 0011 0001

~$a  = 1100 0011

There are following Bitwise operators supported by Perl language

[ Show Example ]

Operator Description Example


Binary AND Operator copies a bit to the result if
($a & $b) will give 12 which is
&
it exists in both operands. 0000 1100
Binary OR Operator copies a bit if it exists in($a | $b) will give 61 which is
|
eather operand. 0011 1101
Binary XOR Operator copies the bit if it is set in
($a ^ $b) will give 49 which is
^
one operand but not both. 0011 0001
(~$a ) will give -61 which is
Binary Ones Complement Operator is unary and 1100 0011 in 2's complement
~
has the efect of 'flipping' bits. form due to a signed binary
number.
Binary Left Shift Operator. The left operands
$a << 2 will give 240 which is
<< value is moved left by the number of bits
1111 0000
specified by the right operand.
Binary Right Shift Operator. The left operands
$a >> 2 will give 15 which is
>> value is moved right by the number of bits
0000 1111
specified by the right operand.

Perl Logical Operators

There are following logical operators supported by Perl language. Assume variable $a holds
true and variable $b holds false then −

[ Show Example ]

Operator Description Example


Called Logical AND operator. If both the
and operands are true then then condition becomes ($a and $b) is false.
true.
C-style Logical AND operator copies a bit to the
&& ($a && $b) is false.
result if it exists in both operands.
Called Logical OR Operator. If any of the two
Or operands are non zero then then condition ($a or $b) is true.
becomes true.
C-style Logical OR operator copies a bit if it
|| ($a || $b) is true.
exists in eather operand.
138
Called Logical NOT Operator. Use to reverses the
not logical state of its operand. If a condition is true not($a and $b) is true.
then Logical NOT operator will make false.

Quote-like Operators

There are following Quote-like operators supported by Perl language. In the following table,
a {} represents any pair of delimiters you choose.

Operator Description Example


q{ } Encloses a string with-in single quotes q{abcd} gives 'abcd'
qq{ } Encloses a string with-in double quotes qq{abcd} gives "abcd"
qx{ } Encloses a string with-in invert quotes qx{abcd} gives `abcd`

Function

A Perl subroutine or function is a group of statements that together performs a task. You can
divide up your code into separate subroutines. How you divide up your code among different
subroutines is up to you, but logically the division usually is so each function performs a
specific task.

Define and Call a Subroutine

The general form of a subroutine definition in Perl programming language is as follows −

sub subroutine_name{
body of the subroutine
}

The typical way of calling that Perl subroutine is as follows −

subroutine_name( list of arguments );

Let's have a look into the following example, which defines a simple function and then call it.
Because Perl compiles your program before executing it, it doesn't matter where you declare
your subroutine.

#!/usr/bin/perl

# Function definition
sub Hello{
print "Hello, World!\n";
}

# Function call
Hello();

When above program is executed, it produces the following result −

Hello, World!

139
Passing Arguments to a Subroutine

You can pass various arguments to a subroutine like you do in any other programming
language and they can be acessed inside the function using the special array @_. Thus the
first argument to the function is in $_[0], the second is in $_[1], and so on.

You can pass arrays and hashes as arguments like any scalar but passing more than one array
or hash normally causes them to lose their separate identities. So we will use references
( explained in the next chapter ) to pass any array or hash.

Let's try the following example, which takes a list of numbers and then prints their average −

#!/usr/bin/perl

# Function definition
sub Average{
# get total number of arguments passed.
$n = scalar(@_);
$sum = 0;

foreach $item (@_){


$sum += $item;
}
$average = $sum / $n;

print "Average for the given numbers : $average\n";


}

# Function call
Average(10, 20, 30);

When above program is executed, it produces the following result −

Average for the given numbers : 20

Scope

A scope is simply an area within which a variable is usable and visible. Perl’s rules
for scoping are simple. It works on areas in the code called blocks. There are two types of
blocks

1) A special block called a global block, which is the entire perl file.
2) Each () in an if (condition) {}, while {} or do{} and any other conditional loop
defines a block. Any use of brackets where you can insert code,(any place
beside brackets that make hashes) defines a block, and not just subroutine
calls.

Blocks can be nested or internal to other blocks, and generally are completely
wrangle-able.

Examples

1)while(1)

{
140
}

2)if(@array<5){

If(@array>2)

…………..

3)subroutine block:

sub subname

my @s=@-1;

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are the importance of operators?


2. Define subroutine
3. What is scope?
4. What are nested subroutines?
Section : B

1)With an example, explain about scope

2)Discuss the different operators used by perl.

141
Section : C

1)Explain subroutine with an example

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016


142
Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 35 / 45

ic (Lecture Notes Per Hour) 40 Minutes

REMOTE METHOD INVOCATION(RMI)

Remote Method Invocation (RMI) facilitates object function calls between Java Virtual
Machines (JVMs). JVMs can be located on separate computers - yet one JVM can invoke
methods belonging to an object stored in another JVM. Methods can even pass objects that a
foreign virtual machine has never encountered before, allowing dynamic loading of new
classes as required.

Consider the follow scenario :

 Developer A writes a service that performs some useful function. He regularly


updates this service, adding new features and improving existing ones.
 Developer B wishes to use the service provided by Developer A. However, it's
inconvenient for A to supply B with an update every time.

Java RMI provides a very easy solution! Since RMI can dynamically load new classes,
Developer B can let RMI handle updates automatically for him. Developer A places the new
classes in a web directory, where RMI can fetch the new updates as they are required.

Figure 1 - Connections made when client uses RMI

Figure 1 shows the connections made by the client when using RMI. Firstly, the client must
contact an RMI registry, and request the name of the service. Developer B won't know the
exact location of the RMI service, but he knows enough to contact Developer A's registry.
This will point him in the direction of the service he wants to call..

Developer A's service changes regularly, so Developer B doesn't have a copy of the class.
Not to worry, because the client automatically fetches the new subclass from a webserver
where the two developers share classes. The new class is loaded into memory, and the client
is ready to use the new class. This happens transparently for Developer B - no extra code
need to be written to fetch the class.

Architecture:

143
The RMI application consists of the following components

1)client

2)server

3)registry

Client:

A client application gets a reference to a remote server objects from the registry and
then invoke methods on this remote objects.

Server:

The server creates some java objects, registers them with the naming service and waits for
remote clients to invoke methods on these objects.

Registry:

It is the naming service. The RMI components usually run on separate networked
computers.

RMI technology is useful for many business application written in java

1)getting stock market price quotes

2)obtaining flight information

3)requesting and downloading music files

4)performing inventory maintanence.

Advantages of RMI

1)Handles threads
144
2)handles sockets

3)marshals objects

4)dynamic loading of classes

5)can also make changes on the server end, that might not mean you need to change anything
on the client side.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define RMI
2. What are the applications of RMI?
3.
Section : B

1)What are the advantages of RMI?Explain.

Section : C

1)Discuss the architecture of RMI.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

145
Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 36 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Creating an RMI application:

The following steps are used to create an RMI application.

1)declaring remote interface

The remote interface describe the behaviour of the remote object and do not contain
the behaviour . The client program will “have a feeling” that it calls method. But actually
these calls will be redirected to a remote server.

2)Implementing remote interface

In RMI, the interface and implementation are completely separated. While the remote
interfaces just declares the methods used by the client, the actual class that provides the
implementation .

These methods must have actually the same signatures as their proxies on the client,
otherwise the rmi clients won’t find them.

3)Creating stub and skeleton

After the remote interface and its implementation are created, you need to generate
the objects responsible for the network communication between them.

Stub:

The stub is a client side object that represents the remote object. It does the following

 Intiate a connection with the remote JVM


 Marshals(prepares and transmits) the parameters to the server
 Waits for the result of the method invocation.
 Unmarshals(read) the return value of exception returned.
 Returns the value to the client.

Skeleton:

The skeleton is a server side object that process the client’s network calls. It performs
the following operations for each received cell.

 Unmarshals(read) the parameters for the remote method


 Invoke the method on the actual remote-object implementation
 Marshals the result to the caller.

The following step is used to create a stub and skeleton

D:/jdk1.4/bin/rmic impl;

146
Where

rmic is the method method invocation compiler

impl is the implementing the interface program.

4)Registering remote object

Before a client program can invoke a particular method on the remote object, it has to
find this object on the network. A server makes remote object visible to the client by
registering these objects with a naming service.

The rmiregistry is a simple naming service. The process of registering an object with
rmiregistry is called binding.

D:/jdk1.4/bin/start rmiregistry

5)Writing RMI client

The client has to perform a lookup in the registry on the server machine and obtain a
remote reference to the object listed under the specified name. The lookup method of
java.rmi.naming class located the remote object on the specified host and port.

intf i=(intf)Naming.lookup(impl)

where

intf is the remote interface program

impl is the implementing the remote interface program

6)pushing data from the RMI server

The RMI client has to register itself with the server, and it also has to implement and
interface that contains the code refreshing the screen.

Periodically the RMI server will call the method that refreshes the screen on each
registered client. In other word, instead of the client pulling the data from the server, the
server is pushing data to the client.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define stub
2. Define skeleton.
3. What is remote interface?
Section : B

1)Write a note on stub

2)Discuss the following 1)RMI client 2)RMI server.

147
3)Write a note on skeleton.

Section : C

1) ). Write the ways in which a RMI program is developed

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

148
Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 37 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Example program:Simple Interest

1)Creating remote interface

import java.rmi.*;

public interface intf extends Remote

double si(int p,int n,double r) throws RemoteException;

2)Implementing the remote interface

import java.rmi.*;

import java.rmi.server.*;

public class impl extends RemoteCastObject implements intf

public impl() throws RemoteException;

{}

public double si(int p,int n,double r)

return ((p*n*r)/100);

3)Creating server program

import java.net.*;

import java.rmi.*;

public class server

149
{

public static void main(String args[])

try

impl i=new impl();

Naming.rebind(“server”,i);

}catch(Exception e){System.out.println(e);}

4)Creating client program

import java.io.*;

import java.rmi.*;

public class client

public static void main(String args[]) throws IOException

try

String s1=”rmi://”+args[0]+”/server”;

intf i=(intf)Naming.lookup(s1);

DataInputStream d=new DataInputStream(System.in);

System.out.println(“Enter the value of P,N,R”);

int p=Integer.parseInt(d.readLine());

int n=Integer.parseInt(d.readLine());

Double r=Integer.parseDouble(d.readLine());

System.out.println(“The simple interest is “+i.si(p,n,r));

}catch(Exception e){System.out.println(e);}
150
}

5)Compile all four programs(intf,impl,server and client)

D:/jdk1.4/bin/javac intf.java

D:/jdk1.4/bin/javac impl.java

D:/jdk1.4/bin/javac server.java

D:/jdk1.4/bin/javac client.java

6)Create stub and skeleton

D:/jdk1.4/bin/rmic impl

7)start the rmiregistry

D:/jdk1.4/bin/start rmiregistry

8)run the server program

D:/jdk1.4/bin/java server

9)Run the client program

D:/jdk1.4/bin/java client 127.0.0.1

RMI over Inter-ORB Protocol(IIOP)

The RMI technology uses the Java Remote Method Protocol(JRMP) ,which can be
used for communications between java programs only. On the other hand,CORBA
technology can be used in distributed applications whose components are written in different
languages,but CORBA uses the Inter-ORB Protocol. It allows write java client programs that
are communicating with non-java objects. RMI-IIOP supports both JRMP and IIOP
Protocols.

CORBA uses the interface definition language (IDL) to define objects, and the RMI
compiler supports mapping between Java and IDL objects. The –iiop flag causes rmic to
generate stub and ties (CORBA specific delegation mechanism) for remote objects using
IIOP protocol, rather than stub and skeleton

Some other differences in the development of RMI-IIOP applications(as opposed to


CORBA applications) are listed here.

The server implementation class must extend the javax.rmi.PortableRemoteObject


class.

The JNDI includes the tnameserv.exe program, which is used as a naming service.

151
RMI and RMI-IIOP protocols are also implemented in the enterprise javabeans
containers.

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define corba
2. Write a note on IIOP
Section : B

1)What are the importance of IIOP?Explain.

Section : C

1)Write a RMI program to find the simple interest.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)

152
Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 38 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Introduction to JSP

JSP technology is a text based documents that describes how to process a request to create a
response. JSP is java based technology that simplifies the process of developing dynamic
web sites, It also mix together regular,static and dynamic html.

JSP enables us to write HTML pages containing tags that run powerful Java programs. JSP
separates presentation and business logic as Web designer can design and update JSP
pages without learning the Java language and Java Developer can also write code without
concerning the web design.

JSP are text files with the extension filename.jsp, which take the place of additional html
pages.

In the end a JSP becomes a Servlet

JSP pages are converted into Servlet by the Web Container. The Container translates a JSP
page into servlet class source(.java) file and then compiles into a Java Servlet class.

Advantage of JSP

 JSP programming is easy to learn and easy to implement for Non-Java


programmers also.
 JSP programming environment provides the separation between presentation
logic and business logic.
 JSP programming environment provides parallel development of web
applications.
 JSP programming has implicit objects.
153
 JSP programming eliminates the repeated deployment
 JSP provides optional mechanism in configuring web application file
(web.xml).
 JSP environment provides implicit/global exception handling mechanism.
 JSP programming provides and additional concept called Custom Tags
Development.
 JSP programming environment provides page compilation automatically.

Lifecycle of JSP

A JSP page is converted into Servlet in order to service requests. The translation of a JSP
page to a Servlet is called Lifecycle of JSP. JSP Lifecycle consists of following steps.

1. Translation of JSP to Servlet code.


2. Compilation of Servlet to bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method

Web Container translates JSP code into a servlet class source(.java) file, then compiles that
into a java servlet class. In the third step, the servlet class bytecode is loaded using
classloader. The Container then creates an instance of that servlet class.

The initialized servlet can now service request. For each request the Web Container call the
_jspService() method. When the Container removes the servlet instance from service, it calls
the jspDestroy() method to perform any required clean up.
154
First JSP program

What happens to a JSP when it is translated into Servlet

Let's see what really happens to JSP code when it is translated into Servlet

<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>

The above JSP page becomes this Servlet

public class hello_jsp extends HttpServlet


{
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");
out.write("<html><body>");
int count=0;
out.write("Page count is:");
out.print(++count);
out.write("</body></html>");

}
}

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define JSP.
Section : B

1)What are the advantages of JSP?Explain

2)Discuss the life cycle of JSP.

Section : C

1) What happens to a JSP when it is translated into Servlet

Discussion 05 Minutes

155
Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 39 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Day 43

JSP Variables
 
If you familiar with other programming language, java too has data type variable to identify
what data to belongs. This variable stores information of data, and differentiate with others.
E.g.
String, int, byte, long, float, double, boolean

Declare a variable
Declaration of variable in JSP is storing information of data. We need to define data’s type
what is this. It may be a string, may be a int (integer), or float

156
1. String variable Example in JSP
jspString.jsp
 

<%@ page language="java" errorPage="" %>


<%
String stVariable="this is defining String variable";
%>

<html>
<body>
String variable having value : <%=stVariable%>
</body>
</html>

2. Int variable Example in JSP

int can only having numeric values e.g 1,2,3,5

jspInt.jsp
 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>


<%
int iVariable=5;
%>

<html>
<body>
int variable having value : <%=iVariable%>
</body>
</html>

3. Long variable is same as int variable just long can store more bytes than int.

4. float variable Example in JSP

float variable can be having decimal numbers. E.g 5.6 ,23.455

jspFloat.jsp
 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>


<%
float fVariable=567.345f;
%>

<html>
<body>
float variable having value : <%=fVariable%>
</body>
</html>

157
When you work on float variable don’t forget to add f character float fVariable=567.345f,
otherwise it will get error of “Type mismatch: cannot convert from double to float”

5. double variable Example in JSP


This is same as float variable; it can store more bytes than float variable. In double we don’t
need to put f character

6. Boolean variable Example in JSP

This is useful when we need to check condition. Let’s check in example

jspBoolean.jsp
 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>


<%
boolean checkCondition=false;
%>

<html>
<body>
<%
if(checkCondition==true)
{
out.print("This condition is true");
}
else
{
out.print("This condition is false");
}
%>
</body>
</html>

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define variable
2. List any four data types supported by JSP.
Section : B

1)Write a JSP program to display hello world

Section : C

1)Write a jsp program to find the factorial value of a given no.

Discussion 05 Minutes

158
Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 40 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Components of a JSP page

A JSP page contains jsp elements,fixed template data or combination of the two. JSP
elements are instructions to the jsp container about what code to generate and how to show
operate.

There are three types of JSP elements.

JSP Scripting Element

JSP Scripting element are written inside <% %> tags. These code inside <% %> tags are
processed by the JSP engine during translation of the JSP page. Any other text in the JSP
page is considered as HTML code or plain text.

159
Example:

<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body

There are five different types of scripting elements

Scripting Element Example


Comment <%-- comment --%>
Directive <%@ directive %>
Declaration <%! declarations %>
Scriptlet <% scriplets %>
Expression <%= expression %>

JSP Comment

JSP Comment is used when you are creating a JSP page and want to put in comments about
what you are doing. JSP comments are only seen in the JSP page. These comments are not
included in servlet source code during translation phase, nor they appear in the HTTP
response. Syntax of JSP comment is as follow

<%-- JSP comment --%>

Simple Example of JSP Comment

<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
<%-- Code to show page count --%>
Page Count is <% out.println(++count); %>
</body

Scriptlet Tag

Scriptlet Tag allows you to write java code inside JSP page. Syntax of Scriptlet Tag is as
follows :

<% java code %>

160
Example of Scriptlet

In this example, we will show number of page visit.

<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>

Example of JSP Scriptlet Tag

In this example, we will create a simple JSP page which retrieves the name of the user from
the request parameter. The index.html page will get the username from the user.

index.html

<form method="post" action="welcome.jsp">


Name <input type="text" name="user" >
<input type="submit" value="submit">
</form>

welcome.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome Page</title>
</head>
<%
String user = request.getParameter("user");
%>

<body>
Hello, <% out.println(user); %>
</body>
</html>
%>

Example of Declaration Tag

<html>
<head>
<title>My First JSP Page</title>
</head>
<%!
int count = 0;

161
%>
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>

The above JSP page becomes this Servlet

public class hello_jsp extends HttpServlet


{
int count=0;
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");
out.write("<html><body>");

out.write("Page count is:");


out.print(++count);
out.write("</body></html>");
}
}

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are JSP comments?


2. What are scripting elements?
Section : B

1)Explain various scripting elements with example.

Section : C

1)What are the components of JSP Programming?Explain.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

162
Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 41 / 45

ic (Lecture Notes Per Hour) 40 Minutes

2)JSP Directive Tag

Directive Tag gives special instruction to Web Container at the time of page translation.
Directive tags are of three types: page, include and taglib.

Directive Description
defines page dependent properties such as language, session, errorPage
<%@ page ... %>
etc.
<%@ include ...
defines file to be included.
%>
<%@ taglib ... %> declares tag library used in the page

We'll discuss about include and taglib directive later. You can place page directive anywhere
in the JSP file, but it is good practice to make it as the first statement of the JSP page.

163
The Page directive defines a number of page dependent properties which communicates with
the Web Container at the time of translation.

 import attribute
 language attribute
 extends attribute
 session attribute
 isThreadSafe attribute
 isErrorPage attribute
 errorPage attribute
 contentType attribute
 autoFlush attribute
 buffer attribute

import attribute

The import attribute defines the set of classes and packages that must be inported in servlet
class definition. For example

<%@ page import="java.util.Date" %>


or
<%@ page import="java.util.Date,java.net.*" %>

language attribute

language attribute defines scripting language to be used in the page.

extends attribute

extends attribute defines the class name of the superclass of the servlet class that is generated
from the JSP page.

session attribute

session attribute defines whether the JSP page is participating in an HTTP session. The value
is either true or false.

isThreadSafe attribute

isThreadSafe attribute declares whether the JSP is thread-safe.The value is either true or false

isErrorPage attribute

164
isErrorPage attribute declares whether the current JSP Page represents another JSP's error
page.

errorPage attribute

errorPage attribute indicates another JSP page that will handle all the run time exceptions
thrown by current JSP page.

contentType attribute

contentType attribute defines the MIME type for the JSP response.

autoFlush attribute

autoFlush attribute defines whether the buffered output is flushed automatically. The default
value is "true".

buffer attribute

buffer attribute defines how buffering is handled by the implicit out object.

Expression Tag

Expression Tag is used to print out java language expression that is put between the tags. An
expression tag can hold any java language expression that can be used as an argument to the
out.print() method. Syntax of Expression Tag

<%= JavaExpression %>

When the Container sees this

<%= (2*5) %>

It turns it into this:

out.print((2*5));

Example of Expression Tag

<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
165
<body>
Page Count is <%= ++count %>
</body>
</html>

Include Directive

The include directive tells the Web Container to copy everything in the included file and
paste it into current JSP file. Syntax of include directive.

<%@ include file="filename.jsp" %>

Example of include directive

welcome.jsp

<html>
<head>
<title>Welcome Page</title>
</head>

<body>
<%@ include file="header.jsp" %>
Welcome, User
</body>
</html>

header.jsp

<html>
<body>
<img src="header.jpg" alt="This is Header image" / >
</body>
</html>

Taglib Directive

The taglib directive is used to define tag library that the current JSP page uses. A JSP page
might include several tag library. We will look into it in more details in Custom Tag section.
Syntax of taglib directive:

166
<%@ taglib prefix="prefixOfTag" uri="uriOfTagLibrary" %>

The prefix is used to distinguish the custom tag from other libary custom tag. Prefix is
prepended to the custom tag name. Every custom tag must have a prefix.

The URI is the unique name for Tag Library.

Example of Taglib Directive

In this example, we are using a tag userName. To use this tag we must specify some
information to the Web Container using Taglib Directive.

<html>
<head>
<title>Welcome Page</title>
</head>
<%@ taglib prefix="mine" uri="myTags" %>
<body>
Welcome, <mine:userName / >
</body>
</html>
FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are Expression tags?


2. Define taglib directory.
Section : B

1)Discuss the JSP directive tags with example.

2)Explian taglib directives with an example.

Section : C

1)Explain the JSP include directives with example.

Discussion 05 Minutes

167
Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 4 2 / 45

ic (Lecture Notes Per Hour) 40 Minutes

3)JSP Action tags

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You
can dynamically insert a file, reuse JavaBeans components, forward the user to another page,
or generate HTML for the Java plugin.

There is only one syntax for the Action element, as it conforms to the XML standard:

<jsp:action_name attribute="value" />

Action elements are basically predefined functions and there are following JSP actions
available:

Syntax Purpose
jsp:include Includes a file at the time the page is requested
jsp:useBean Finds or instantiates a JavaBean
jsp:setProperty Sets the property of a JavaBean
jsp:getProperty Inserts the property of a JavaBean into the output
jsp:forward Forwards the requester to a new page
Generates browser-specific code that makes an OBJECT or
jsp:plugin
EMBED tag for the Java plugin
jsp:element Defines XML elements dynamically.
jsp:attribute Defines dynamically defined XML element's attribute.
jsp:body Defines dynamically defined XML element's body.
jsp:text Use to write template text in JSP pages and documents.

168
The <jsp:include> Action

This action lets you insert files into the page being generated. The syntax looks like this:

<jsp:include page="relative URL" flush="true" />

Unlike the include directive, which inserts the file at the time the JSP page is translated into a
servlet, this action inserts the file at the time the page is requested.

Following is the list of attributes associated with include action:

Attribute Description

Page The relative URL of the page to be included.

The boolean attribute determines whether the included resource


Flush
has its buffer flushed before it is included.

Example:

Let us define following two files (a)date.jsp and (b) main.jsp as follows:

Following is the content of date.jsp file:

<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>

Here is the content of main.jsp file:

<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page="date.jsp" flush="true" />
</center>
</body>
</html>

Now let us keep all these files in root directory and try to access main.jsp. This would display
result something like this:

The include action Example

Today's date: 12-Sep-2010 14:54:22

169
The <jsp:useBean> Action

The useBean action is quite versatile. It first searches for an existing object utilizing the id
and scope variables. If an object is not found, it then tries to create the specified object.

The simplest way to load a bean is as follows:

<jsp:useBean id="name" class="package.class" />

Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to
modify and retrieve bean properties.

Following is the list of attributes associated with useBean action:

Attribute Description

Class Designates the full package name of the bean.

Type Specifies the type of the variable that will refer to the object.

Gives the name of the bean as specified by the instantiate ()


beanName
method of the java.beans.Beans class.

Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid
example related to these actions.

The <jsp:setProperty> Action

The setProperty action sets the properties of a Bean. The Bean must have been previously
defined before this action. There are two basic ways to use the setProperty action:

You can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:

<jsp:useBean id="myName" ... />


...
<jsp:setProperty name="myName" property="someProperty" .../>

In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated
or an existing bean was found.

A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean
element, as below:

<jsp:useBean id="myName" ... >


...
<jsp:setProperty name="myName" property="someProperty" .../>
</jsp:useBean>

Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing
one was found.

Following is the list of attributes associated with setProperty action:

Attribute Description

170
Designates the bean whose property will be set. The Bean must
Name
have been previously defined.

Indicates the property you want to set. A value of "*" means that
property all request parameters whose names match bean property names
will be passed to the appropriate setter methods.

The value that is to be assigned to the given property. The the


Value parameter's value is null, or the parameter does not exist, the
setProperty action is ignored.

The param attribute is the name of the request parameter whose


Param value the property is to receive. You can't use both value and
param, but it is permissible to use neither.

The <jsp:getProperty> Action

The getProperty action is used to retrieve the value of a given property and converts it to a
string, and finally inserts it into the output.

The getProperty action has only two attributes, both of which are required ans simple syntax
is as follows:

<jsp:useBean id="myName" ... />


...
<jsp:getProperty name="myName" property="someProperty" .../>

Following is the list of required attributes associated with setProperty action:

Attribute Description

The name of the Bean that has a property to be retrieved. The


Name
Bean must have been previously defined.

The property attribute is the name of the Bean property to be


Property
retrieved.

Example:

Let us define a test bean which we will use in our example:

/* File: TestBean.java */
package action;

public class TestBean {


private String message = "No message specified";

public String getMessage() {


return(message);
}
public void setMessage(String message) {
this.message = message;
}

171
}

Compile above code to generated TestBean.class file and make sure that you copied
TestBean.class in C:\apache-toMCA/MSC(CS&CST)t-7.0.2\webapps\WEB-
INF\classes\action folder and CLASSPATH variable should also be set to this folder:

Now use the following code in main.jsp file which loads the bean and sets/gets a simple
String parameter:

<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>

<jsp:useBean id="test" class="action.TestBean" />

<jsp:setProperty name="test"
property="message"
value="Hello JSP..." />

<p>Got message....</p>

<jsp:getProperty name="test" property="message" />

</center>
</body>
</html>

Now try to access main.jsp, it would display following result:

Using JavaBeans in JSP

Got message....

Hello JSP...

The <jsp:forward> Action

The forward action terminates the action of the current page and forwards the request to
another resource such as a static page, another JSP page, or a Java Servlet.

The simple syntax of this action is as follows:

<jsp:forward page="Relative URL" />

Following is the list of required attributes associated with forward action:

Attribute Description

page Should consist of a relative URL of another resource such as a


172
static page, another JSP page, or a Java Servlet.

Example:

Let us reuse following two files (a) date.jsp and (b) main.jsp as follows:

Following is the content of date.jsp file:

<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>

Here is the content of main.jsp file:

<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:forward page="date.jsp" />
</center>
</body>
</html>

Now let us keep all these files in root directory and try to access main.jsp. This would display
result something like as below. Here it discarded content from main page and displayed
content from forwarded page only.

Today's date: 12-Sep-2010 14:54:22

The <jsp:plugin> Action

The plugin action is used to insert Java components into a JSP page. It determines the type of
browser and inserts the <object> or <embed> tags as needed.

If the needed plugin is not present, it downloads the plugin and then executes the Java
component. The Java component can be either an Applet or a JavaBean.

The plugin action has several attributes that correspond to common HTML tags used to
format Java components. The <param> element can also be used to send parameters to the
Applet or Bean.

Following is the typical syntax of using plugin action:

<jsp:plugin type="applet" codebase="dirname" code="MyApplet.class"


width="60" height="80">
<jsp:param name="fontcolor" value="red" />
<jsp:param name="background" value="black" />

<jsp:fallback>
Unable to initialize Java Plugin
173
</jsp:fallback>

</jsp:plugin>

You can try this action using some applet if you are interested. A new element, the
<fallback> element, can be used to specify an error string to be sent to the user in case the
component fails.

The <jsp:element> Action

The <jsp:attribute> Action

The <jsp:body> Action

The <jsp:element>, lt;jsp:attribute> and <jsp:body> actions are used to define XML elements
dynamically. The word dynamically is important, because it means that the XML elements
can be generated at request time rather than statically at compile time.

Following is a simple example to define XML elements dynamically:

<%@page language="java" contentType="text/html"%>


<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page">

<head><title>Generate XML Element</title></head>


<body>
<jsp:element name="xmlElement">
<jsp:attribute name="xmlElementAttr">
Value for the attribute
</jsp:attribute>
<jsp:body>
Body for XML element
</jsp:body>
</jsp:element>
</body>
</html>

This would produce following HTML code at run time:

<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page">

<head><title>Generate XML Element</title></head>


<body>
<xmlElement xmlElementAttr="Value for the attribute">
Body for XML element
</xmlElement>
</body>
</html>

The <jsp:text> Action

The <jsp:text> action can be used to write template text in JSP pages and documents.
Following is the simple syntax for this action:

174
<jsp:text>Template data</jsp:text>

The body fo the template cannot contain other elements; it can only contain text and EL
expressions ( Note: EL expressions are explained in subsequent chapter). Note that in XML
files, you cannot use expressions such as ${whatever > 0}, because the greater than signs are
illegal. Instead, use the gt form, such as ${whatever gt 0} or an alternative is to embed the
value in a CDATA section.

<jsp:text><![CDATA[<br>]]></jsp:text>

If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use
the <jsp:text> element as follows:

<jsp:text><![CDATA[<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">]]>
</jsp:text>
<head><title>jsp:text action</title></head>
<body>

<books><book><jsp:text>
Welcome to JSP Programming
</jsp:text></book></books>

</body>
</html>

175
FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are JSP action tags?


2. Define<jsp: useBean> action tag.
3. Define <jsp:plugin> action tag.
Section : B

1)With an example, explain about include action tags

2)With an example, explain about useBean action tags.

Section : C

1)Explain about JSP action jags with example.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

176
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 43 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Implicit Objects in JSP

JSP provide access to some implicit object which represent some commonly used objects for
servlets that JSP page developers might need to use. For example you can retrieve HTML
form parameter data by using request variable, which represent the HttpServletRequest
object.

Following are the JSP implicit object

Implicit
Description
Object
request The HttpServletRequest object associated with the request.
The HttpServletRequest object associated with the response that is sent
response
back to the browser.
out The JspWriter object associated with the output stream of the response.
177
The HttpSession object associated with the session for the given user of
session
request.
application The ServletContext object for the web application.
config The ServletConfig object associated with the servlet for current JSP page.
The PageContext object that encapsulates the enviroment of a single request
pageContext
for this current JSP page
The page variable is equivalent to this variable of Java programming
page
language.
The exception object represents the Throwable object that was thrown by
exception
some other JSP page.

Exception Handling

Exception Handling is a process of handling exceptional condition that might occur in your
application. Exception Handling in JSP is much easier than Java Technology exception
handling. Although JSP Technology also uses the same exception class object.

It is quite obvious that you dont want to show error stack trace to the guy surfing your
website. You can't prevent all errors in your application but you can atleast give an user
friendlier error response page.

Ways to perform exception handling in JSP

JSP provide two different way to perform exception handling.

1. Using isErrorPage and errorPage attribute of page directive.


2. Using <error-page> tag in Deployment Descriptor.

Example of isErrorPage and errorPage attribute

isErrorPage attribute in page directive officially appoint a JSP page as an error page.

error.jsp

178
errorPage attribute in page directive tells the Web Container that if an exception occur in
this page, forward the request to an error page.

sum.jsp

Declaring error page in Deployment Descriptor

You can also declare error pages in the DD for the entire Web Apllication.Using <error-
page> tag in Deployment Descriptor you can even configure different error pages for
different exception types, or HTTP error code type(400,500 etc.).

Declaring an error page for all type of exception

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>

179
Declaring an error page for more detailed exception

<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/error.jsp</location>
</error-page>

Declaring an error page based on HTTP Status code

<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>

FAQ( As in Question Bank) 10 Minutes

Section : A

1. What are implicit objects?


2. What are exceptions?
Section : B

1)Explain various implicit objects used by JSP.

Section : C

1)With an example, explain about exception handling mechanisms in jsp.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

180
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 44 / 45

ic (Lecture Notes Per Hour) 40 Minutes

JavaMail
The JavaMail API provides a platform-independent and protocol-independent framework to build
mail and messaging applications. The JavaMail API provides a set of abstract classes defining objects
that comprise a mail system. It is an optional package (standard extension) for reading, composing,
and sending electronic messages.

JavaMail API

The JavaMail API provides a platform-independent and protocol-independent framework to


build mail and messaging applications. The JavaMail API provides a set of abstract classes
defining objects that comprise a mail system. It is an optional package (standard extension)
for reading, composing, and sending electronic messages.

JavaMail provides elements that are used to construct an interface to a messaging system,
including system components and interfaces. While this specification does not define any
specific implementation, JavaMail does include several classes that implement RFC822 and
MIME Internet messaging standards.

Architecture

As said above the java application uses JavaMail API to compose, send and receive
emails.The following figure illustrates the architecture of JavaMail:

181
The abstract mechanism of JavaMail API is similar to other J2EE APIs, such as JDBC, JNDI,
and JMS. As seen the architecture diagram above, JavaMail API is divided into two main
parts:

 An application-independent part: An application-programming interface (API) is used


by the application components to send and receive mail messages, independent of the
underlying provider or protocol used.

 A service-dependent part: A service provider interface (SPI) speaks the protocol-


specific languages, such as SMTP, POP, IMAP, and Network News Transfer Protocol
(NNTP). It is used to plug in a provider of an e-mail service to the J2EE platform.

Generating a HelloWorld e-mail:

package com.tutorialspoint;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class CheckingMails {

public static void check(String host, String storeType, String user,


String password)
{

182
try {

//create properties field


Properties properties = new Properties();

properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);

//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");

store.connect(host, user, password);

//create the folder object and open it


Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);

// retrieve the messages from the folder in an array and print it


Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);

for (int i = 0, n = messages.length; i < n; i++) {


Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());

//close the store and folder objects


emailFolder.close(false);
store.close();

} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

String host = "pop.gmail.com";// change accordingly


String mailStoreType = "pop3";
String username = "[email protected]";// change accordingly
String password = "*****";// change accordingly

check(host, mailStoreType, username, password);

}
JavaMail Protocols:

The protocols that underpin the workings of electronic mail are well established are
very mature.

1)Simple Mail Transport Protocol(SMTP):

183
It was designed for the delivery of mail services to servers. SMTP is merely a
delivery agent and is not used to read email.SMTP can act as a relay server by delivering
email on behalf of another server.

2)Post Office Protocol(pop3)


The post office protocol is the mechanism by which the majority of people collect
their email. It is then the responsibility of the user to take care of the email by filling it in
some logical storage. Such as with a mailbox at a real post office, a user come along and
collect or downloads, his or her email, storing it locally and removing it from the server.

3)Internet message access protocol:


IMAP is a protocol that many enterprise email servers employ. IMAP offers a
folder structure for the user to interact with and all messages are stored on the server. The
user has no need to download email to his or her local machine. This setup has major
advantage, fro the user, of keeping all of his or her emails in one place, irrespective of the
client that user to log in with.

4)Multipurpose Internet Main Extension:


MIME defines the translation of and all the rules that are associated with the
transmission of binary-based email. Internet mail is fundamentally based on the American
standard code for information interchange(ASCII) text, and on the whole does not permit non
ASCII data to be used. In such a way (ASCII), they could be transported and, when
received,decoded back out to their nature binary representations.

JavaMail components:
The javamail API is a collection of about one hundred classes and interfaces. It
contains four major components.

 Session Management: The session aspect of the API defines the interaction the
mail clients with the network. It handles all aspects associated with the overall
communication, including the protocol to use for transfer and any default
values that may be required.
It provides two different classes.
1.javax.mail.section-defines the mail session used for communicating
with remote mail systems.
2java.util.properties-It is to allow for the different session parameters
to be placed in.

2)Message manipulation: JavaMail is to send and receive mail messages.

It provides different classes.

1.javax.mail.message-The javamail API offers a rich library of classes to make the


construction and deconstruction of mail messages.

2)javax.mail.internet.mimemessage- the message class is an abstract class and


therefore to actually start to use a mail message you must use a subclassed implementation.

3)Mail storage and retrieval:

1.javax.mail.store-Messages are organized into folders and these folders are held
within a single store. A store must be default have atleast one folder in which messages can

184
reside. This requirement allows the javamail API to provide a uniform access methods across
all the different protocols.

It provides different classes.

1.javax.mail.URLName-used to access mail storage.

2)javax.mail.folder-can contain additional folder, thus providing a directory-like


structure to the message archieve.

4)Transportation:

Javamail API is the class responsibility for the delivery of messages


javax.mail.transport.

You will be using the SMTP protocol for delivery. As a convenience, the transport
class offers the following static method for sending message.

Tansport.send(msg);

FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define javamail
2. Define SMTP
3. Define MIME.
4. List the components of javamail.
Section : B

1)What are the components of JavaMail?Explain

2)Write a simple program to implement JavaMail.

Section : C

1)What are the protocols supported by JavaMail?Explain.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

185
Note:
Lecture Notes Minimum 2 Pages

SRM ARTS AND SCIENCE COLLEGE


SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)

Lecture Notes – (2017-18)


Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45

Semester : ODD Year : 2016

Subject Name : Advanced Java Subject Code :

Faculty Name : V. S. Padmavathy Session : 45 / 45

ic (Lecture Notes Per Hour) 40 Minutes

Java Messaging Service

JMS is to enable java applications to communicate with messaging oriented middleware


infrastructure. JMS is a messaging agent that delivers messages between J2EE application
and components.

JMS consists of five elements. These are a providers,clients,messages,administered


objects and native clients. A provider is the messaging agent that is responsible for messaging
the messaging service that use the provider for communication. Messages are objects
transmitted between clients. Administered objects are JMS object used in transmission.

Components of JMS program


186
The six elements of JMS are destinations,connections,connection factories,sessions,message
producers,message consumers.

1)Destinations:

A destination is somewhere you are sending a message. Specific types of destinations


are queues(point-to-point systems or topics(publish/subscribe systems). Destinations are
normally configured in the messaging server and are not directly instantiated in the
application. You can obtain them via a JNDI lookup/ Queues and topics are also be created
dynamically, but queues and topics so created are only valid for the lifetime of the
connections, with which they are assicated.

2)Connections

JMS connections are similar to the connection class in JDBC. It represents a


connection between the application and the messaging server which messages can be sent.
The connection interface javax.jms.connection.

3)Connection factories

As in JDBC, connections in JMS are not directly instantiated. Instead, a connection


factory creates connections. Connection factories and destinations are they only types of
objects in JMS that need to be obtained via JNDI. Connection factories don’t do anything else
other than create connection objects. The connection factory interface is
javax.jms.connectionfactory.

4)sessions

A session serves as a factory for the message objects,message producers and


consumers. TemporaryTopics and TemporaryQueues. It also does the following.

 Provides transactional behaviour for the work done by its producers and
consumers.
 Defines a serial order for the message, it consumes and the messages it
produces.
 Retains messages it consumes until they have been acknowledged.

5)Producers:

Finally, having created a number of administrative objects (a connectionfactory, a


connection , a session and a destination. The javax.jms.Message-Producer interface has sub
interfaces: QueueSender and TopicPublisher. You can use whichever interface you like but
the QueueServer and MessageProducers.

6)Consumers:

If you want to receive messages, use the session to create a MessageConsumer. The
interface javax.jms.MessageConsumer has two sub-interfaces. QueueReceiver and
TophicSubcriber. Messages can be received two ways with a MessageConsumer.

First, with the push approach, you can create a class that implements the Message Listener
interface and pass an instance of it to MessageConsumer.setMessage.Listener[]. Whenever a

187
message becomes available if will be automatically passed to the listener’s onMessage()
method.

Second, with the pull approach, you call MessageConsumer.receive(), which will return a
message if one is available. If no message is available the no-argument version of receiver()
will block. You can also call receive(int), which will timeout after the specified number of
milliseconds, or reeiveNoWait(), which will return null if message is available.

Types of JMS

Point-To-Point Messaging

In the point-to-point domain, message producers are called senders and consumers are called
receivers. They exchange messages by means of a destination called a queue: senders
produce messages to a queue; receivers consume messages from a queue. What
distinguishes point-to-point messaging is that a message can be consumed by only one
consumer.

Figure 2–1 shows the simplest messaging operation in the point-to-point domain.


MyQueueSender sends Msg1 to the queue destination MyQueue1. Then, MyQueueReceiver
obtains the message from MyQueue1.

Figure 2–1 Simple Point-to-Point Messaging

Figure 2–2 shows a more complex picture of point-to-point messaging to illustrate the


possibilities offered by this domain. Two senders, MyQSender1 and MyQSender2, use the
same connection to send messages to MyQueue1. MyQSender3 uses an additional connection
to send messages to MyQueue1. On the receiving side, MyQReceiver1 consumes messages
from MyQueue1, and MyQReceiver2 and MyQReceiver3, share a connection in order to
consume messages from MyQueue1.

188
Figure 2–2 Complex Point-to-Point Messaging

This more complex picture exemplifies a number of additional points about point-to-point
messaging.

 More than one sender can produce and send messages to a queue. Senders can share a
connection or use different connections, but they can all access the same queue.

 More than one receiver can consume messages from a queue, but each message can
be consumed by only one receiver. Thus Msg1, Msg2, and Msg3 are consumed by
different receivers. (This is a Message Queue extension.)

 Receivers can share a connection or use different connections, but they can all access
the same queue. (This is a Message Queue extension.)

 Senders and receivers have no timing dependencies: the receiver can consume a
message whether or not it was running when the sender produced and sent the
message.

 Messages are placed in a queue in the order they are produced, but the order in which
they are consumed depends on factors such as message expiration date, message
priority, whether a selector is used in consuming messages, and the releative message
processing rate of the consumers.

 Senders and receivers can be added and deleted dynamically at runtime, thus allowing
the messaging system to expand or contract as needed.

The point-to-point domain offers a number of advantages:

 Messages destined for a queue are always retained, even if there are no receivers.

 Java clients can use a queue browser object to inspect the contents of a queue. They
can then consume messages based on the information gained from this inspection.
That is, although the consumption model is normally FIFO (first in, first out),
receivers can consume messages that are not at the head of the queue by using
189
message selectors. Administrative clients can also use the queue browser to monitor
the contents of a queue.

 The fact that multiple receivers can consume messages from the same queue allows
you to use load-balancing to scale message consumption if the order in which
messages are received is not important.

Publish/Subscribe Messaging

In the publish/subscribe domain, message producers are called publishers and message
consumers are called subscribers. They exchange messages by means of a destination called
a topic: publishers produce messages to a topic; subscribers subscribe to a topic and
consume messages from a topic.

Figure 2–3 shows a simple messaging operation in the publish/subscribe domain.


MyTopicPublisher publishes Msg1 to the destination MyTopic. Then, MyTopicSubscriber1
and MyTopicSubscriber2 each receive a copy of Msg1 from MyTopic.

Figure 2–3 Simple Publish/Subscribe Messaging

While the publish/subscribe model does not require that there be more than one subscriber,
two subscribers are shown in the figure to emphasize the fact that this domain allows you to
broadcast messages. All subscribers to a topic get a copy of any message published to that
topic.

Subscribers can be durable or non-durable. If a durable subscriber becomes inactive, the


broker retains messages for it until the subscriber becomes active and consumes the
messages. If a non-durable subscriber becomes inactive, the broker does not retain messages
for it.

Figure 2–4 shows a more complex picture of publish/subscribe messaging to illustrate the


possibilities offered by this domain. Several producers publish messages to the Topic1
destination. Several subscribers consume messages from the Topic1 destination. Unless, a
subscriber is using a selector to filter messages, each subscriber gets all the messages
published to the topic to which it is subscribed. In Figure 2–4, MyTSubscriber2 has filtered

190
out Msg2.Figure 2–4 Complex Publish/Subscribe Messaging

This more complex picture exemplifies a number of additional points about publish/subscribe
messaging.

 More than one publisher can publish messages to a topic. Publishers can share a
connection or use different connections, but they can all access the same topic.

 More than one subscriber can consume messages from a topic. Subscribers consume
all messages published to a topic unless they use selectors to filter out messages or the
messages expire before they are consumed.

 Subscribers can share a connection or use different connections, but they can all
access the same topic.

 For durable subscribers, the broker retains messages for the subscribers while these
subscribers are inactive.

 Messages are placed in a topic in the order they are produced, but the order in which
they are consumed depends on factors such as message expiration date, message
priority, and whether a selector is used in consuming messages.

 Publishers and subscribers have a timing dependency: a topic subscriber can consume
only messages published after the subscriber has subscribed to the topic.

 Publishers and subscribers can be added and deleted dynamically at runtime, thus
allowing the messaging system to expand or contract as needed.

The main advantage of the publish/subscribe model is that it allows messages to be broadcast
to multiple subscribers.

191
FAQ( As in Question Bank) 10 Minutes

Section : A

1. Define JMS
2. List out the various types of JMS
Section : B

1)What are the components of JMS.

Section : C

1)What are the various types of JMS?Explain in details.

Discussion 05 Minutes

Signature of the Faculty Signature of the HOD

Note:
Lecture Notes Minimum 2 Pages

192

You might also like