Advance Java Labmanual
Advance Java Labmanual
Advance Java Labmanual
LAB MANUAL
of
Advance Java Lab
(Subject Code: 5CS2-24 :) (L-T-P: 0-0-2)
Max. Marks: 50(IA:30, ETE:20)
Advance Java Lab
Name of Laboratory:
2
Experiment 1:- Servlets
Objective :- Write a program to provide database connectivity using Type 1 Driver to a
employee table to insert, update, delete data using Servlets.
Procedure:-
1. use SampleDB;
Or if you are using MySQL Command Line Client program, save the above script into a file,
let’s say, SQLScript.sql and execute the following command:
source Path\To\The\Script\File\SQLScript.sql
Here’s an example screenshot taken while executing the above script in MySQL Command
Line Client program:
4
2. The principal JDBC interfaces and classes
Let’s take an overview look at the JDBC’s main interfaces and classes with which we usually
work. They are all available under the java.sql package:
o DriverManager: this class is used to register driver for a specific database type (e.g.
MySQL in this tutorial) and to establish a database connection with the server via its
getConnection() method.
o Connection: this interface represents an established database connection (session)
from which we can create statements to execute queries and retrieve results, get
metadata about the database, close connection, etc.
o Statement and PreparedStatement: these interfaces are used to execute static SQL
query and parameterized SQL query, respectively. Statement is the super interface of
the PreparedStatement interface. Their commonly used methods are:
A prepared statement is one that contains placeholders (in form question marks ?)
for dynamic values will be set at runtime. For example:
SELECT * from Users WHERE user_id=?
Here the value of user_id is parameterized by a question mark and will be set by one
of the setXXX() methods from the PreparedStatement interface, e.g. setInt(int
index, int value).
o ResultSet: contains table data returned by a SELECT query. Use this object to iterate
over rows in the result set using next() method, and get value of a column in the current
row using getXXX() methods (e.g. getString(), getInt(), getFloat() and so on). The
column value can be retrieved either by index number (1-based) or by column name.
o SQLException: this checked exception is declared to be thrown by all the above
methods, so we have to catch this exception explicitly when calling the above
classes’ methods.
5
4. try {
5. Connection conn = DriverManager.getConnection(dbURL, username, password);
6. if (conn != null) {
7. System.out.println("Connected");
8. }
9. } catch (SQLException ex) {
10. ex.printStackTrace();
11. }
Once the connection was established, we have a Connection object which can be used to
create statements in order to execute SQL queries. In the above code, we have to close the
connection explicitly after finish working with the database:
conn.close();
However, since Java 7, we can take advantage of the try-with-resources statement which will
close the connection automatically, as shown in the following code snippet:
1. try (Connection conn = DriverManager.getConnection(dbURL, username, password))
{
2. // code to execute SQL queries goes here...
3. } catch (SQLException ex) {
4. ex.printStackTrace();
5. }
username: bill
password: secretpass
fullname: Bill Gates
email: [email protected]
Here’s the code snippet:
1. String sql = "INSERT INTO Users (username, password, fullname, email) VALUES
(?, ?, ?, ?)";
2. PreparedStatement statement = conn.prepareStatement(sql);
3. statement.setString(1, "bill");
4. statement.setString(2, "secretpass");
5. statement.setString(3, "Bill Gates");
6. statement.setString(4, "[email protected]");
7. int rowsInserted = statement.executeUpdate();
8. if (rowsInserted > 0) {
9. System.out.println("A new user was inserted successfully!");
10. }
In this code, we create a parameterized SQL INSERT statement and create a
PreparedStatement from the Connectionobject. To set values for the parameters in the
INSERT statement, we use the PreparedStatement‘s setString()methods because all these
columns in the table Users are of type VARCHAR which is translated to String type in Java.
Note that the parameter index is 1-based (unlike 0-based index in Java array).
6
The PreparedStatement interface provides various setXXX() methods corresponding to each
data type, for example:
o setBoolean(int parameterIndex, boolean
x) o setDate(int parameterIndex, Date x)
o setFloat(int parameterIndex, float x)
o …
And so on. Which method to be used is depending on the type of the corresponding column
in the database table?
Finally we call the PreparedStatement’s executeUpdate() method to execute the INSERT
statement. This method returns an update count indicating how many rows in the table were
affected by the query, so checking this return value is necessary to ensure the query was
executed successfully. In this case, executeUpdate() method should return 1 to indicate one
record was inserted.
7
based, the first column will be at index 1, the second at index 2, and so on. If you are not sure
or don’t know exactly the index of column, so passing a column name would be useful:
String fullname = result.getString("fullname");
For other data types, the ResultSet provide appropriate getter methods:
o getString()
o getInt()
o getFloat()
o getDate()
o getTimestamp()
o …
The following code snippet will update the record of “Bill Gates” as we inserted previously:
8
Experiment 2:- JSP
Objective :- Write a program in JSP to provide Login. Password Functionality using Type 1
Driver.
Procedure:-
Creating login form, we have used the DAO (Data Access Object), Factory method and DTO
(Data Transfer Object) design patterns. There are many files:
In this example, we are using the Oracle10g database to match the emailId and password
with the database. The table name is user432 which have many fields like name, email, pass
etc. You may use this query to create the table:
index.jsp
1. <a href="login.jsp">login</a>|
2. <a href="logout.jsp">logout</a>|
3. <a href="profile.jsp">profile</a>
9
login.jsp
This file creates a login form for two input fields name and password. It is the simple login
form, you can change it for better look and feel. We are focusing on the concept only.
loginprocess.jsp
This jsp file contains all the incoming values to an object of bean class which is passed as an
argument in the validate method of the LoginDao class. If emailid and password is correct, it
displays a message you are successfully logged in! and maintains the session so that we may
recognize the user.
1. <%@page import="bean.LoginDao"%>
2. <jsp:useBean id="obj" class="bean.LoginBean"/>
3.
4. <jsp:setProperty property="*" name="obj"/>
5.
6. <%
7. boolean status=LoginDao.validate(obj);
8. if(status){
9. out.println("You r successfully logged in");
10
10. session.setAttribute("session","TRUE");
11. }
12. else
13. {
14. out.print("Sorry, email or password error");
15. %>
16. <jsp:include page="index.jsp"></jsp:include>
17. <%
18. }
19. %>
LoginBean.java
It is the bean class that have 2 properties email and pass with its setter and getter methods.
1. package bean;
2.
3. public class LoginBean {
4. private String email,pass;
5.
6. public String getEmail() {
7. return email;
8. }
9.
10. public void setEmail(String email) {
11. this.email = email;
12. }
13.
14. public String getPass() {
15. return pass;
16. }
17.
18. public void setPass(String pass) {
19. this.pass = pass;
20. }
21.
22.
23. }
Provider.java
11
This interface contains four constants that may differ from database to database.
1. package bean;
2.
3. public interface Provider {
4. String DRIVER="oracle.jdbc.driver.OracleDriver";
5. String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";
6. String USERNAME="system";
7. String PASSWORD="oracle";
8.
9. }
ConnectionProvider.java
This class provides a factory method that returns the object of Connection. Here, driver class
is loaded only once and connection object gets memory only once because it is static.
1. package bean;
2. import java.sql.*;
3. import static bean.Provider.*;
4.
5. public class ConnectionProvider {
6. private static Connection con=null;
7. static{
8. try{
9. Class.forName(DRIVER);
10. con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD );
LoginDao.java
12
1. package bean;
2. import java.sql.*;
3. public class LoginDao {
4.
5. public static boolean validate(LoginBean bean){
6. boolean status=false;
7. try{
8. Connection con=ConnectionProvider.getCon();
9.
10. PreparedStatement ps=con.prepareStatement(
11. "select * from user432 where email=? and pass=?");
12.
13. ps.setString(1,bean.getEmail());
14. ps.setString(2, bean.getPass());
15.
16. ResultSet rs=ps.executeQuery();
17. status=rs.next();
18.
19. }catch(Exception e){}
20.
21. return status;
22.
23. }
24. }
13
Experiment 3:- Cookies
Objective :- Write a program using servlet to write persistent and non-persistent cookies on
client side.
Procedure:-
Cookies in Servlet
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
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
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
14
2. Cookies are maintained at client side.
Disadvantage of Cookies
Cookie class
There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be
changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)
For adding cookie or getting the value from the cookie, we need some methods provided
by other interfaces. They are:
15
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of c
ookie
4. }
16
In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet. As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the different value.
index.html
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29. }
17
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
18
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
19
Experiment 4:- Client Request
Objective :- Write a program to print server side information using JSP as Client IP Address,
URL, Context Info, hit count.
Procedure:-
When a browser requests for a web page, it sends lot of information to the web server which
can not be read directly because this information travel as a part of header of HTTP request.
You can check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and you
would use very frequently in web programming:
Header Description
Accept This header specifies the MIME types that the browser or other clients
can handle. Values of image/png or image/jpeg are the two most
common possibilities.
Accept- This header specifies the character sets the browser can use to display the
Charset information. For example ISO-8859-1.
Accept- This header specifies the types of encodings that the browser knows how
Encoding to handle. Values of gzip or compress are the two most common
possibilities.
Accept- This header specifies the client's preferred languages in case the servlet
Language can produce results in more than one language. For example en, en-us, ru,
etc.
Authorization This header is used by clients to identify themselves when accessing
password-protected Web pages.
Connection This header indicates whether the client can handle persistent HTTP
connections. Persistent connections permit the client or other browser to
retrieve multiple files with a single request. A value of Keep-Alive means
that persistent connections should be used
Content- This header is applicable only to POST requests and gives the size of the
Length POST data in bytes.
Cookie This header returns cookies to servers that previously sent them to the
browser.
Host This header specifies the host and port as given in the original URL.
If-Modified- This header indicates that the client wants the page only if it has been
Since changed after the specified date. The server sends a code, 304 which
means Not Modified header if no newer result is available.
If- This header is the reverse of If-Modified-Since; it specifies that the
Unmodified- operation should succeed only if the document is older than the specified
Since date.
Referer This header indicates the URL of the referring Web page. For example, if
you are at Web page 1 and click on a link to Web page 2, the URL of
Web page 1 is included in the Referer header when the browser requests
Web page 2.
20
User-Agent This header identifies the browser or other client making the request and
can be used to return different content to different types of browsers.
The request object provides methods to get HTTP header information including form data,
cookies, HTTP methods etc.
There are following important methods which can be used to read HTTP header in your JSP
program. These method are available with HttpServletRequest object which represents client
request to webserver.
21
10
String getAuthType()
Returns the name of the authentication scheme used to protect the servlet, for
example, "BASIC" or "SSL," or null if the JSP was not protected
11
String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request.
12
String getContentType()
Returns the MIME type of the body of the request, or null if the type is not known.
13
String getContextPath()
Returns the portion of the request URI that indicates the context of the request.
14
String getHeader(String name)
Returns the value of the specified request header as a String.
15
String getMethod()
Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT.
16
String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does
not exist.
17
String getPathInfo()
Returns any extra path information associated with the URL the client sent when it
made this request.
18
String getProtocol()
Returns the name and version of the protocol the request.
19
String getQueryString()
Returns the query string that is contained in the request URL after the path.
20
String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.
21
String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
22
String getRemoteUser()
Returns the login of the user making this request, if the user has been authenticated,
or null if the user has not been authenticated.
23
String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query
string in the first line of the HTTP request.
24
String getRequestedSessionId()
Returns the session ID specified by the client.
25
String getServletPath()
Returns the part of this request's URL that calls the JSP.
22
26
String[] getParameterValues(String name)
Returns an array of String objects containing all of the values the given request
parameter has, or null if the parameter does not exist.
27
boolean isSecure()
Returns a boolean indicating whether this request was made using a secure channel,
such as HTTPS.
28
int getContentLength()
Returns the length, in bytes, of the request body and made available by the input
stream, or -1 if the length is not known.
29
int getIntHeader(String name)
Returns the value of the specified request header as an int.
30
int getServerPort()
Returns the port number on which this request was received.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement()
method to get each parameter name.
23
14. Enumeration headerNames = request.getHeaderNames();
15. while(headerNames.hasMoreElements()) {
16. String paramName = (String)headerNames.nextElement();
17. out.print("<tr><td>" + paramName + "</td>\n");
18. String paramValue = request.getHeader(paramName);
19. out.println("<td> " + paramValue + "</td></tr>\n");
20. }
21. %>
22. </table>
23. </center>
24. </body>
25. </html>
Now put the above code in main.jsp and try to access it. This would produce result
something as follows:
24
Experiment 5:- JSP Tags
Objective :- Write a program to create a custom tag in JSP that gives Forward and Include
Actions
Procedure:-
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
jsp:plugin Generates browser-specific code that makes an OBJECT or 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.
Common Attributes:
There are two attributes that are common to all Action elements: the id attribute and the
scope attribute.
Id attribute: The id attribute uniquely identifies the Action element, and allows the
action to be referenced inside the JSP page. If the Action creates an instance of an object
the id value can be used to reference it through the implicit object PageContext
Scope attribute: This attribute identifies the lifecycle of the Action element. The id
attribute and the scope attribute are directly related, as the scope attribute determines
the lifespan of the object associated with the id. The scope attribute has four possible
values: (a) page, (b)request, (c)session, and (d) application.
25
ASETL CSE/VI SEM AJP LAB
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
page The relative URL of the page to be included.
flush The boolean attribute determines whether the included resource has its buffer
flushed before it is included.
Example:
Let us define following two files (a)date.jsp and (b) main.jsp as follows:
1. <p>
2. Today's date: <%= (new java.util.Date()).toLocaleString()%>
3. </p>
1. <html>
2. <head>
3. <title>The include Action Example</title>
4. </head>
5. <body>
6. <center>
7. <h2>The include action Example</h2>
8. <jsp:include page="date.jsp" flush="true" />
9. </center>
10. </body>
11. </html>
Now let us keep all these files in root directory and try to access main.jsp. This would
display result something like this:
26
Today's date: 12-Sep-2010 14:54:22
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
class Designates the full package name of the bean.
type Specifies the type of the variable that will refer to the object.
beanName Gives the name of the bean as specified by the instantiate () method of the
java.beans.Beans class.
Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid
example related to these actions.
The 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:
27
3. <jsp:setProperty name="myName" property="someProperty" .../>
4. </jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing
one was found.
Attribute Description
name Designates the bean whose property will be set. The Bean must have been
previously defined.
property Indicates the property you want to set. A value of "*" means that all request
parameters whose names match bean property names will be passed to the
appropriate setter methods.
value The value that is to be assigned to the given property. The the parameter's
value is null, or the parameter does not exist, the setProperty action is ignored.
param The param attribute is the name of the request parameter whose value the
property is to receive. You can't use both value and param, but it is permissible
to use neither.
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
name The name of the Bean that has a property to be retrieved. The Bean must have
been previously defined.
property The property attribute is the name of the Bean property to be retrieved.
Example:
1. /* File: TestBean.java */
2. package action;
28
3. public class TestBean {
4. private String message = "No message specified";
5. public String getMessage() {
6. return(message);
7. }
8. public void setMessage(String message) {
9. this.message = message;
10. }
11. }
Compile above code to generated TestBean.class file and make sure that you copied
TestBean.class in C:\apache-tomcat-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:
1. <html>
2. <head>
3. <title>Using JavaBeans in JSP</title>
4. </head>
5. <body>
6. <center>
7. <h2>Using JavaBeans in JSP</h2>
8. <jsp:useBean id="test" class="action.TestBean" />
9. <jsp:setProperty name="test"
property="message"
value="Hello JSP..." />
10. <p>Got message....</p>
11. <jsp:getProperty name="test" property="message" />
12. </center>
13. </body>
14. </html>
29
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
page Should consist of a relative URL of another resource such as a static page,
another JSP page, or a Java Servlet.
Example:
Let us reuse following two files (a) date.jsp and (b) main.jsp as follows:
1. <p>
2. Today's date: <%= (new java.util.Date()).toLocaleString()%>
3. </p>
1. <html>
2. <head>
3. <title>The include Action Example</title>
4. </head>
5. <body>
6. <center>
7. <h2>The include action Example</h2>
8. <jsp:forward page="date.jsp" />
9. </center>
30
10. </body>
11. </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.
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.
31
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.
1. <html xmlns="http://www.w3c.org/1999/xhtml"
2. xmlns:jsp="http://java.sun.com/JSP/Page">
3. <head><title>Generate XML Element</title></head>
4. <body>
5. <xmlElement xmlElementAttr="Value for the attribute">
6. Body for XML element
7. </xmlElement>
8. </body>
9. </html>
The <jsp:text> Action
The <jsp:text> action can be used to write template text in JSP pages and documents.
Following is the simple syntax for this action:
32
1. <jsp:text>Template data</jsp:text>
The body of 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.
1. <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:
1. <jsp:text><![CDATA[<!DOCTYPE html
2. PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3. "DTD/xhtml1-strict.dtd">]]>
4. </jsp:text>
5. <head><title>jsp:text action</title></head>
6. <body>
7. <books><book><jsp:text>
8. Welcome to JSP Programming
9. </jsp:text></book></books>
10. </body>
11. </html>
33
Experiment 6:- Session Beans
Objective :- Write a program to implement Stateless Session Beans
Procedure:-
Stateless Session Bean
Stateless Session bean is a business object that represents business logic only. It doesn't
have state (data).
In other words, conversational state between multiple method calls is not maintained by the
container in case of stateless session bean.
The stateless bean objects are pooled by the EJB container to service the request on demand.
It can be accessed by one client at a time. In case of concurrent access, EJB container routes
each request to different instance.
1. @Stateless
2. @PostConstruct
3. @PreDestroy
There is only two states of stateless session bean: does not exist and ready. It is explained by
the figure given below.
34
EJB Container creates and maintains a pool of session bean first. It injects the dependency if
then calls the @PostConstruct method if any. Now actual business logic method is invoked
by the client. Then, container calls @PreDestory method if any. Now bean is ready for
garbage collection.
To develop stateless bean application, we are going to use Eclipse IDE and glassfish 3 server.
To create EJB application, you need to create bean component and bean client.
To create the stateless bean component, you need to create a remote interface and a bean class.
File: AdderImplRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3.
4. @Remote
5. public interface AdderImplRemote {
6. int add(int a,int b);
7. }
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.ejb.Stateless;
3.
4. @Stateless(mappedName="st1")
5. public class AdderImpl implements AdderImplRemote {
6. public int add(int a,int b){
7. return a+b;
8. }
9. }
The stateless bean client may be local, remote or webservice client. Here, we are going to
create remote client. It is console based application. Here, we are not using dependency
injection. The dependency injection can be used with web based client only.
File: AdderImpl.java
1. package com.javatpoint;
35
2. import javax.naming.Context;
3. import javax.naming.InitialContext;
4.
5. public class Test {
6. public static void main(String[] args)throws Exception {
7. Context context=new InitialContext();
8. AdderImplRemote remote=(AdderImplRemote)context.lookup("st1");
9. System.out.println(remote.add(32,32));
10. }
11. }
36
Experiment 7:- Entity Bean
Objective :- Write a program to implement Entity Bean
Procedure:-
Enterprise JavaBeans: Working with Entity and Session Beans
Today, more and more developers want to write distributed transactional applications for the
enterprise, and leverage the speed, security, and reliability of server-side technology. One
approach is to use a multitiered model where a thin-client application invokes business logic
that executes on the server.
Normally, thin-client multitiered applications are hard to write because they involve many
lines of intricate code to handle transaction and state management, multithreading, resource
pooling, and other complex low-level details. The Enterprise JavaBeans (EJB) architecture
makes these applications easy to write because it separates the low-level details from the
business logic. You concentrate on creating the best business solution and leave the rest to
the underlying architecture.
To show you how it works, this article walks through a very simple web-based application
where the thin-client is a servlet. The servlet invokes enterprise Beans for database reads and
writes and to perform a simple calculation.
There are two types of enterprise Beans: session Beans and entity Beans. An enterprise Bean
that implements a business task is a session Bean, and an enterprise Bean that implements a
business entity is an entity Bean.
A session Bean represents a transient conversation with a client, and might execute
database reads and writes. A session Bean might invoke the JDBC calls itself or it
might use an entity Bean to make the call, in which case the session Bean is a client to
the entity Bean. A session Bean's fields contain the state of the conversation and are
transient. If the server or client crashes, the session Bean is gone. This model is
typically used with database programming languages such as PL/SQL.
An entity Bean represents data in a database and the methods to act on that data. In a
relational database context for a table of employee information, there is one Bean for
each row in the table. Entity Beans are transactional and long-lived. As long as the
data remains in the database, the entity Bean exists. This model can be easily used for
relational databases and is not restricted to object databases.
37
Life of client is life of Bean. Persists as long as data in database.
Can be transaction aware. Transactional.
Does not survive server crashes. Survives server crashes.
Note: In the Enterprise Java Beans specification, EJB Server support for session Beans is
mandatory. EJB Server Support for entity Beans is currently optional, but becomes
mandatory for version 2.0 of the specification.
Simple Example
A high-level view of the simple example application is shown in the diagram. The client
application is a servlet that receives data from and sends data to a browser, and interacts with
an entity Bean and a session Bean through their home and remote interfaces. The EJB Home
Server handles all the low-level details including the database read and write operations.
An enterprise Bean's remote interface describes the Bean's methods, or what the Bean
does. A client program or another enterprise Bean calls the methods defined in the
remote interface to invoke the business logic implemented by the Bean.
An enterprise Bean's home interface describes how a client program or another
enterprise Bean creates, finds, and removes that enterprise Bean from its container.
The container, shown in light blue (cyan), provides the interface between the
enterprise Bean and the low-level platform-specific functionality that supports the
enterprise Bean.
You do not need to know how an enterprise Bean is implemented to use it; all you need to
know are its methods. You might or might not write your own enterprise Beans to use in an
application. It is possible and often desirable to use enterprise Beans written by a provider
that you assemble into an application.
Deployment tools and an EJB Home Server are essential to running the application code. The
deployment tools generate enterprise Bean containers, which are classes that provide an interface
to the low-level implementations in a given EJB Server. The server provider can include
containers and deployment tools for their server and will typically publish their low-level
interfaces so other vendors can develop containers and deployment tools for their server.
38
The simple example uses the EJB Server created by EJBHome. Visit this site for a free
reference implementation that includes the EJB Server and deployment tools for generating
containers. The site also provides tutorials to walk you through example programs that come
with the download.
Source Code
The source code files for the example are listed below. The example program requires a
database table named bonus with the following fields:
Other naming conventions are used within the source code and discussed below where they
appear. While source file-naming conventions are standard across EJB Server
implementations, naming conventions used within the source are specific to the EJB Server
or deployment tool you use.
Client Program
BonusServlet.java.
Running the Application
Entity Bean
39
Session Bean
Calc.java, the remote interface with this method:
o calcBonus
CalcHome.java, the home interface with this
method: o create
CalcBean.java, an enterprise Bean with these public fields and methods:
o int bonus
o int calcBonus
o ejbCreate
Container Classes
When the entity and session Beans are deployed, a number of container source and class files
are generated with the following prefixes. A container is a set of classes generated by the
deployment tool that manages an enterprise Bean's persistence, transactional properties, and
security.
EJBHomeBonus*.java
EJBHomeBonus*.class
EJBHomeCalc*.java
EJBHomeCalc*.class
Client Program
The thin-client BonusServlet.java declares variables and parameter values of specific types to
locate the database table, create the home interface, and invoke the entity and session Bean
methods.
Note: To keep the code simple, data values that the servlet would normally receive from user
input to a browser form is hard coded.
These are the import and declarations statements. The entity Bean remote interface type is
Bonus and maps to the database table name, which is also Bonus. The socsec and bonus
variables map to the fields in the database table. Variable names that map to the database
table or fields in the database are case insensitive.
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. import java.util.Properties;
5. import javax.naming.*;
6. //location of Bean classes
7. import com.ejbhome.examples.*;
40
12. //Session Bean home and remote interface variables
13. CalcHome homecalc;
14. Calc theCalculation;
The EJB Home Server uses the beans.properties configuration file to map enterprise Beans to
the home interfaces for their respective container classes. Here is how the mapping looks.
The container classes are not created until the Beans are deployed, but you can put the entry
into this file before you deploy because the naming convention is consistent. The values calcs
and bonuses are used in the next code segment for the enterprise Bean lookup. The values in
this file and the strings used in the code have to match exactly so the EJB Home Server can
look up the enterprise Bean home interface.
1. calcs=com.ejbhome.examples.EJBHomeCalcHome
2. bonuses=com.ejbhome.examples.EJBHomeBonusHome
3. Here is the servlet init method implementation. The JNDI API is used to look up the
Beans and containers.
4. public void init(ServletConfig config)
5. throws ServletException{
6. try{
7. Properties env = new Properties();
8. env.put("java.naming.factory.initial",
9. "com.ejbhome.naming.
10. //spi.rmi.RMIInitCtxFactory");
11. Context ctx = new InitialContext(env);
12. //Look up home interfaces and containers
13. //for entity and session beans.
14. //Strings map to settings in
15. the beans.properties file.
16. homebonus =
17. (BonusHome)ctx.lookup("bonuses");
18. homecalc =
19. (CalcHome)ctx.lookup("calcs");
1. try{
2. socsec = 555220000;
41
3. bonus = 200;
1. try{
2. //Instantiate a primary key object
3. BonusPK PK = new BonusPK(555220000);
4. //Locate a record with the primary key
5. rec1 = hmebonus.findByPrimaryKey(PK);
6. //Use the entity Bean home interface
7. //to retrieve current bonus value
8. retbonus = rec1.getBonus();
This next code segment creates the session Bean's home interface, and uses the home
interface to call the session Bean's calcBonus method. The hard-coded values passed to the
calcBonus method would normally be received by user input to a form in the browser. For
simplicity, the code to display the final bonus in the browser is not included in the segment,
but here is the entire source file for the BonusServlet.java servlet.
1. //Calculate bonus
2. int base = 100;
3. int perf=5, company=2;
4. theCalculation = homecalc.create();
5. int calc = theCalculation.calcBonus(
a. base, perf, company);
6. System.out.println(calc);
7. rec1.addBonus(calc);
8. retbonus = rec1.getBonus();
9. } catch (Exception FinderException) {
10. FinderException.printStackTrace();
11. }
42
Running the Application
The thin-client servlet produces the following output. Of course, you need the entity and
session Beans compiled and deployed before the application will actually work. The next
sections describe the source files for the enterprise Beans and enterprise Bean deployment.
Record 1
SocSec:555220000
Bonus Total: 200
Record 2
1. package com.ejbhome.examples;
2. import javax.ejb.*;
3. import java.rmi.*;
4. public interface BonusHome extends EJBHome {
5. Bonus create(int bonus, int socsec)
6. throws CreateException, RemoteException;
7. Bonus findByPrimaryKey(BonusPK socsec)
8. throws FinderException, RemoteException;
9. }
When the home interface is instantiated, the EJB Home Server also creates the remote interface
and enterprise Bean instances. Here is the remote interface. It extends EJBObject and declares
43
the BonusBean methods. It also follows the rules of the RMI API in that the arguments and
return types for each method must be serializable and the methods should throw
java.rmi.RemoteException as one of its exception.
package com.ejbhome.examples;
1. import javax.ejb.*;
2. import java.rmi.*;
The EJBHome server requires a container-managed entity Bean to have a primary key class
with a public primary key field (or fields, if using composite primary keys). You can have the
container manage an enterprise Bean or write the code to manage the Bean yourself. In this
example, both Beans are container-managed, and you should always let the container manage
an entity Bean.
Here is the primary key class. The primary key in the Bonus table is socsec, and so socsec is
a public field in this class that is assigned a value when the class is constructed.
1. package com.ejbhome.examples;
8. public BonusPK() {}
9. }
Now for a look at the entity bean source code. It implements EntityBean and the developer-
defined and interface methods. It should follow the rules of the RMI API in that the
arguments and return types for each method must be serializable and the methods should
throw java.rmi.RemoteException as one of its exception.
1. package com.ejbhome.examples;
2. import java.rmi.RemoteException;
3. import javax.ejb.*;
44
5. public int bonus = 0;
6. public int socsec = 0;
7. protected EntityContext ctx;
45
Session Bean Source Code
The session Bean performs a simple calculation. Its source code is similar to the entity Bean
source code with the few differences described here.
The home interface does not have a FindByPrimaryKey method because no database access
is involved. A session Bean could perform database access, and would then need a
FindByPrimaryKey method, but the simple example does not need it.
1. package com.ejbhome.examples;
2. import javax.ejb.*;
3. import java.rmi.*;
4. public interface CalcHome extends EJBHome {
5. Calc create() throws CreateException, RemoteException;
6. }
7. The remote interface declares the session Bean's one method.
8. package com.ejbhome.examples;
9. import javax.ejb.*;
10. import java.rmi.*;
11. public interface Calc extends EJBObject {
12. int calcBonus(int base, int perf, int company) throws RemoteException;
13. }
14. The session Bean implements SessionBean and the developer-defined and interface
methods.
15. package com.ejbhome.examples;
16. import java.rmi.RemoteException;
17. import javax.ejb.*;
18. public class CalcBean implements SessionBean
19. throws Remote Exception {
20. public int bonus;
21. protected SessionContext ctx;
22. public int calcBonus(int base,
23. int perf, int company) {
24. int calc = (base*perf*company);
25. this.bonus += calc;
26. return this.bonus;
27. }
28. public void ejbCreate() throws CreateException,
29. RemoteException {}
46
39. RemoteException { }
40. public void ejbPassivate() throws
41. RemoteException { }
42. public void ejbLoad() throws
43. RemoteException { }
44. public void ejbStore() throws
45. RemoteException { }
46. }
Container Classes
The Deployer tool generates these container classes for BonusBean and CalcBean.
BonusBean CalcBean
EJBHomeBonusBean.class EJBHomeCalcBean.class
EJBHomeBonusBean.java EJBHomeCalcBean.java
EJBHomeBonusHome.class EJBHomeCalcHome.class
EJBHomeBonusHome.java EJBHomeCalcHome.java
EJBHomeBonusHome_Skel.class EJBHomeCalcHome_Skel.class
EJBHomeBonusHome_Skel.java EJBHomeCalcHome_Skel.java
EJBHomeBonusHome_Stub.class EJBHomeCalcHome_Stub.class
EJBHomeBonusHome_Stub.java EJBHomeCalcHome_Stub.java
EJBHomeBonusMetaData.class EJBHomeCalcMetaData.class
EJBHomeBonusMetaData.java EJBHomeCalcMetaData.java
EJBHomeRemoteBonus.class EJBHomeRemoteCalc.class
EJBHomeRemoteBonus.java EJBHomeRemoteCalc.java
EJBHomeRemoteBonus_Skel.class EJBHomeRemoteCalc_Skel.class
EJBHomeRemoteBonus_Skel.java EJBHomeRemoteCalc_Skel.java
EJBHomeRemoteBonus_Stub.class EJBHomeRemoteCalc_Stub.class
EJBHomeRemoteBonus_Stub.java EJBHomeRemoteCalc_Stub.java
47
Experiment 8:- Struts
Objective :- Write a program to implement Struts
Procedure:-
we are creating the struts 2 without IDE. We can simply create the struts 2 application by
following these simple steps:
1. Create the directory structure
2. Create input page (index.jsp)
3. Provide the entry of Controller in (web.xml) file
4. Create the action class (Product.java)
5. Map the request with the action in (struts.xml) file and define the view components
6. Create view components (welcome.jsp)
7. load the jar files
8. start server and deploy the project
1) Create the directory structure
The directory structure of struts 2 is same as servlet/JSP. Here, struts.xml file must be located
in the classes folder.
48
5. <s:textfield name="price" label="Product Price"></s:textfield>
6. <s:submit value="save"></s:submit>
7. </s:form>
49
17. }
18. public float getPrice() {
19. return price;
20. }
21. public void setPrice(float price) {
22. this.price = price;
23. }
24.
25. public String execute(){
26. return "success";
27. }
28. }
5) Map the request in (struts.xml) file and define the view components
It is the important file from where struts framework gets information about the action and
decides which result to be invoked. Here, we have used many elements such as struts,
package, action and result.
struts element is the root elements of this file. It represents an application.
package element is the sub element of struts. It represents a module of the application. It
generally extends the struts-default package where many interceptors and result types are
defined.
action element is the sub element of package. It represents an action to be invoked for the
incoming request. It has name, class and method attributes. If you don't specify name
attribute by default execute() method will be invoked for the specified action class.
result element is the sub element of action. It represents an view (result) that will be invoked.
Struts framework checks the string returned by the action class, if it returns success, result
page for the action is invoked whose name is success or has no name. It has name and type
attributes. Both are optional. If you don't specify the result name, by default success is
assumed as the result name. If you don't specify the type attribute, by default dispatcher is
considered as the default result type. We will learn about result types later.
struts.xml
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
3. Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
4. <struts>
5. <package name="default" extends="struts-default">
6.
7. <action name="product" class="com.javatpoint.Product">
8. <result name="success">welcome.jsp</result>
9. </action>
10.
11. </package>
12. </struts>
50
6) Create view components (welcome.jsp)
It is the view component the displays information of the action. Here, we are using struts tags
to get the information.
The s:property tag returns the value for the given name, stored in the action
object. welcome.jsp
1. <%@ taglib uri="/struts-tags" prefix="s" %>
2.
3. Product Id:<s:property value="id"/><br/>
4. Product Name:<s:property value="name"/><br/>
5. Product Price:<s:property value="price"/><br/>
51
Experiment 9:- Develop an application to implement RMI based Calculator
Theory:
The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM.
The RMI provides remote communication between the applications using two objects stub
and skeleton.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does the
following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.
3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes
the RMI compiler and creates stub and skeleton objects.
rmic AdderRemote
Implementation //RMICalImpl.java
import java.rmi.*;
import java.io.*;
import java.rmi.server.*;
public class RMICalImpl extends UnicastRemoteObject implements RMICalIntf
{ //Defining the methods declared in the interface
RMICalImpl() throws RemoteException
{
}
public double add(double a, double b)throws RemoteException
{
return(a+b);
}
public double sub(double a,double b)throws RemoteException
{
return(a-b);
}
public double mul(double a,double b)throws RemoteException
{
return(a*b);
}
public double div(double a,double b)throws RemoteException
{
return(a/b);
}
}