[go: up one dir, main page]

0% found this document useful (0 votes)
70 views86 pages

7da70advance Java Lab Manual

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 86

ASETL CSE/VI SEM AJP LAB

IT 404 – ADVANCE JAVA PROGRAMING LABORATORY


LABORATORY MANUAL
FOR VI SEMESTER B.TECH (CSE)
ACADEMIC YEAR (2015-2016)

Prepared & Maintain by


Mr. Vineet Singh
Assistant Professor
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
AMITY SCHOOL OF ENGINEERING & TECHNOLOGY
AMITY UNIVERSITY LUCKNOW CAMPUS

1
ASETL CSE/VI SEM AJP LAB

LIST OF EXPERIMENTS

1. Write a program to provide database connectivity using Type 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
3. Write a program using servlet to write persistent and non-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. Write an android program to connect with SQL Database and perform INSERT,
MODIFY and DELETE operations.

List of Open Ended Program


10. Develop an application to implement RMI based Calculator.
11. Develop an application to authentication, which validate the login-id and password by
the JSP, servlet and database code.

2
ASETL CSE/VI SEM AJP LAB

CONTENTS
LIST OF EXPERIMENTS ......................................................................................................... 2

Experiment 1:- Servlets .............................................................................................................. 4


Experiment 2:- JSP ..................................................................................................................... 9
Experiment 3:- Cookies ............................................................................................................ 14
Experiment 4:- Client Request .................................................................................................. 20
Experiment 5:- JSP Tags .......................................................................................................... 25
Experiment 6:- Session Beans ................................................................................................... 34
Experiment 7:- Entity Bean ...................................................................................................... 37
Experiment 8:- Struts ............................................................................................................... 48
Experiment 9:- Android............................................................................................................ 52

OPEN ENDED EXPERIMENTS .............................................................................................. 73


Experiment 10:- Develop an application to implement RMI based Calculator .......................... 74
Experiment 11:- Develop an application to authentication, which validate the login-id and
password by the JSP, servlet and database code. ...................................................................... 82

3
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

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
ASETL CSE/VI SEM AJP LAB

Experiment 9:- Android


Objective :- Write an android program to connect with SQL Database and perform INSERT,
MODIFY and DELETE operations.

Procedure:-

We will cover the basic CRUD (Create, Read, Update and Delete) Operation. So that you will
be able to handle MySQL Database after going through this experiment.
Creating the MySQL Database

 First create a database table.

Employee Table

 As you can see I have a table named employee with 4 columns (id, name, designation,
salary). Id is set auto increment and primary key so we do not need to insert id.
 Now we will create our php scripts.

Creating PHP Scripts

 The first thing we need is to connect to the database. So create a file


named dbConnect.php and write the following code.

android mysql tutorial

1 <?php
2 /*
3 author: Belal Khan
4 website: https://www.simplifiedcoding.net
5
6 My Database is androiddb
7 you need to change the database name rest the things are default if you are using wamp
8 or xampp server
9 You may need to change the host user name or password if you have changed the
10 defaults in your server
11 */
12

52
ASETL CSE/VI SEM AJP LAB

13 //Defining Constants
14 define('HOST','localhost');
15 define('USER','root');
16 define('PASS','');
17 define('DB','androiddb');
18 //Connecting to Database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

 Now in CRUD the first thing is to insert data (Create)


 So create a file name addEmp.php. This script will add an employee.

addEmp.php
<?php
1
if($_SERVER['REQUEST_METHOD']=='POST'){
2
3
//Getting values
4
$name = $_POST['name'];
5
$desg = $_POST['desg'];
6
$sal = $_POST['salary'];
7
8
//Creating an sql query
9
$sql = "INSERT INTO employee (name,designation,salary) VALUES
10
('$name','$desg','$sal')";
11
12
//Importing our db connection script
13
require_once('dbConnect.php');
14
15
//Executing query to database
16
if(mysqli_query($con,$sql)){
17
echo 'Employee Added Successfully';
18
}else{
19
echo 'Could Not Add Employee';
20
}
21
22
//Closing the database
23
mysqli_close($con);
24
}

 Now after adding an employee we will fetch the name and id of all the employees. So
that user can select a particular employee to see all the details of that employee.
 For this create a new file named getAllEmp.php and write the following code.

getAllEmp.php
1 <?php
2 //Importing Database Script
3 require_once('dbConnect.php');
4
5 //Creating sql query
6 $sql = "SELECT * FROM employee";

