Adv Java Notes For College
Adv Java Notes For College
Session : 1 / 45
Servlets
Definition:
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:
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.
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
Section : C
Discussion 05 Minutes
4
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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.
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.
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.
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.
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();
}
}
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
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
7
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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:
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());
}
}
Section : A
Section : B
Section : C
1)How to connect two different servlet program with the help of Servlet Chaining mechanism?Explain.
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
10
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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.
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
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
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
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();
}
}
13
ServletInputStream object is normally retrieved via the ServletRequest.getInputStream()
method.
Constructor:
protected ServletInputStream()
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
Methods
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.
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
Section : B
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
15
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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.
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
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
Disadvantage of Cookies
Cookie class
Cookie(String name, String value) constructs a cookie with a specified name and value.
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.
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);}
}
}
Section : A
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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.
A web server can send a hidden HTML form field along with a unique session ID as follows:
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.
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.
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:
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:
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.
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.
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
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
24
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
1)HTTP Authentication:
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.
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:
String codebase=””+getCodeBase();
String servlet=getParameter(“servlet”);
if(servlet!=null){
if(servlet.startsWith(“/”)&&codebase.endsWith(“/”)){
codebase=codebase.substring(0,codebase.length()-1);
{
26
}
Section : A
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
27
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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 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 −
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.
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.
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.
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
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Using the statement object’s executeQuery() method,information can be retrieved from the
database.
ResultSet rs=st.executeQuery(“select * from emp”);
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
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
34
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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.
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.
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.*;
out.println(df.format(date));
}
}
36
FAQ( As in Question Bank) 10 Minutes
Section : A
1. Define SSI.
Section : B
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
37
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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:
There are different types of form controls that you can use to collect data using HTML form:
Checkboxes Controls
38
Hidden Controls
Clickable Buttons
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.
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>
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>
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
<!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 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>
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>
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
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 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
<!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>
Section : A
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
43
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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();
}
}
Section : A
1. What is Tunneling?
2. What is the role of servlet in J2EE?APR 14
Section : B
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
46
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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.
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.
The components and containers of the JavaBeans component model are similar in many ways
to the Component and Container classes of the AWT.
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 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.
48
Interface Methods and Properties
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.
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.
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.
Section : A
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
50
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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.
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
3)moleculebean
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.
5)standard mechanisms are used to save the state of a bean. This information can later be retrieved.
Section : A
1. Define BDK
2. List any four types of JavaBean.
Section : B
Section : C
Discussion 05 Minutes
53
Note:
Lecture Notes Minimum 2 Pages
Developing beans
Creating a spectrum bean
package spectrum;
import java.awt.*;
54
{
public spectrum()
vertical=true;
setsize(100,100);
return vertical;
this.vertical=vertical;
repaint();
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);
Z:/spectrum/edit spectrum.mft
Type
Name:spectrum\spectrum.class
Java-Bean:True
Z:/bdk1.4/beanbox/run
Section : A
Section : C
1)List out the steps involved to create a simple bean with a simple program
Discussion 05 Minutes
56
Note:
Lecture Notes Minimum 2 Pages
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.
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
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.
Example program
package serial;
import java.awt.*;
import java.io.*;
import java.util.*;
{
58
public static void main(String args[])
rry
v.add(add Integer(-7);
v.addElement(new Rectangle(20,20,100,50));
v.addElement(“Hello”);
System.out.println(v);
oos.writeObject(v);
oos.flush();
oos.close();
}catch(Exception e){System.out.println(e);
java serial.save1
[-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.
2.1 ObjectoutputStream
It provides methods to serialize objects,arrays and simple types to an output stream. The methods
are
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.
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.*;
try {
Object obj=ois.readObject();
fis.close();
60
System.out.println(obj);
}catch(Exception e){System.out.println(e);}
[-7 java.awt.rectangle[x=20,y=20,width=100,height=100,Hello]
Section : A
Section : C
Discussion 05 Minutes
61
Note:
Lecture Notes Minimum 2 Pages
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
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
return IBMS.GetInfoBus();
63
}
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.
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.
Section : A
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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
Method
3)PropertyVhangeSupport
It can be used to perform much of the work associated with bound properties.
Method
Example
1)start the bdk and create an instance of the circle,square and triangle beans
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.
import java.beans.*;
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
Section : B
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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 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.
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
Options are
c-create an archieve
Section : A
Section : C
1)List out the steps involved to create a simple bean with a simple program
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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.
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
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.
Methods are
3)FeatureDescriptor
1)BeanDescriptor
Methods
2)EventSetDescriptor
Methods
3)MethodDescriptor
Methods
71
1)method getMethod()-returns a method object for the associated 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.
Methods
Methods:
package spectrum;
import java.beans.*;
import java.awt.event.*;
import java.lang.reflect.*;
try
class cls=spectrum.class;
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.
It is defined in the java.beans package. It specifies the three methods show below.
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.*;
…………
Javabeans API
73
The javabeans functionality is provided by a set of classes and interfaces in the
java.beans package.
Section : A
Section : C
Discussion 05 Minutes
74
Signature of the Faculty Signature of the HOD
Note:
Lecture Notes Minimum 2 Pages
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.
Applications of EJB
2)banking application
Advantages of EJB
2)portability
3)interface/implementation separation
5)cross platform
EJB’S role:
EJB specification describes container. The container provides services such support
for transactions, support for persistence and management of multiple instances of a given
bean.
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.
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.
Section : A
Section : C
Discussion 05 Minutes
77
Signature of the Faculty Signature of the HOD
Note:
Lecture Notes Minimum 2 Pages
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.
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.
Section : A
Section : C
Discussion 05 Minutes
80
Signature of the Faculty Signature of the HOD
Note:
Lecture Notes Minimum 2 Pages
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.*;
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.*;
package book;
import javax.ejb.*;
SessionContext cts;
{}
82
public void ejbRemote()
{}
{}
{}
this.ctx=ctx;
import javax.ejb.deployment.*;
import java.io.*;
import javax.util.properties;
sd.setEnterpriseBeanClassName(“Hello”);
sd.setHomeInterfaceClassName(“HelloHome”);
sd.setRemoteInterfaceClassName(“HelloRemote”);
p.put(“myprop1”,”myval”);
sd.setEnvironmentProperties(p);
sd.setSessionTimeout(0);
sd.setStateManagementType(SessionDescriptor,STATELESS_SESSION);
83
try
Oos.writeObject(sd);
oos.close();
}catch(Exception e){System.out.println(e);}
A manifest file is a text document that contains information about the contents of a jar file.
Name:HelloBeanDD.ser
Enterprise-Bean:True
Use the jar program that comes with the java JDK to generate your 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.*;
{
84
try
HelloHome home=(HelloHome)ic.lookup(“HelloHome”);
Hello hel=home.create();
System.out.println(“returned:”+retval);
hel.remove();
}catch(Exception e){System.out.println(e);}
java –Djava.Naming.factory.initial=weblogic.jndi.T3InitialContextFactory
HelloClient
Section : A
1)Explain the following with example 1)Remote Interface 2)Home Interface 3)Bean implementation
class
Section : C
Discussion 05 Minutes
85
Signature of the Faculty Signature of the HOD
Note:
Lecture Notes Minimum 2 Pages
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.
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
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.
Listing 1 shows the code for the remote business interface, SimpleSession.java.
87
Listing 1. SimpleSession.java
package beans;
import javax.ejb.Remote;
@Remote
Listing 2 shows the code for the actual bean implementation, SimpleSessionBean.java.
Listing 2. SimpleSessionBean.java
package beans;
import javax.ejb.Stateless;
@Stateless
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;
88
public static void main(String[] args) throws Exception
SimpleSession simpleSession
= (SimpleSession) ctx.lookup(SimpleSession.class.getName());
After you've created and organized the sample session bean files as just described, follow
these steps to compile the application:
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.
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:
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.
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:
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:
It may not seem very practical, but it makes you unbelievably popular at parties.
Section : A
Section : C
Discussion 05 Minutes
91
Signature of the Faculty Signature of the HOD
Note:
Lecture Notes Minimum 2 Pages
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
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.
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, on the other hand, a rollback occurs while the bean is in the “method ready in transaction”
state, beforecompletion() is not invoked.
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
Listing 5. CalculatorBean.java
package beans;
import javax.ejb.Stateful;
@Stateful
_value = 0;
if (operation.equals("+")) {
return;
if (operation.equals("-")) {
94
return;
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):
Next, within the SimpleCalculatorApp directory where the client and beans directories are located,
execute the following commands from the command prompt:
Then copy the resulting EJB3 file to your JBoss deployment directory:
%JBOSS_HOME%\server\all\deploy.
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:
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
Section : A
Section : C
Discussion 05 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.
97
Isolated - Each transaction executes independent of any other transaction.
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.
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.
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
- 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.
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.
- 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:
- 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.
Section : A
Section : C
Discussion 05 Minutes
100
Signature of the Faculty Signature of the HOD
Note:
Lecture Notes Minimum 2 Pages
101
Types of Entity Beans
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.
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.
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
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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
import java.util.collection;
import java.rmi.RemoteException;
import javax.ejb.*;
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());
}
}
}
108
FAQ( As in Question Bank) 10 Minutes
Section : A
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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
2)A BMP either writes the data code in 2)The CMP uss EJB query language.
5)In BMP, it is the developer who handles 5)On the contrary,it is the vendor who takes care of
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.*;
The client performs all of its interactions with the remote EJB in the run method.
package book;
import javax.ejb.*;
import java.rmi.*;
package book;
111
import javax.ejb.*;
import javax.naming.*;
import java.util.*;
SessionContext cts;
{}
try
p.put(Context.INITIAL_CONTEXT_FACTORY,”weblogic.jndi.TengahInitialFactory”);
orderHome oh=(orderhome)ic.lookup(“orderhome”);
order o1=oh.create(1,”1”,1);
ol.remote();
}catch(Exception e){System.out.println(e);}
{}
{}
{}
this.ctx=ctx;
112
4)The client
import book;
import book.client;
import javax.naming.InitialContext;
InitialContext ic=newInitialContext();
clienthome ch=(clienthome)ic.lookup(“clienthome”);
client c=ch.create();
c.run();
c.remove();
System.out.println(“client is done”);
Section : A
113
1)Distinguish between CMP and BMP
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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.
1.sessiondescriptor class
public sessionDescriptor();
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 EntityDescriptor();
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
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
117
Lecture Notes – (2017-18)
Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45
It does occur:
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)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
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
Section : A
1. Define Network
2. Define distributed system.
Section : B
Section : C
1)What are Tips,Tricks and Traps for building distributed and other systems?Explain in details.
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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:
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.
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
Section : A
122
1. Write a note on application server
2. Define web server.
Section : B
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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
so known as associative arrays. Here is a little detail about these data types.
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.
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 −
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 −
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
Section : A
1. Define perl
2. What are handles?
3. What are hashes?
4. What are arrays?
Section : B
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
127
Lecture Notes – (2017-18)
Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45
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
Syntax
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";
A Perl if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
Syntax
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
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
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
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 −
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;
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
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;
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
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;
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 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
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;
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
Section : A
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
135
DEPARTMENT OF MCA/MSC(CS&CST)
Perl operators:
Arithmetic Operators
Equality Operators
Logical Operators
Assignment Operators
Bitwise Operators
Logical Operators
Quote-like 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 −
[ Show Example ]
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
-----------------
[ Show Example ]
There are following logical operators supported by Perl language. Assume variable $a holds
true and variable $b holds false then −
[ Show Example ]
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.
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.
sub subroutine_name{
body of the subroutine
}
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();
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;
# Function call
Average(10, 20, 30);
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;
Section : A
141
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
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.
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 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.
Advantages of RMI
1)Handles threads
144
2)handles sockets
3)marshals objects
5)can also make changes on the server end, that might not mean you need to change anything
on the client side.
Section : A
1. Define RMI
2. What are the applications of RMI?
3.
Section : B
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
145
Subject Name : Advanced Java Subject Code :
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.
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.
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
Skeleton:
The skeleton is a server side object that process the client’s network calls. It performs
the following operations for each received cell.
D:/jdk1.4/bin/rmic impl;
146
Where
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
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
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.
Section : A
1. Define stub
2. Define skeleton.
3. What is remote interface?
Section : B
147
3)Write a note on skeleton.
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
148
Semester : ODD Year : 2016
import java.rmi.*;
import java.rmi.*;
import java.rmi.server.*;
{}
return ((p*n*r)/100);
import java.net.*;
import java.rmi.*;
149
{
try
Naming.rebind(“server”,i);
}catch(Exception e){System.out.println(e);}
import java.io.*;
import java.rmi.*;
try
String s1=”rmi://”+args[0]+”/server”;
intf i=(intf)Naming.lookup(s1);
int p=Integer.parseInt(d.readLine());
int n=Integer.parseInt(d.readLine());
Double r=Integer.parseDouble(d.readLine());
}catch(Exception e){System.out.println(e);}
150
}
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
D:/jdk1.4/bin/rmic impl
D:/jdk1.4/bin/start rmiregistry
D:/jdk1.4/bin/java server
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
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.
Section : A
1. Define corba
2. Write a note on IIOP
Section : B
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
152
Course / Branch: MCA/MSC(CS&CST) Total No. of Hours Allotted : 45
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.
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
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.
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
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>
}
}
Section : A
1. Define JSP.
Section : B
Section : C
Discussion 05 Minutes
155
Signature of the Faculty Signature of the HOD
Note:
Lecture Notes Minimum 2 Pages
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
<html>
<body>
String variable having value : <%=stVariable%>
</body>
</html>
jspInt.jsp
<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.
jspFloat.jsp
<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”
jspBoolean.jsp
<html>
<body>
<%
if(checkCondition==true)
{
out.print("This condition is true");
}
else
{
out.print("This condition is false");
}
%>
</body>
</html>
Section : A
1. Define variable
2. List any four data types supported by JSP.
Section : B
Section : C
Discussion 05 Minutes
158
Signature of the Faculty Signature of the HOD
Note:
Lecture Notes Minimum 2 Pages
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.
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
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
<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 :
160
Example of Scriptlet
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>
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
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>
%>
<html>
<head>
<title>My First JSP Page</title>
</head>
<%!
int count = 0;
161
%>
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>
Section : A
Section : C
Discussion 05 Minutes
162
Note:
Lecture Notes Minimum 2 Pages
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
language attribute
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
out.print((2*5));
<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.
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.
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
Section : C
Discussion 05 Minutes
167
Signature of the Faculty Signature of the HOD
Note:
Lecture Notes Minimum 2 Pages
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:
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:
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.
Attribute Description
Example:
Let us define following two files (a)date.jsp and (b) main.jsp as follows:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
<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:
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.
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to
modify and retrieve bean properties.
Attribute Description
Type Specifies the type of the variable that will refer to the object.
Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid
example related to these actions.
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:
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:
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing
one was found.
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 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:
Attribute Description
Example:
/* File: TestBean.java */
package action;
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:setProperty name="test"
property="message"
value="Hello JSP..." />
<p>Got message....</p>
</center>
</body>
</html>
Got message....
Hello JSP...
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.
Attribute Description
Example:
Let us reuse following two files (a) date.jsp and (b) main.jsp as follows:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
<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.
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.
<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>, 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.
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page">
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
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
176
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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.
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.
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
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.).
<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>
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
Section : A
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
180
SRM ARTS AND SCIENCE COLLEGE
SRM NAGAR, KATTANKULATHUR – 603203
DEPARTMENT OF MCA/MSC(CS&CST)
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
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:
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;
182
try {
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");
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
JavaMail Protocols:
The protocols that underpin the workings of electronic mail are well established are
very mature.
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.
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.
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.
4)Transportation:
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);
Section : A
1. Define javamail
2. Define SMTP
3. Define MIME.
4. List the components of javamail.
Section : B
Section : C
Discussion 05 Minutes
185
Note:
Lecture Notes Minimum 2 Pages
1)Destinations:
2)Connections
3)Connection factories
4)sessions
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:
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.
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.
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.
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.
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
Section : C
Discussion 05 Minutes
Note:
Lecture Notes Minimum 2 Pages
192