Sie sind auf Seite 1von 58

ENGINEERING COLLEGE BIKANER

(An Autonomous Institution of Government of Rajasthan)


Affiliation: Bikaner Technical University, Bikaner
DEPARTMENT OF INFORMATION TECHNOLOGY

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:

Name of Program: B. Tech. (V semester)

Dr. Narpat Singh Shekhawat


Assistant Professor,
Name of Instructor:
Computer Science Engineering

Instructor’s office-hours: 9.00am 3.00pm


Good core java concepts, mathematical and
Prerequisite: logical skills.
LAB venue: LAB – 3
SWAYAM/NPTEL videos, ppts, Class notes
Tools/Material Used: posted on blackboard
LIST OF EXPERIMENTS

Write a program to provide database connectivity using Type 1


1. Driver to a employee table to insert, update, delete data using
Servlets
2. Write a program in JSP to provide Login. Password Functionality
using Type 1 Driver
Write a program using servlet to write persistent and non-
3.
persistent cookies on client side.
4. Write a program to print server side information using JSP as
Client IP Address, URL, Context Info, hit count.
5. Write a program to create a custom tag in JSP that gives Forward
and Include Actions
6. Write a program to implement Stateless Session Beans

7. Write a program to implement Entity Bean

8. Write a program to implement Struts

9. Develop an application to implement RMI based Calculator

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. Creating a sample MySQL database


Let’s create a MySQL database called SampleDB with one table Users with the following
structure:

Execute the following SQL script inside MySQL Workbench:


create database SampleDB;

1. use SampleDB;

2. CREATE TABLE `users` (


3. `user_id` int(11) NOT NULL AUTO_INCREMENT,
4. `username` varchar(45) NOT NULL,
5. `password` varchar(45) NOT NULL,
6. `fullname` varchar(45) NOT NULL,
7. `email` varchar(45) NOT NULL,
8. PRIMARY KEY (`user_id`)
9. );

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:

 boolean execute(String sql): executes a general SQL statement. It returns true if


the query returns a ResultSet, false if the query returns an update count or returns
 nothing. This method can be used with a Statement only.
 int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE
statement and returns an update account indicating number of rows affected (e.g.
 1 row inserted, or 2 rows updated, or 0 rows affected).
 ResultSet executeQuery(String sql): executes a SELECT statement and returns
a ResultSet object which contains results returned by the query.

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.

3. Connecting to the database


Supposing the MySQL database server is listening on the default port 3306 at localhost. The
following code snippet connects to the database name SampleDB by the user root and
password secret
1. String dbURL = "jdbc:mysql://localhost:3306/sampledb";
2. String username = "root";
3. String password = "secret";

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. }

4. Executing INSERT statement


Let’s write code to insert a new record into the table Users with following details:

 username: bill
 password: secretpass
 fullname: Bill Gates
 email: bill.gates@microsoft.com
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, "bill.gates@microsoft.com");
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.

5. Executing SELECT statement


The following code snippet queries all records from the Users table and print out details for
each record:
1. String sql = "SELECT * FROM Users";
2. Statement statement = conn.createStatement();
3. ResultSet result = statement.executeQuery(sql);
4. int count = 0;
5. while (result.next()){
6. String name = result.getString(2);
7. String pass = result.getString(3);
8. String fullname = result.getString("fullname");
9. String email = result.getString("email");
10. String output = "User #%d: %s - %s - %s - %s";
11. System.out.println(String.format(output, ++count, name, pass, fullname, email));
12. }
OUTPUT:
User #1: bill - secretpass - Bill Gates - bill.gates@microsoft.com
Because the SQL SELECT query here is static so we just create a Statement object from the
connection. The while loop iterates over the rows contained in the result set by repeatedly
checking return value of the ResultSet’s next() method. The next() method moves a cursor
forward in the result set to check if there is any remaining record. For each iteration, the
result set contains data for the current row, and we use the ResultSet’s getXXX(column
index/column name)method to retrieve value of a specific column in the current row, for
example this statement
String name = result.getString(2);
Retrieves value of the second column in the current row, which is the username field. The value
is casted to a String because we know that the username field is of type VARCHAR based on the
database schema mentioned previously. Keep in mind that the column index here is 1-

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 …

6. Executing UPDATE statement