53
ASETL CSE/VI SEM AJP LAB

7
8 //getting result
9 $r = mysqli_query($con,$sql);
10
11 //creating a blank array
12 $result = array();
13
14 //looping through all the records fetched
15 while($row = mysqli_fetch_array($r)){
16
17 //Pushing name and id in the blank array created
18 array_push($result,array(
19 "id"=>$row['id'],
20 "name"=>$row['name']
21 ));
22 }
23
24 //Displaying the array in json format
25 echo json_encode(array('result'=>$result));
26
27 mysqli_close($con);

 Now we need to display a selected employee. For this create a new file
named getEmp.php and write the following code.

getEmp.php
1 <?php
2
3 //Getting the requested id
4 $id = $_GET['id'];
5
6 //Importing database
7 require_once('dbConnect.php');
8
9 //Creating sql query with where clause to get an specific employee
10 $sql = "SELECT * FROM employee WHERE id=$id";
11
12 //getting result
13 $r = mysqli_query($con,$sql);
14
15 //pushing result to an array
16 $result = array();
17 $row = mysqli_fetch_array($r);
18 array_push($result,array(
19 "id"=>$row['id'],
20 "name"=>$row['name'],
21 "desg"=>$row['designation'],
22 "salary"=>$row['salary']
23 ));

54
ASETL CSE/VI SEM AJP LAB

24
25 //displaying in json format
26 echo json_encode(array('result'=>$result));
27
28 mysqli_close($con);

 Now in CRUD we have completed (C-Create (Insert) and R-Read(Fetch)) the next
is U-Update. We may need to update the details of an existing employee. For this
create a new file named updateEmp.phpand write the following code.

updateEmp.php
<?php
1
if($_SERVER['REQUEST_METHOD']=='POST'){
2
//Getting values
3
$id = $_POST['id'];
4
$name = $_POST['name'];
5
$desg = $_POST['desg'];
6
$sal = $_POST['salary'];
7
8
//importing database connection script
9
require_once('dbConnect.php');
10
11
//Creating sql query
12
$sql = "UPDATE employee SET name = '$name', designation = '$desg', salary = '$sal'
13
WHERE id = $id;";
14
15
//Updating database table
16
if(mysqli_query($con,$sql)){
17
echo 'Employee Updated Successfully';
18
}else{
19
echo 'Could Not Update Employee Try Again';
20
}
21
22
//closing connection
23
mysqli_close($con);
24
}

 Now the final thing which is D-Delete. We may need to delete an existing employee.
For this create a new file named deleteEmp.php and write the following.

deleteEmp.php
1 <?php
2 //Getting Id
3 $id = $_GET['id'];
4
5 //Importing database
6 require_once('dbConnect.php');
7
8 //Creating sql query

55
ASETL CSE/VI SEM AJP LAB

9 $sql = "DELETE FROM employee WHERE id=$id;";


10
11 //Deleting record in database
12 if(mysqli_query($con,$sql)){
13 echo 'Employee Deleted Successfully';
14 }else{
15 echo 'Could Not Delete Employee Try Again';
16 }
17
18 //closing connection
19 mysqli_close($con);

 Now thats all we have created all the scripts for CRUD operation. Now we need the
address of these scripts. In my case I am using wamp server. And my server is
running in my ip -> http://192.168.94.1
 To know what is the ip in your system you can use ipconfig command. Open
command prompt and write ipconfig and hit enter.

 So we are using wamp server and for wamp the root directory is www (usually
c:/wamp/www). And we stored my scripts inside www/Android/CRUD. So the paths
to my scripts would be

http://192.168.94.1/Android/CRUD/file_name.php

Creating an Android Studio Project

 Create a new Android Studio project. For this Android MySQL Tutorial I have
created my project named MySQLCRUD.
 In this Android MySQL Application we will be performing some network operations
we need internet permission. So add internet permission to your manifest file.

1 <uses-permission android:name="android.permission.INTERNET" />

 Now create a new java class inside your package named Config. And write the
following code.

android mysql tutorial


1 package net.simplifiedcoding.mysqlcrud;
2
3 /**
4 * Created by Belal on 10/24/2015.

56
ASETL CSE/VI SEM AJP LAB

5 */
6 public class Config {
7
8 //Address of our scripts of the CRUD
9 public static final String
10 URL_ADD="http://192.168.94.1/Android/CRUD/addEmp.php";
11 public static final String URL_GET_ALL =
12 "http://192.168.94.1/Android/CRUD/getAllEmp.php";
13 public static final String URL_GET_EMP =
14 "http://192.168.94.1/Android/CRUD/getEmp.php?id=";
15 public static final String URL_UPDATE_EMP =
16 "http://192.168.94.1/Android/CRUD/updateEmp.php";
17 public static final String URL_DELETE_EMP =
18 "http://192.168.94.1/Android/CRUD/deleteEmp.php?id=";
19
20 //Keys that will be used to send the request to php scripts
21 public static final String KEY_EMP_ID = "id";
22 public static final String KEY_EMP_NAME = "name";
23 public static final String KEY_EMP_DESG = "desg";
24 public static final String KEY_EMP_SAL = "salary";
25
26 //JSON Tags
27 public static final String TAG_JSON_ARRAY="result";
28 public static final String TAG_ID = "id";
29 public static final String TAG_NAME = "name";
30 public static final String TAG_DESG = "desg";
public static final String TAG_SAL = "salary";

//employee id to pass with intent


public static final String EMP_ID = "emp_id";
}

 We will create a separate class for handling our networking request. So create a new
class inside your package named RequestHandler. And write the following code.

RequestHandler.java
1 package net.simplifiedcoding.mysqlcrud;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.InputStreamReader;
6 import java.io.OutputStream;
7 import java.io.OutputStreamWriter;
8 import java.io.UnsupportedEncodingException;
9 import java.net.HttpURLConnection;
10 import java.net.URL;
11 import java.net.URLEncoder;
12 import java.util.HashMap;
13 import java.util.Map;

57
ASETL CSE/VI SEM AJP LAB

14
15 import javax.net.ssl.HttpsURLConnection;
16
17 /**
18 * Created by Belal on 10/24/2015.
19 */
20
21 public class RequestHandler {
22
23 //Method to send httpPostRequest
24 //This method is taking two arguments
25 //First argument is the URL of the script to which we will send the request
26 //Other is an HashMap with name value pairs containing the data to be send with the
27 request
28 public String sendPostRequest(String requestURL,
29 HashMap<String, String> postDataParams) {
30 //Creating a URL
31 URL url;
32
33 //StringBuilder object to store the message retrieved from the server
34 StringBuilder sb = new StringBuilder();
35 try {
36 //Initializing Url
37 url = new URL(requestURL);
38
39 //Creating an httmlurl connection
40 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
41
42 //Configuring connection properties
43 conn.setReadTimeout(15000);
44 conn.setConnectTimeout(15000);
45 conn.setRequestMethod("POST");
46 conn.setDoInput(true);
47 conn.setDoOutput(true);
48
49 //Creating an output stream
50 OutputStream os = conn.getOutputStream();
51
52 //Writing parameters to the request
53 //We are using a method getPostDataString which is defined below
54 BufferedWriter writer = new BufferedWriter(
55 new OutputStreamWriter(os, "UTF-8"));
56 writer.write(getPostDataString(postDataParams));
57
58 writer.flush();
59 writer.close();
60 os.close();
61 int responseCode = conn.getResponseCode();
62
63 if (responseCode == HttpsURLConnection.HTTP_OK) {

58
ASETL CSE/VI SEM AJP LAB

64
65 BufferedReader br = new BufferedReader(new
66 InputStreamReader(conn.getInputStream()));
67 sb = new StringBuilder();
68 String response;
69 //Reading server response
70 while ((response = br.readLine()) != null){
71 sb.append(response);
72 }
73 }
74
75 } catch (Exception e) {
76 e.printStackTrace();
77 }
78 return sb.toString();
79 }
80
81 public String sendGetRequest(String requestURL){
82 StringBuilder sb =new StringBuilder();
83 try {
84 URL url = new URL(requestURL);
85 HttpURLConnection con = (HttpURLConnection) url.openConnection();
86 BufferedReader bufferedReader = new BufferedReader(new
87 InputStreamReader(con.getInputStream()));
88
89 String s;
90 while((s=bufferedReader.readLine())!=null){
91 sb.append(s+"\n");
92 }
93 }catch(Exception e){
94 }
95 return sb.toString();
96 }
97
98 public String sendGetRequestParam(String requestURL, String id){
99 StringBuilder sb =new StringBuilder();
100 try {
101 URL url = new URL(requestURL+id);
102 HttpURLConnection con = (HttpURLConnection) url.openConnection();
103 BufferedReader bufferedReader = new BufferedReader(new
104 InputStreamReader(con.getInputStream()));
105
106 String s;
107 while((s=bufferedReader.readLine())!=null){
108 sb.append(s+"\n");
109 }
110 }catch(Exception e){
111 }
112 return sb.toString();
113 }

59
ASETL CSE/VI SEM AJP LAB

114
115 private String getPostDataString(HashMap<String, String> params) throws
116 UnsupportedEncodingException {
117 StringBuilder result = new StringBuilder();
118 boolean first = true;
119 for (Map.Entry<String, String> entry : params.entrySet()) {
120 if (first)
121 first = false;
122 else
123 result.append("&");
124
125 result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
126 result.append("=");
127 result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}

return result.toString();
}
}

 For our application we will need two more activities other than our MainActivity.