The following code snippet will update the record of “Bill Gates” as we inserted previously:

1. String sql = "UPDATE Users SET password=?, fullname=?, email=?


WHERE username=?";
2. PreparedStatement statement = conn.prepareStatement(sql);
3. statement.setString(1, "123456789");
4. statement.setString(2, "William Henry Bill Gates");
5. statement.setString(3, "bill.gates@microsoft.com");
6. statement.setString(4, "bill");
7. int rowsUpdated = statement.executeUpdate();
8. if (rowsUpdated > 0) {
9. System.out.println("An existing user was updated successfully!");
10. }
This code looks very similar to the INSERT code above, except the query type is UPDATE.
7. Executing DELETE statement
The following code snippet will delete a record whose username field contains “bill”:
1. String sql = "DELETE FROM Users WHERE username=?";
2. PreparedStatement statement = conn.prepareStatement(sql);
3. statement.setString(1, "bill");
4. int rowsDeleted = statement.executeUpdate();
5. if (rowsDeleted > 0) {
6. System.out.println("A user was deleted successfully!");
7. }

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:

  index.jsp it provides three links for login, logout and profile


  login.jsp for getting the values from the user
  loginprocess.jsp, a jsp file that processes the request and calls the methods.
 LoginBean.java, a bean class that have properties and setter and getter methods.

 Provider.java, an interface that contains many constants like DRIVER_CLASS,
CONNECTION_URL, USERNAME and PASSWORD

 ConnectionProvider.java, a class that is responsible to return the object of
Connection. It uses the Singleton and factory method design pattern.

 LoginDao.java, a DAO class that verifies the emailId and password from the
 database.
 logout.jsp it invalidates the session.

 profile.jsp it provides simple message if user is logged in, otherwise forwards the
request to the login.jsp page.

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:

1. CREATE TABLE "USER432"


2. ( "NAME" VARCHAR2(4000),
3. "EMAIL" VARCHAR2(4000),
4. "PASS" VARCHAR2(4000)
5. )
6. /
We assume that there are many records in this table.

index.jsp

It simply provides three links for login, logout and profile.

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.

1. <%@ include file="index.jsp" %>


2. <hr/>
3.
4. <h3>Login Form</h3>
5. <%
6. String profile_msg=(String)request.getAttribute("profile_msg");
7. if(profile_msg!=null){
8. out.print(profile_msg);
9. }
10. String login_msg=(String)request.getAttribute("login_msg");
11. if(login_msg!=null){
12. out.print(login_msg);
13. }
14. %>
15. <br/>
16. <form action="loginprocess.jsp" method="post">
17. Email:<input type="text" name="email"/><br/><br/>
18. Password:<input type="password" name="password"/><br/><br/>
19. <input type="submit" value="login"/>"
20. </form>

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 );

11. }catch(Exception e){}


12. }
13.
14. public static Connection getCon(){
15. return con;
16. }
17.
18. }

LoginDao.java

This class varifies the emailid and password.

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.

How Cookie works

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

as the old user.

Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

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

Persistent cookie

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

Advantage of Cookies

1. Simplest technique of maintaining the state.

14
2. Cookies are maintained at client side.

Disadvantage of Cookies

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


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

Cookie class

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


of useful methods for cookies.

Constructor of Cookie class


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

Useful Methods of 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)

Other methods required for using Cookies

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

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


used to add cookie in response object.

15
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.

How to create Cookie?

Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

1. Cookie ck=new Cookie("user","");//deleting value of cookie


2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?

Let's see the simple code to get all the cookies.

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. }

Simple example of Servlet Cookies

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

1. <form action="servlet1" method="post">


2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

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 HttpServletRequest Object:

The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time


a client requests a page the JSP engine creates a new object to represent that request.

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.

S.N. Method & Description


1 Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with this request.
2 Enumeration getAttributeNames()
Returns an Enumeration containing the names of the attributes available to this
request.
3 Enumeration getHeaderNames()
Returns an enumeration of all the header names this request contains.
4 Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters
contained in this request.
5 HttpSession getSession()
Returns the current session associated with this request, or if the request does not
have a session, creates one.
6 HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if if there is no
current session and create is true, returns a new session.
7 Locale getLocale()
Returns the preferred Locale that the client will accept content in, based on the
Accept-Language header
8 Object getAttribute(String name)
Returns the value of the named attribute as an Object, or null if no attribute of the
given name exists.
9 ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a ServletInputStream.

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.