One is to show the list of all employee from where user can select a particular
employee to see. And the other one is to show the details of selected employee from
where we can update and delete the employee as well. And from
the MainActivity we will add an employee. So before going further create two more
activities named ViewAllEmployee and ViewEmployee.
 Now for activity_main.xml create the following layout

 Use the following xml code for the above layout

android mysql tutorial


1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:orientation="vertical"
5 android:layout_height="match_parent"
6 android:paddingLeft="@dimen/activity_horizontal_margin"
7 android:paddingRight="@dimen/activity_horizontal_margin"

60
ASETL CSE/VI SEM AJP LAB

8 android:paddingTop="@dimen/activity_vertical_margin"
9 android:paddingBottom="@dimen/activity_vertical_margin"
10 tools:context=".MainActivity">
11
12 <TextView
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:text="Employee Name" />
16
17 <EditText
18 android:layout_width="match_parent"
19 android:layout_height="wrap_content"
20 android:id="@+id/editTextName" />
21
22 <TextView
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:text="Designation" />
26
27 <EditText
28 android:layout_width="match_parent"
29 android:layout_height="wrap_content"
30 android:id="@+id/editTextDesg" />
31
32 <TextView
33 android:layout_width="wrap_content"
34 android:layout_height="wrap_content"
35 android:text="Salary" />
36
37 <EditText
38 android:layout_width="match_parent"
39 android:layout_height="wrap_content"
40 android:id="@+id/editTextSalary" />
41
42 <Button
43 android:layout_width="match_parent"
44 android:layout_height="wrap_content"
45 android:text="Add Employee"
46 android:id="@+id/buttonAdd" />
47
48 <Button
49 android:layout_width="match_parent"
50 android:layout_height="wrap_content"
51 android:text="View Employee"
android:id="@+id/buttonView" />

</LinearLayout>

 Write the following code in MainActivity.java

61
ASETL CSE/VI SEM AJP LAB

MainActivity.java
1 package net.simplifiedcoding.mysqlcrud;
2
3 import android.app.ProgressDialog;
4 import android.content.Intent;
5 import android.os.AsyncTask;
6 import android.support.v7.app.AppCompatActivity;
7 import android.os.Bundle;
8 import android.view.Menu;
9 import android.view.MenuItem;
10 import android.view.View;
11 import android.widget.Button;
12 import android.widget.EditText;
13 import android.widget.Toast;
14
15 import java.util.HashMap;
16
17 public class MainActivity extends AppCompatActivity implements
18 View.OnClickListener{
19
20 //Defining views
21 private EditText editTextName;
22 private EditText editTextDesg;
23 private EditText editTextSal;
24
25 private Button buttonAdd;
26 private Button buttonView;
27
28 @Override
29 protected void onCreate(Bundle savedInstanceState) {
30 super.onCreate(savedInstanceState);
31 setContentView(R.layout.activity_main);
32
33 //Initializing views
34 editTextName = (EditText) findViewById(R.id.editTextName);
35 editTextDesg = (EditText) findViewById(R.id.editTextDesg);
36 editTextSal = (EditText) findViewById(R.id.editTextSalary);
37
38 buttonAdd = (Button) findViewById(R.id.buttonAdd);
39 buttonView = (Button) findViewById(R.id.buttonView);
40
41 //Setting listeners to button
42 buttonAdd.setOnClickListener(this);
43 buttonView.setOnClickListener(this);
44 }
45
46
47 //Adding an employee
48 private void addEmployee(){
49

62
ASETL CSE/VI SEM AJP LAB

50 final String name = editTextName.getText().toString().trim();


51 final String desg = editTextDesg.getText().toString().trim();
52 final String sal = editTextSal.getText().toString().trim();
53
54 class AddEmployee extends AsyncTask<Void,Void,String>{
55
56 ProgressDialog loading;
57
58 @Override
59 protected void onPreExecute() {
60 super.onPreExecute();
61 loading =
62 ProgressDialog.show(MainActivity.this,"Adding...","Wait...",false,false);
63 }
64
65 @Override
66 protected void onPostExecute(String s) {
67 super.onPostExecute(s);
68 loading.dismiss();
69 Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
70 }
71
72 @Override
73 protected String doInBackground(Void... v) {
74 HashMap<String,String> params = new HashMap<>();
75 params.put(Config.KEY_EMP_NAME,name);
76 params.put(Config.KEY_EMP_DESG,desg);
77 params.put(Config.KEY_EMP_SAL,sal);
78
79 RequestHandler rh = new RequestHandler();
80 String res = rh.sendPostRequest(Config.URL_ADD, params);
81 return res;
82 }
83 }
84
85 AddEmployee ae = new AddEmployee();
86 ae.execute();
87 }
88
89 @Override
90 public void onClick(View v) {
91 if(v == buttonAdd){
92 addEmployee();
93 }
94
95 if(v == buttonView){
96 startActivity(new Intent(this,ViewAllEmployee.class));
97 }
}
}

63
ASETL CSE/VI SEM AJP LAB

 Now from this activity we will move to the activity ViewAllEmployee. So create the
following layout in ViewAllEmployee’s layout file which
is activity_view_all_employee.xml.
 In this activity we will create a ListView only.

 You can use the following code for the above layout

android mysql tutorial


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
1 xmlns:tools="http://schemas.android.com/tools"
2 android:layout_width="match_parent"
3 android:orientation="vertical"
4 android:layout_height="match_parent"
5 android:paddingLeft="@dimen/activity_horizontal_margin"
6 android:paddingRight="@dimen/activity_horizontal_margin"
7 android:paddingTop="@dimen/activity_vertical_margin"
8 android:paddingBottom="@dimen/activity_vertical_margin"
9 tools:context="net.simplifiedcoding.mysqlcrud.ViewAllEmployee">
10
11
12 <ListView
13 android:layout_width="match_parent"
14 android:layout_height="wrap_content"
15 android:id="@+id/listView" />
16
17
</LinearLayout>

 Because we are creating a ListView, we need one more Layout Resource File for our
ListView. Inside layouts create a new xml file named list_item.xml and write the
following code.

64
ASETL CSE/VI SEM AJP LAB

android mysql tutorial


1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical" android:layout_width="match_parent"
4 android:layout_height="match_parent">
5
6 <TextView
7 android:id="@+id/id"
8 android:layout_width="wrap_content"
9 android:layout_height="wrap_content" />
10
11 <TextView
12 android:id="@+id/name"
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content" />
15
16 </LinearLayout>

 Now write the following code in ViewAllEmployee.java