HTTP Header Request Example:

Following is the example which uses getHeaderNames() method of HttpServletRequest to


read the HTTP header infromation. This method returns an Enumeration that contains the
header information associated with the current HTTP request.

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.

1. <%@ page import="java.io.*,java.util.*" %>


2. <html>
3. <head>
4. <title>HTTP Header Request Example</title>
5. </head>
6. <body>
7. <center>
8. <h2>HTTP Header Request Example</h2>
9. <table width="100%" border="1" align="center">
10. <tr bgcolor="#949494">
11. <th>Header Name</th><th>Header Value(s)</th>
12. </tr>
13. <%

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:

HTTP Header Request Example


Header Name Header Value(s)
accept */*
accept-language en-us
user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;
Trident/4.0; InfoPath.2; MS-RTC LM 8)
accept-encoding gzip, deflate
host localhost:8080
connection Keep-Alive
cache-control no-cache

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:

<jsp:action_name attribute="value" />

Action elements are basically predefined functions and there are following JSP actions
available:

Syntax Purpose
jsp:include Includes a file at the time the page is requested
jsp:useBean Finds or instantiates a JavaBean
jsp:setProperty Sets the property of a JavaBean
jsp:getProperty Inserts the property of a JavaBean into the output
jsp:forward Forwards the requester to a new page
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.

The <jsp:include> Action

25
ASETL CSE/VI SEM AJP LAB

This action lets you insert files into the page being generated. The syntax looks like this:

1. <jsp:include page="relative URL" flush="true" />

Unlike the include directive, which inserts the file at the time the JSP page is translated into
a servlet, this action inserts the file at the time the page is requested.

Following is the list of attributes associated with include action:

Attribute Description
page The relative URL of the page to be included.
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:

Following is the content of date.jsp file:

1. <p>
2. Today's date: <%= (new java.util.Date()).toLocaleString()%>
3. </p>

Here is the content of main.jsp file:

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:

The include action Example

26
Today's date: 12-Sep-2010 14:54:22

The <jsp:useBean> Action

The useBean action is quite versatile. It first searches for an existing object utilizing the id
and scope variables. If an object is not found, it then tries to create the specified object.

The simplest way to load a bean is as follows:

<jsp:useBean id="name" class="package.class" />

Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to
modify and retrieve bean properties.

Following is the list of attributes associated with useBean action:

Attribute Description
class Designates the full package name of the bean.
type Specifies the type of the variable that will refer to the object.
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 <jsp:setProperty> Action

The setProperty action sets the properties of a Bean. The Bean must have been previously
defined before this action. There are two basic ways to use the setProperty action:

You can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:

1. <jsp:useBean id="myName" ... />


2. ...
3. <jsp:setProperty name="myName" property="someProperty" .../>

In this case, the jsp:setProperty is executed regardless of whether a new bean was
instantiated or an existing bean was found.

A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean
element, as below:

1. <jsp:useBean id="myName" ... >


2. ...

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.

Following is the list of attributes associated with setProperty action:

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 <jsp:getProperty> Action

The getProperty action is used to retrieve the value of a given property and converts it to a
string, and finally inserts it into the output.

The getProperty action has only two attributes, both of which are required ans simple syntax
is as follows:

1. <jsp:useBean id="myName" ... />


2. ...
3. <jsp:getProperty name="myName" property="someProperty" .../>

Following is the list of required attributes associated with setProperty action:

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:

Let us define a test bean which we will use in our 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>

Now try to access main.jsp, it would display following result:

Using JavaBeans in JSP

29
Got message....

Hello JSP...

The <jsp:forward> Action

The forward action terminates the action of the current page and forwards the request to
another resource such as a static page, another JSP page, or a Java Servlet.

The simple syntax of this action is as follows:

1. <jsp:forward page="Relative URL" />

Following is the list of required attributes associated with forward action:

Attribute Description
page Should consist of a relative URL of another resource such as a static page,
another JSP page, or a Java Servlet.

Example:

Let us reuse following two files (a) date.jsp and (b) main.jsp as follows:

Following is the content of date.jsp file:

1. <p>
2. Today's date: <%= (new java.util.Date()).toLocaleString()%>
3. </p>

Here is the content of main.jsp file:

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.

Today's date: 12-Sep-2010 14:54:22

The <jsp:plugin> Action

The plugin action is used to insert Java components into a JSP page. It determines the type
of browser and inserts the <object> or <embed> tags as needed.

If the needed plugin is not present, it downloads the plugin and then executes the Java
component. The Java component can be either an Applet or a JavaBean.

The plugin action has several attributes that correspond to common HTML tags used to
format Java components. The <param> element can also be used to send parameters to the
Applet or Bean.

Following is the typical syntax of using plugin action:

1. <jsp:plugin type="applet" codebase="dirname" code="MyApplet.class"width="60"


height="80">
2. <jsp:param name="fontcolor" value="red" />
3. <jsp:param name="background" value="black" />
4. <jsp:fallback>
5. Unable to initialize Java Plugin
6. </jsp:fallback>
7. </jsp:plugin>

You can try this action using some applet if you are interested. A new element, the
<fallback> element, can be used to specify an error string to be sent to the user in case the
component fails.

The <jsp:element> Action


The <jsp:attribute> Action
The <jsp:body> Action

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.

Following is a simple example to define XML elements dynamically:

1. <%@page language="java" contentType="text/html"%>


2. <html xmlns="http://www.w3c.org/1999/xhtml"
3. xmlns:jsp="http://java.sun.com/JSP/Page">
4. <head><title>Generate XML Element</title></head>
5. <body>
6. <jsp:element name="xmlElement">
7. <jsp:attribute name="xmlElementAttr">
8. Value for the attribute
9. </jsp:attribute>
10. <jsp:body>
11. Body for XML element
12. </jsp:body>
13. </jsp:element>
14. </body>
15. </html>

This would produce following HTML code at run 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.

Annotations used in Stateless Session Bean

There are 3 important annotations used in stateless session bean:

1. @Stateless
2. @PostConstruct
3. @PreDestroy

Life cycle of Stateless Session Bean

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.

Example of Stateless Session Bean

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.

1) Create stateless bean component

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. }

2) Create stateless bean client

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.

Enterprise Beans Defined


An enterprise Bean is a body of code with fields and methods to implement modules of
business logic. Client programs interact with one or more Beans, and an enterprise Bean can
be implemented to interact with other enterprise Beans. An enterprise Bean is a building
block that can be used alone or with other enterprise Beans to build a complete and robust
thin-client multitiered application.

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.

Session Beans Entity Beans


Fields contain conversation state. Represents data in a database.
Handles database access for client. Shares access for multiple users.

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:

CREATE TABLE BONUS


SOCSEC Integer,
BONUS Real,
primary key (SOCSEC)
The source code follows naming conventions so the EJB Home Server can find the
application classes, containers, and database table. For example with The source for a given
enterprise Bean, the enterprise Bean, home interface, and primary key class names use the
remote interface name as a prefix.

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

 Bonus.java, the remote interface with these methods:


 o getBonus
o getSocSec
 o addBonus
 BonusHome.java, the home interface with these
 methods: o create
 o findByPrimaryKey
 BonusBean.java, an enterprise Bean with these public fields and
 methods: o int bonus
o int socsec
o getBonus
o getSocSec
o addBonus
 o ejbCreate
 BonusPK.java, primary key with these fields and methods:
o socsec
o BonusPK

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.*;

8. public class BonusServlet extends HttpServlet {

9. //Entity Bean home and remote interface variables


10. BonusHome homebonus;
11. Bonus theBonus, rec1;

40
12. //Session Bean home and remote interface variables
13. CalcHome homecalc;
14. Calc theCalculation;

15. int socsec = 0, retsocsec = 0;


16. int bonus = 0, retbonus = 0;

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");

20. } catch (Exception NamingException) {


21. NamingException.printStackTrace();
22. }
23. }
In the next code segment, the socsec and bonus variables are initialized with values that
would normally come from user input to a form in the browser. These values are used to
create the entity Bean home interface and two records in the Bonus table. After each record is
created, its data is retrieved from the database and displayed in the browser. For simplicity,
the code to display the data in the browser is not included in the segment, but here is the
entire source file for the BonusServlet.java servlet.

1. try{
2. socsec = 555220000;

41
3. bonus = 200;

4. for(int i = 1; i < 3; i++){


5. // Use the entity Bean home interface to
6. // create a record
7. theBonus = homebonus.create(socsec, bonus);
8. // Get the data from the record and display
9. // it in the browser
10. retbonus = theBonus.getBonus();
11. retsocsec = theBonus.getSocSec();
12. socsec += 1;
13. }
14. } catch (Exception CreateException) {
15. CreateException.printStackTrace();
16. }
This next code segment uses the primary key class to retrieve a record from the database, and
uses the home interface to retrieve the data in the record fields. For simplicity, the code to
display the retrieved data in the browser is not included in the segment, but here is the entire
source file for the BonusServlet.java servlet.

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

Soc Sec: 555220001


Bonus Total: 200

Calculate Bonus for 555220000

Bonus Before: 200


Bonus After: 1200

Entity Bean Source Code


The example entity Bean represents a row in the Bonus table. At runtime, there can be any
number of simultaneous entity Bean instantiations to represent different rows in the table. The
thin-client servlet instantiates two entity Beans to create the two rows in the Bonus table.

socsec (Primary Key) bonus


555220000 200
555220001 200
However, the thin-client servlet does not work directly with the entity Bean to create rows or
access data, but creates an instance of the home interface. The home interface extends
EJBHome and has methods that define how the entity Bean is created and located in its
container. It also follows the rules of the Remote Method Invocation (RMI) API in that the
arguments and return types for each method must be serializable and the methods should
throwjava.rmi.RemoteException as one of its exception.

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.*;

3. public interface Bonus extends EJBObject {


4. int getBonus() throws RemoteException;
5. int getSocSec() throws RemoteException;
6. void addBonus(int bonus ) throws RemoteException;
7. }

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;

2. public class BonusPK implements


3. java.io.Serializable {
4. public int socsec;

5. public BonusPK(int socsec) {


6. this.socsec = socsec;
7. }

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.*;

4. public class BonusBean implements EntityBean {

44
5. public int bonus = 0;
6. public int socsec = 0;
7. protected EntityContext ctx;

8. public int getBonus() throws RemoteException {


9. return bonus;
10. }
11. public int getSocSec() throws RemoteException {
12. return socsec;
13. }

14. public void addBonus(int bonus)


15. throws RemoteException {
16. this.bonus += bonus;
17. }

18. public void ejbCreate(int socsec, int bonus)


19. throws CreateException, RemoteException {
20. this.socsec=socsec;
21. this.bonus=bonus;
22. }

23. // Other interface methods

24. public void setEntityContext(


25. javax.ejb.EntityContext ctx)
26. throws RemoteException
27. {
28. this.ctx = ctx;
29. }
30. public void unsetEntityContext()
31. throws RemoteException {
32. ctx = null;
33. }

34. public void ejbRemove() throws RemoteException,


35. RemoveException { }
36. public void ejbActivate() throws
37. RemoteException { }
38. public void ejbPassivate() throws
39. RemoteException { }
40. public void ejbLoad() throws
41. RemoteException { }
42. public void ejbStore() throws
43. RemoteException { }
44. }

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 {}

30. // Other interface methods


31. public void setSessionContext(
32. javax.ejb.SessionContext ctx)
33. throws RemoteException {
34. this.ctx = ctx;
35. }
36. public void ejbRemove() throws
37. RemoteException { }
38. public void ejbActivate() throws

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.

2) Create input page (index.jsp)


This jsp page creates a form using struts UI tags. To use the struts UI tags, you need to
specify uri /struts-tags. Here, we have used s:form to create a form, s:textfield to create a text
field, s:submit to create a submit button.
index.jsp
1. <%@ taglib uri="/struts-tags" prefix="s" %>
2. <s:form action="product">
3. <s:textfield name="id" label="Product Id"></s:textfield>
4. <s:textfield name="name" label="Product Name"></s:textfield>

48
5. <s:textfield name="price" label="Product Price"></s:textfield>
6. <s:submit value="save"></s:submit>
7. </s:form>

3) Provide the entry of Controller in (web.xml) file


In struts 2, StrutsPrepareAndExecuteFilter class works as the controller. As we know well,
struts 2 uses filter for the controller. It is implicitly provided by the struts framework.
web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app>
3. <filter>
4. <filter-name>struts2</filter-name>
5. <filter-class>
6. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
7. </filter-class>
8. </filter>
9. <filter-mapping>
10. <filter-name>struts2</filter-name>
11. <url-pattern>/*</url-pattern>
12. </filter-mapping>
13. </web-app>

4) Create the action class (Product.java)


This is simple bean class. In struts 2, action is POJO (Plain Old Java Object). It has one extra
method execute i.e. invoked by struts framework by default.
Product.java
1. package com.javatpoint;
2. public class Product {
3. private int id;
4. private String name;
5. private float price;
6. public int getId() {
7. return id;
8. }
9. public void setId(int id) {
10. this.id = id;
11. }
12. public String getName() {
13. return name;
14. }
15. public void setName(String name) {
16. this.name = name;

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/>

7) Load the jar files


To run this application, you need to have the struts 2 jar files. Here, we are providing all the
necessary jar files for struts 2. Download it and put these jar files in the lib folder of your
project.
8) start server and deploy the project
Finally, start the server and deploy the project and access it.

51
Experiment 9:- Develop an application to implement RMI based Calculator
Theory:

RMI (Remote Method Invocation)

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.

Understanding 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.

Understanding requirements for the distributed applications


If any application performs these tasks, it can be distributed application.
.
1. The application need to locate the remote method
2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.
The RMI application have all these features, so it is called the distributed
application. RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application. The
client application need only two files, remote interface and client application. In the rmi
application, both client and server interacts with the remote interface. The client application
invokes methods on the proxy object, RMI sends the request to the remote JVM. The return
value is sent back to the proxy object and then to the client application.

1) create the remote interface


For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface. Here, we are creating a
remote interface that extends the Remote interface. There is only one method named add()
and it declares RemoteException.
1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }
2) Provide the implementation of the remote interface
Now provide the implementation of the remote interface. For providing the implementation
of the Remote interface, we need to
o Either extend the UnicastRemoteObject class,
o or use the exportObject() method of the UnicastRemoteObject class
In case, you extend the UnicastRemoteObject class, you must define a constructor that
declares RemoteException.
1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AdderRemote extends UnicastRemoteObject implements Adder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }

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

4) Start the registry service by the rmiregistry tool


Now start the registry service by using the rmiregistry tool. If you don't specify the port
number, it uses a default port number. In this example, we are using the port number 5000.
rmiregistry 5000

5) Create and run the server application


Now rmi services need to be hosted in a server process. The Naming class provides methods
to get and store the remote object. The Naming class provides 5 methods.
public static java.rmi.Remote lookup(java.lang.String) It returns the
throws java.rmi.NotBoundException, reference of the
java.net.MalformedURLException, remote object.
java.rmi.RemoteException;
public static void bind(java.lang.String, java.rmi.Remote) It binds the remote
throws java.rmi.AlreadyBoundException, object with the given
java.net.MalformedURLException, name.
java.rmi.RemoteException;
public static void unbind(java.lang.String) throws It destroys the remote
java.rmi.RemoteException, java.rmi.NotBoundException, object which is bound
java.net.MalformedURLException; with the given name.
public static void rebind(java.lang.String, java.rmi.Remote) It binds the remote
throws java.rmi.RemoteException, object to the new
java.net.MalformedURLException; name.
public static java.lang.String[] list(java.lang.String) throws It returns an array of
java.rmi.RemoteException, the names of the
java.net.MalformedURLException; remote objects bound
in the registry.
In this example, we are binding the remote object by the name sonoo.
1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }

6) Create and run the client application


At the client we are getting the stub object by the lookup() method of the Naming class and
invoking the method on this object. In this example, we are running the server and client
applications, in the same machine so we are using localhost. If you want to access the remote
object from another machine, change the localhost to the host name (or IP address) where the
remote object is located.
1. import java.rmi.*;
2. public class MyClient{
3. public static void main(String args[]){
4. try{
5. Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
6. System.out.println(stub.add(34,4));
7. }catch(Exception e){}
8. }
9. }

For running this rmi example,


1) compile all the java files
javac *.java

2)create stub and skeleton object by rmic tool


rmic AdderRemote

3)start rmi registry in one command prompt


rmiregistry 5000

4)start the server in another command prompt


java MyServer

5)start the client application in another command prompt


java MyClient
Interface //RMICalIntf.java
import java.rmi.*;
import java.rmi.server.*;
public interface RMICalIntf extends Remote
{ //Declaring the methods to be implemented
double add(double a,double b) throws RemoteException;
double sub(double a,double b) throws RemoteException;
double mul(double a,double b) throws RemoteException;
double div(double a,double b) throws RemoteException;
}

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);
}
}

Server side //RMICalServer.java


import java.rmi.*;
public class RMICalServer
{
public static void main(String args[])
{
try
{ //creating implementation object
RMICalImpl si = new RMICalImpl();
Naming.rebind("calserver",si);
}
catch(Exception e){}
}
}
Client side //RMICalClient.java
import javax.swing.*;
import java.awt.*;
import java.rmi.*;
import java.awt.event.*;
import java.io.*;
public class RMICalClient extends JFrame implements ActionListener
{
double n1 = 0.0;
double d1;
double n2 = 0.0;
JButton jb[] = new JButton[21];
JTextField tf;
Container con;
int button,i;
String str;
String num="";
JPanel tp,bp; //declaring 2 panels for textfield and buttons
public RMICalClient()
{
setTitle("calculator");
tp = new JPanel();
bp = new JPanel();
tf = new JTextField(22);
tf.setEditable(false);
con = getContentPane();
bp.setLayout(new GridLayout(5,4));
tp.add(tf);
con.add(tp,"North"); //placing the textfield in the north
for(int i=0;i<10;i++) //inserting and numbering buttons
{
jb[i] = new JButton(""+i);
}
jb[10] = new JButton("+");
jb[11] = new JButton("-");
jb[12] = new JButton("*");
jb[13] = new JButton("/");
jb[14] = new JButton("clear");
jb[15] = new JButton(".");
jb[16] = new JButton("=");
for(int i = 0;i<17;i++)
{
jb[i].addActionListener(this);
bp.add(jb[i]);
}
con.add(bp,"Center"); //placing the panel with the buttons in the
center setDefaultCloseOperation(EXIT_ON_CLOSE); }
public void actionPerformed(ActionEvent ae)
{
str = ae.getActionCommand(); //get the text on the button
System.out.println(str);
for(int i=0;i<10;i++)
{
if(ae.getSource()==jb[i])
{
num = num+str; //if the button clicked is a number,
tf.setText(num); // concatenate it to the string “num”
}
}
if((ae.getSource())==jb[15]) //if the button pressed is “.”
{
num = num+str; //concatenate it to num
tf.setText(num);
}
for(int i=10;i<14;i++)
{
if(ae.getSource()==jb[i]) //if the button is an operator
{
button = i-9; //store the operator in “button”
if(num!="") //obtain the first operand
{
tf.setText("");
n1 = Double.parseDouble(num); //convert string in to
num=""; //double & store it in “n1”
}
Else
{
tf.setText("");
}
}
}
if(ae.getSource()==jb[16]) //if the button pressed is “=”
{
if(!(tf.getText().equals("")))
{
tf.setText("");
n2 = Double.parseDouble(num);//store 2nd
operand //in n2
num = "";
try
{
String url = "rmi://localhost/calserver";
RMICalIntf a =(RMICalIntf)
Naming.lookup(url); switch(button)
{
case 1:
d1 = a.add(n1,n2);
break;
case 2:
d1 = a.sub(n1,n2);
break;
case 3:
d1 = a.mul(n1,n2);
break;
case 4:
d1 = a.div(n1,n2);
break;
default:
d1 = 0.0;
}
str = String.valueOf(d1); //convert the //value to string
tf.setText(str); //print the value
}
catch(Exception e){}
}
Else
{
tf.setText("");
}
}
if(ae.getSource()==jb[14]) //if button pressed is “CLEAR”
{
tf.setText("");
num = "";
n1=0.0;
n2=0.0;
button=0;
}
}
public static void main(String args[])
{
JFrame f = new RMICalClient();
f.setSize(200,200);
f.setVisible(true);
}
}

Das könnte Ihnen auch gefallen