Java
1 package net.simplifiedcoding.mysqlcrud;
2
3 import android.app.ProgressDialog;
4 import android.content.Intent;
5 import android.os.AsyncTask;
6 import android.support.v7.app.AppCompatActivity;
7 import android.os.Bundle;
8 import android.view.Menu;
9 import android.view.MenuItem;
10 import android.view.View;
11 import android.widget.AdapterView;
12 import android.widget.ListAdapter;
13 import android.widget.ListView;
14 import android.widget.SimpleAdapter;
15 import android.widget.Toast;
16
17 import org.json.JSONArray;
18 import org.json.JSONException;
19 import org.json.JSONObject;
20
21 import java.util.ArrayList;
22 import java.util.HashMap;
23
24 public class ViewAllEmployee extends AppCompatActivity implements
25 ListView.OnItemClickListener {
26
27 private ListView listView;
28

65
ASETL CSE/VI SEM AJP LAB

29 private String JSON_STRING;


30
31 @Override
32 protected void onCreate(Bundle savedInstanceState) {
33 super.onCreate(savedInstanceState);
34 setContentView(R.layout.activity_view_all_employee);
35 listView = (ListView) findViewById(R.id.listView);
36 listView.setOnItemClickListener(this);
37 getJSON();
38 }
39
40
41 private void showEmployee(){
42 JSONObject jsonObject = null;
43 ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,
44 String>>();
45 try {
46 jsonObject = new JSONObject(JSON_STRING);
47 JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
48
49 for(int i = 0; i<result.length(); i++){
50 JSONObject jo = result.getJSONObject(i);
51 String id = jo.getString(Config.TAG_ID);
52 String name = jo.getString(Config.TAG_NAME);
53
54 HashMap<String,String> employees = new HashMap<>();
55 employees.put(Config.TAG_ID,id);
56 employees.put(Config.TAG_NAME,name);
57 list.add(employees);
58 }
59
60 } catch (JSONException e) {
61 e.printStackTrace();
62 }
63
64 ListAdapter adapter = new SimpleAdapter(
65 ViewAllEmployee.this, list, R.layout.list_item,
66 new String[]{Config.TAG_ID,Config.TAG_NAME},
67 new int[]{R.id.id, R.id.name});
68
69 listView.setAdapter(adapter);
70 }
71
72 private void getJSON(){
73 class GetJSON extends AsyncTask<Void,Void,String>{
74
75 ProgressDialog loading;
76 @Override
77 protected void onPreExecute() {
78 super.onPreExecute();

66
ASETL CSE/VI SEM AJP LAB

79 loading = ProgressDialog.show(ViewAllEmployee.this,"Fetching
80 Data","Wait...",false,false);
81 }
82
83 @Override
84 protected void onPostExecute(String s) {
85 super.onPostExecute(s);
86 loading.dismiss();
87 JSON_STRING = s;
88 showEmployee();
89 }
90
91 @Override
92 protected String doInBackground(Void... params) {
93 RequestHandler rh = new RequestHandler();
94 String s = rh.sendGetRequest(Config.URL_GET_ALL);
95 return s;
96 }
97 }
98 GetJSON gj = new GetJSON();
99 gj.execute();
100 }
101
102 @Override
103 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
104 Intent intent = new Intent(this, ViewEmployee.class);
105 HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
106 String empId = map.get(Config.TAG_ID).toString();
107 intent.putExtra(Config.EMP_ID,empId);
startActivity(intent);
}
}

 Now from this screen user can select a particular employee to see the detail. And from
this activity we will move to the next activity where we can delete or update
employee. So create following layout for your activity ViewEmployee. For this
activity I have activity_view_employee.xml . So we will create the following layout.

67
ASETL CSE/VI SEM AJP LAB

 Write the following code in ViewEmployee.java

ViewEmployee.java
1 package net.simplifiedcoding.mysqlcrud;
2
3 import android.app.ProgressDialog;
4 import android.content.DialogInterface;
5 import android.content.Intent;
6 import android.os.AsyncTask;
7 import android.support.v7.app.AlertDialog;
8 import android.support.v7.app.AppCompatActivity;
9 import android.os.Bundle;
10 import android.view.Menu;
11 import android.view.MenuItem;
12 import android.view.View;
13 import android.widget.Button;
14 import android.widget.EditText;
15 import android.widget.Toast;
16
17 import org.json.JSONArray;
18 import org.json.JSONException;
19 import org.json.JSONObject;
20
21 import java.util.HashMap;
22
23 public class ViewEmployee extends AppCompatActivity implements
24 View.OnClickListener {
25
26 private EditText editTextId;
27 private EditText editTextName;
28 private EditText editTextDesg;
29 private EditText editTextSalary;
30
31 private Button buttonUpdate;
32 private Button buttonDelete;
33

68
ASETL CSE/VI SEM AJP LAB

34 private String id;


35
36 @Override
37 protected void onCreate(Bundle savedInstanceState) {
38 super.onCreate(savedInstanceState);
39 setContentView(R.layout.activity_view_employee);
40
41 Intent intent = getIntent();
42
43 id = intent.getStringExtra(Config.EMP_ID);
44
45 editTextId = (EditText) findViewById(R.id.editTextId);
46 editTextName = (EditText) findViewById(R.id.editTextName);
47 editTextDesg = (EditText) findViewById(R.id.editTextDesg);
48 editTextSalary = (EditText) findViewById(R.id.editTextSalary);
49
50 buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
51 buttonDelete = (Button) findViewById(R.id.buttonDelete);
52
53 buttonUpdate.setOnClickListener(this);
54 buttonDelete.setOnClickListener(this);
55
56 editTextId.setText(id);
57
58 getEmployee();
59 }
60
61 private void getEmployee(){
62 class GetEmployee extends AsyncTask<Void,Void,String>{
63 ProgressDialog loading;
64 @Override
65 protected void onPreExecute() {
66 super.onPreExecute();
67 loading =
68 ProgressDialog.show(ViewEmployee.this,"Fetching...","Wait...",false,false);
69 }
70
71 @Override
72 protected void onPostExecute(String s) {
73 super.onPostExecute(s);
74 loading.dismiss();
75 showEmployee(s);
76 }
77
78 @Override
79 protected String doInBackground(Void... params) {
80 RequestHandler rh = new RequestHandler();
81 String s = rh.sendGetRequestParam(Config.URL_GET_EMP,id);
82 return s;
83 }

69
ASETL CSE/VI SEM AJP LAB

84 }
85 GetEmployee ge = new GetEmployee();
86 ge.execute();
87 }
88
89 private void showEmployee(String json){
90 try {
91 JSONObject jsonObject = new JSONObject(json);
92 JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
93 JSONObject c = result.getJSONObject(0);
94 String name = c.getString(Config.TAG_NAME);
95 String desg = c.getString(Config.TAG_DESG);
96 String sal = c.getString(Config.TAG_SAL);
97
98 editTextName.setText(name);
99 editTextDesg.setText(desg);
100 editTextSalary.setText(sal);
101
102 } catch (JSONException e) {
103 e.printStackTrace();
104 }
105 }
106
107
108 private void updateEmployee(){
109 final String name = editTextName.getText().toString().trim();
110 final String desg = editTextDesg.getText().toString().trim();
111 final String salary = editTextSalary.getText().toString().trim();
112
113 class UpdateEmployee extends AsyncTask<Void,Void,String>{
114 ProgressDialog loading;
115 @Override
116 protected void onPreExecute() {
117 super.onPreExecute();
118 loading =
119 ProgressDialog.show(ViewEmployee.this,"Updating...","Wait...",false,false);
120 }
121
122 @Override
123 protected void onPostExecute(String s) {
124 super.onPostExecute(s);
125 loading.dismiss();
126 Toast.makeText(ViewEmployee.this,s,Toast.LENGTH_LONG).show();
127 }
128
129 @Override
130 protected String doInBackground(Void... params) {
131 HashMap<String,String> hashMap = new HashMap<>();
132 hashMap.put(Config.KEY_EMP_ID,id);
133 hashMap.put(Config.KEY_EMP_NAME,name);

70
ASETL CSE/VI SEM AJP LAB

134 hashMap.put(Config.KEY_EMP_DESG,desg);
135 hashMap.put(Config.KEY_EMP_SAL,salary);
136
137 RequestHandler rh = new RequestHandler();
138
139 String s = rh.sendPostRequest(Config.URL_UPDATE_EMP,hashMap);
140
141 return s;
142 }
143 }
144
145 UpdateEmployee ue = new UpdateEmployee();
146 ue.execute();
147 }
148
149 private void deleteEmployee(){
150 class DeleteEmployee extends AsyncTask<Void,Void,String> {
151 ProgressDialog loading;
152
153 @Override
154 protected void onPreExecute() {
155 super.onPreExecute();
156 loading = ProgressDialog.show(ViewEmployee.this, "Updating...", "Wait...",
157 false, false);
158 }
159
160 @Override
161 protected void onPostExecute(String s) {
162 super.onPostExecute(s);
163 loading.dismiss();
164 Toast.makeText(ViewEmployee.this, s, Toast.LENGTH_LONG).show();
165 }
166
167 @Override
168 protected String doInBackground(Void... params) {
169 RequestHandler rh = new RequestHandler();
170 String s = rh.sendGetRequestParam(Config.URL_DELETE_EMP, id);
171 return s;
172 }
173 }
174
175 DeleteEmployee de = new DeleteEmployee();
176 de.execute();
177 }
178
179 private void confirmDeleteEmployee(){
180 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
181 alertDialogBuilder.setMessage("Are you sure you want to delete this employee?");
182
183 alertDialogBuilder.setPositiveButton("Yes",

71
ASETL CSE/VI SEM AJP LAB

184 new DialogInterface.OnClickListener() {


185 @Override
186 public void onClick(DialogInterface arg0, int arg1) {
187 deleteEmployee();
188 startActivity(new Intent(ViewEmployee.this,ViewAllEmployee.class));
189 }
190 });
191
192 alertDialogBuilder.setNegativeButton("No",
193 new DialogInterface.OnClickListener() {
194 @Override
195 public void onClick(DialogInterface arg0, int arg1) {
196
197 }
198 });
199
200 AlertDialog alertDialog = alertDialogBuilder.create();
201 alertDialog.show();
202 }
203
204 @Override
205 public void onClick(View v) {
206 if(v == buttonUpdate){
207 updateEmployee();
208 }
209
210 if(v == buttonDelete){
confirmDeleteEmployee();
}
}
}

 Now try running your application and you will see the following output.

72
ASETL CSE/VI SEM AJP LAB

OPEN ENDED EXPERIMENTS

73
ASETL CSE/VI SEM AJP LAB

Experiment 10:- 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

74
ASETL CSE/VI SEM AJP LAB

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

75
ASETL CSE/VI SEM AJP LAB

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.

76
ASETL CSE/VI SEM AJP LAB

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

77
ASETL CSE/VI SEM AJP LAB

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

78
ASETL CSE/VI SEM AJP LAB

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

79
ASETL CSE/VI SEM AJP LAB

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

80
ASETL CSE/VI SEM AJP LAB

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

81
ASETL CSE/VI SEM AJP LAB

Experiment 11:- Develop an application to authentication, which validate


the login-id and password by the JSP, servlet and database code.
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:

7. CREATE TABLE "USER432"


8. ( "NAME" VARCHAR2(4000),
9. "EMAIL" VARCHAR2(4000),
10. "PASS" VARCHAR2(4000)
11. )
12. /
We assume that there are many records in this table.

index.jsp

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

4. <a href="login.jsp">login</a>|
5. <a href="logout.jsp">logout</a>|
6. <a href="profile.jsp">profile</a>

82
ASETL CSE/VI SEM AJP LAB

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.

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


22. <hr/>
23.
24. <h3>Login Form</h3>
25. <%
26. String profile_msg=(String)request.getAttribute("profile_msg");
27. if(profile_msg!=null){
28. out.print(profile_msg);
29. }
30. String login_msg=(String)request.getAttribute("login_msg");
31. if(login_msg!=null){
32. out.print(login_msg);
33. }
34. %>
35. <br/>
36. <form action="loginprocess.jsp" method="post">
37. Email:<input type="text" name="email"/><br/><br/>
38. Password:<input type="password" name="password"/><br/><br/>
39. <input type="submit" value="login"/>"
40. </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.

20. <%@page import="bean.LoginDao"%>


21. <jsp:useBean id="obj" class="bean.LoginBean"/>
22.
23. <jsp:setProperty property="*" name="obj"/>
24.
25. <%
26. boolean status=LoginDao.validate(obj);
27. if(status){
28. out.println("You r successfully logged in");

83
ASETL CSE/VI SEM AJP LAB

29. session.setAttribute("session","TRUE");
30. }
31. else
32. {
33. out.print("Sorry, email or password error");
34. %>
35. <jsp:include page="index.jsp"></jsp:include>
36. <%
37. }
38. %>

LoginBean.java

It is the bean class that have 2 properties email and pass with its setter and getter methods.

24. package bean;


25.
26. public class LoginBean {
27. private String email,pass;
28.
29. public String getEmail() {
30. return email;
31. }
32.
33. public void setEmail(String email) {
34. this.email = email;
35. }
36.
37. public String getPass() {
38. return pass;
39. }
40.
41. public void setPass(String pass) {
42. this.pass = pass;
43. }
44.
45.
46. }

84
ASETL CSE/VI SEM AJP LAB

Provider.java

This interface contains four constants that may differ from database to database.

10. package bean;


11.
12. public interface Provider {
13. String DRIVER="oracle.jdbc.driver.OracleDriver";
14. String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";
15. String USERNAME="system";
16. String PASSWORD="oracle";
17.
18. }

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.

19. package bean;


20. import java.sql.*;
21. import static bean.Provider.*;
22.
23. public class ConnectionProvider {
24. private static Connection con=null;
25. static{
26. try{
27. Class.forName(DRIVER);
28. con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD
);
29. }catch(Exception e){}
30. }
31.
32. public static Connection getCon(){
33. return con;
34. }
35.
36. }

85
ASETL CSE/VI SEM AJP LAB

LoginDao.java

This class varifies the emailid and password.

25. package bean;


26. import java.sql.*;
27. public class LoginDao {
28.
29. public static boolean validate(LoginBean bean){
30. boolean status=false;
31. try{
32. Connection con=ConnectionProvider.getCon();
33.
34. PreparedStatement ps=con.prepareStatement(
35. "select * from user432 where email=? and pass=?");
36.
37. ps.setString(1,bean.getEmail());
38. ps.setString(2, bean.getPass());
39.
40. ResultSet rs=ps.executeQuery();
41. status=rs.next();
42.
43. }catch(Exception e){}
44.
45. return status;
46.
47. }
48. }

86

You might also like