[go: up one dir, main page]

0% found this document useful (0 votes)
284 views83 pages

J2EE Lab Manual

This document is a lab manual for an Advanced Java programming course. It provides instructions on how to connect to a MySQL database from a Java program and perform various SQL queries like insertion, selection, updates and deletions. The program code provided demonstrates how to load the MySQL driver, establish a database connection, create SQL statements and execute queries to retrieve and display results from the database. The manual aims to teach students how to execute different types of SQL statements from a Java program to interact with a MySQL database.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
284 views83 pages

J2EE Lab Manual

This document is a lab manual for an Advanced Java programming course. It provides instructions on how to connect to a MySQL database from a Java program and perform various SQL queries like insertion, selection, updates and deletions. The program code provided demonstrates how to load the MySQL driver, establish a database connection, create SQL statements and execute queries to retrieve and display results from the database. The manual aims to teach students how to execute different types of SQL statements from a Java program to interact with a MySQL database.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

BMS INSTITUTE OF TECHNOLOGY, YELAHANKA, BANGALORE-560064

DEPARTMENT OF MCA

LABORATORY MANUAL
SUBJECT: TOPICS IN ENTERPRISE ARCHITECTURE-I / ADVANCED JAVA PROGRAMMING
SUBJECT CODE: 10MCA46 / 13MCA46

PREPARED BY
MR. SHIVAKUMARA T
ASSISTANT PROFESSOR,
DEPARTMENT OF MCA
BMS INSTITUTE OF TECHNOLOGY

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 1


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

BMS Institute of Technology& Management


Doddaballapur Road, Avalahalli, Yelahanka, Bengaluru -560064

Department of MCA
Department Vision
To develop quality professionals in Computer
Applications who can provide sustainable solutions
to the societal and industrial needs

Department Mission
Facilitate effective learning environment through
quality education, state-of-the-art facilities, and
orientation towards research and entrepreneurial
skills

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 2


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

BMS Institute of Technology & Management


Doddaballapur Road, Avalahalli, Yelahanka, Bengaluru - 560064

Department of MCA
Programme Educational Objectives (PEOs)
PEO1: Develop innovative IT applications to meet industrial and societal needs
PEO2: Adapt themselves to changing IT requirements through life-long learning
PEO3: Exhibit leadership skills and advance in their chosen career

Programme Outcomes (POs)


PO1: Apply knowledge of computing fundamentals, computing specialization,
mathematics and domain knowledge to provide IT solutions.
PO2: Identify, analyse and solve IT problems using fundamental principles of
mathematics and computing sciences.
PO3: Design, Develop and evaluate software solutions to meet societal and
environmental concerns.
PO4: Conduct investigations of complex problems using research based knowledge
and methods to provide valid conclusions.
PO5: Select and apply appropriate techniques and modern tools for complex
computing activities.
PO6:Understand professional ethics, cyber regulations and responsibilities.
PO7: Involve in life-long learning for continual development as an IT professional.
PO8: Apply and demonstrate computing and management principles to manage
projects in multidisciplinary environments by involving in different roles
PO9: Comprehend& write effective reports and make quality presentations.
PO10: Understand and assess the impact of IT solutions on socio-environmental
Issues.
PO11: Work collaboratively as a member or leader in multidisciplinary teams.
PO12: Identify potential business opportunities and innovate to create value to the
society and seize that opportunity.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 3


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

f1) Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on
particular queries.

Procedure for Execution.


Step1: Open MySQL and create a database called stud.

Step2: Open the NetBeans 6.9.1 / 7.1 Editor-> Select File->New Project

Step3: Code the java file which is there below (Lab1.java) and save it and compile F9

Step4: Right Click on project folder-> Select properties -> Select Libraries ->Click Add
Jar/Folder button -> find the MYSQL Connector plug-in and click ok.

Step5: Right click on the java file and select run.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 4


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Brief Introduction about the Program:

1. Statement Object: Is used whenever a J2EE component needs to immediately execute a query
without first having the query compiled. It contains the executeQuery() method, which is passed the
query as an argument. The query is then transmitted to the DBMS for processing.

2. The executeQuery() method returns one ResultSet object that contains rows, columns, and
metadata that represent data requested by query.

3. The execute() method of the statement object is used when there may be multiple results returned.

4. The executeUpdate() method is used to execute queries that contain INSERT, UPDATE, DELETE
and DDL statements.

5. PreparedStatement object: A SQL query must be compiled before the DBMS processes the query.
Compiling occurs after one of the Statement object’s execution methods is called.

6. CallableStatement object: Is used to call a stored procedure within a J2EE object. A stored
procedure is a block of code and is identified by a unique name.

7. CallableStatement object uses three types of parameters when calling a stored procedure. These
are IN, OUT, INOUT.

8. Class.forName(“com.mysql.jdbc.Driver”) – Is used to load the JDBC driver.

9. DriverManager.getConnection(url,userID,password) – Method returns a Connection interface


that is used throughout the process to reference the database.

10. java.sql package that manages communication between the driver and the J2EE component.

Program:

package jdbcprg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
public class JdbcPrg
{
private Connection con;
private Statement Datareq;
private ResultSet rs;
public JdbcPrg ()
{
final String url="jdbc:mysql://localhost:3306/stud";
String userid="root";
String password="root";
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(url,userid,password);

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 5


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

}
catch(ClassNotFoundException err)
{
System.err.println("Unable to load the mysql Driver"+err);
System.exit(1);
}
catch(SQLException error1)
{
System.err.println("Cannot connect to the Database"+error1);
System.exit(2);
}
try
{
while(true)
{
System.out.println("\n1.Queries Like:Create table,view,alter,drop,update and delete");
System.out.println("\n2.Queries Like:Insert");
System.out.println("\n3.QueriesLike:Selection/Calculation/GroupBy/OrderBy
/Join/Conditional Testing");
System.out.println("\n4.Exit");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("\nSelect Your Choice");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
try
{
System.out.println("\nQueries Like:Create table,view,alter,drop,update
and delete\n");
String q1=br.readLine();
Datareq=con.createStatement();
Datareq.execute(q1);
System.out.println("\nQuery Executed Successfully\n");
Datareq.close();
}
catch(SQLException sqle)
{
System.err.println(sqle);
}
break;
case 2:
try
{
PreparedStatement pst;
System.out.println("\nQueries Like:Insert\n");
String q2=br.readLine();
pst=con.prepareStatement(q2);
pst.execute();
System.out.println("\nRecods inserted Successfully\n");
pst.close();

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 6


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

}
catch(SQLException e)
{
System.out.println(e);
}
break;
case 3:
try
{
System.out.println("\nQueries Like:Selection/Calculation/GroupBy/OrderBy
/Join/Conditional Testing\n");
String str=br.readLine();
Datareq=con.createStatement();
rs=Datareq.executeQuery(str);
DisplayResult(rs);
Datareq.close();
}
catch(Exception eq)
{
System.err.println(eq);
}
case 4:
System.exit(0);
break;
}
}
}
catch(IOException ioe)
{
System.err.println(ioe);
}
}
private void DisplayResult(ResultSet Result2) throws SQLException
{
ResultSetMetaData rmd=Result2.getMetaData();
int col=rmd.getColumnCount();
int Count=1;
boolean b=Result2.next();
if(!b)
{
System.out.println("\nData Found\n");
}
else
{
do
{
System.out.print("Record"+(Count++)+"=>");
for(int i=0;i<col;i++)
System.out.println(Result2.getString(i+1)+"\t");
System.out.println();
}
while(Result2.next());

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 7


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

}
}
public static void main(String args[])
{
final Lab1 stud1= new Lab1();
}
}

Output:

1.Queries Like:Create table,view,alter,drop,update and delete


2.Queries Like:Insert
3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing
4.Exit

Select Your Choice: 1

Queries Like:Create table,view,alter,drop,update and delete


create table studinfo(usn varchar(10) primary key, name varchar(20));
Query Executed Successfully

1.Queries Like:Create table,view,alter,drop,update and delete


2.Queries Like:Insert
3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing
4.Exit

Select Your Choice: 3

desc studinfo;
Record1=>usn
varchar(10)
NO
PRI

Record2=>name
varchar(20)
YES
Null

1.Queries Like:Create table,view,alter,drop,update and delete


2.Queries Like:Insert
3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing
4.Exit

Select Your Choice: 2

Queries Like:Insert

insert into studinfo values('1BYMCA','SHIVAKUMARA T');


Recods inserted Successfully

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 8


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

1.Queries Like:Create table,view,alter,drop,update and delete


2.Queries Like:Insert
3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing
4.Exit

Select Your Choice3

Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing

select * from studinfo;


Record1=>1BYMCA
SHIVAKUMARA T

1.Queries Like:Create table,view,alter,drop,update and delete


2.Queries Like:Insert
3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing
4.Exit

Select Your Choice: 1

Queries Like:Create table,view,alter,drop,update and delete

Alter table studinfo add column course varchar(10);


Query Executed Successfully

1.Queries Like:Create table,view,alter,drop,update and delete


2.Queries Like:Insert
3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing
4.Exit

Select Your Choice: 1

Queries Like:Create table,view,alter,drop,update and delete

update studinfo set course='MCA' where usn='1BYMCA';


Query Executed Successfully

1.Queries Like:Create table,view,alter,drop,update and delete


2.Queries Like:Insert
3.Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing
4.Exit

Select Your Choice: 3

Queries Like:Selection/Calculation/GroupBy/OrderBy/Join/Conditional Testing

select * from studinfo;


Record1=>1BYMCA
SHIVAKUMARA T
MCA

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 9


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

2) Write a JAVA Servlet Program to implement a dynamic HTML using Servlet (user name and
password should be accepted using HTML and displayed using a Servlet).

Procedure for Execution.

Step1.:Open the NetBeans 6.9.1 Editor-> Select File->New Project


Step2: Select Java Web Folder in Categories-> Select Web Application option-> click Next
Step3: Give the project name and select Main project check box ->click Next.

Step 4. Select the Server-Tomcat-> Click Next -> Click Finish

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 10


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Step 5:Right Click the WebPages folder and select new then select html -> Give the name of
HTML file -> Click finish.

Step6: Code the HTML file and save it.


Step 7: Right Click on project folder-> Select New -> Select Servlet -> Give the name of Servlet
and package name-> Click next.

Step 8:Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will
create the web.xml descriptor file for our Servlet -> Click finish -> Code the Servlet file
Step 9.:Right click on the HTML file and select run.

Brief Introduction.

1. Servlet – is a server side program. A Java Servlet is a Java class that reads requests sent from a
client and responds by sending information to the client.

2. Java class must extend Httpservlet and override Httpservlet’s doGet() or doPost() methods.

3. doGet() or doPost() methods require two arguments. The HttpServletRequest object and
HttpServletResponse object arguments.
4. HttpServletRequest object contains incoming information and HttpServletResponse object is used
by the java servlet to send outgoing information to the client.

5. Both method throws a servletException and IOException,

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 11


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Program:

//Prog2.html

<html>
<head>
<title> Display Username and Password using Servlet </title> </head>
<body bgcolor="pink">
<form method="post" action="Prog2Servlet">
Username <input type="text" name="username" size="35">
Password <input type="password" name="password" size="35"><br/>
<input type="submit" value="Submit"/>
<input type="reset" value="Reser">
</form>
</body>
</html>

//Prog2Servlet.java

package mypackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Prog2Servlet extends HttpServlet
{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();
String uname=req.getParameter("username");
String pass=req.getParameter("password");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet prog2servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>User Information</h1>");
out.println("<br><hr1><br/>");
out.println("<h3>Dear user your information<br/><br/>");
out.println("Username: "+uname+"<br/>");
out.println("Password: "+pass+"<br/></h3>");
out.println("</body>");
out.println("</html>");
}
}

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 12


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

//Web.xml

<web-app>
<servlet>
<servlet-name>Prog2Servlet</servlet-name>
<servlet-class>mypackage.Prog2Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Prog2Servlet</servlet-name>
<url-pattern>/Prog2Servlet</url-pattern>
</servlet-mapping>
</web-app>

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 13


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

3) Write a JAVA Servlet Program to Download a file and display it on the screen (A link has to
be provided in HTML, when the link is clicked corresponding file has to be displayed on
Screen).

Procedure for Execution.

1. Open the NetBeans 7.1 Editor-> Select File->New Project


2. Select Java Web Folder in Categories-> Select Web Application option-> click Next
3. Give the project name and select Main project check box ->click Next.

4. Select the Server-Tomcat-> Click Next -> Click Finish


5. Right Click the WebPages folder and select new then select html -> Give the name of
HTML file -> Click finish.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 14


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

6. Code the HTML file and save it.


7. Right Click on project folder-> Select New -> Select Servlet -> Give the name of Servlet
and package name-> Click next

8. Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will
create the web.xml descriptor file for our Servlet -> Click finish -> Code the Servlet file
9. Right click on the HTML file and select run.

Program:

//Prog3.html
<html>
<head>
<title> File Download </title>
</head>
<body>
<center>
<h1> The File Download Program</h1>
</center>
<a href="Prog3Servlet"> click here to download the file </a>
</body>
</html>

//Prog3Servlet.java
package mypackage;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Prog3Servlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
ServletContext sc = getServletContext();
String filename = sc.getRealPath("Test.txt");
String mimeType = sc.getMimeType(filename);
if (mimeType == null)
{
BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 15
ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

sc.log("Could not get MIME type of "+filename);


resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mimeType);
File file = new File(filename);
resp.setContentLength((int)file.length());
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0)
{
out.write(buf, 0, count);
}
in.close();
out.close();
}
}

//Web.xml

<web-app>
<servlet>
<servlet-name>Prog3Servlet</servlet-name>
<servlet-class>mypackage.Prog3Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Prog3Servlet</servlet-name>
<url-pattern>/Prog3Servlet</url-pattern>
</servlet-mapping>
</web-app>

//Test.txt

You fool nothing is there to Download.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 16


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 17


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

4) Write a JAVA Servlet Program to implement RequestDispatcher object (use include() and
forward() methods).

Procedure for Execution.

Step1. Open the NetBean 7.1 Editor-> Select File->New Project


Step 2. Select Java Web Folder in Categories-> Select Web Application option-> click Next
Step 3. Give the project name and select Main project check box ->click Next.

Step 4. Select the Server-Tomcat-> Click Next -> Click Finish


Step 5. Right Click the webpages folder and select new then select html -> Give the name of
HTML file -> Click finish.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 18


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Step 6. Code the HTML file and save it.


Step 7.1. Right Click on project folder-> Select New -> Select Servlet -> Give the name of Servlet
and package name-> Click next.

Step 7. 2.Right Click on project folder-> Select New -> Select Servlet -> Give the name of Servlet
and package name-> Click next.

Step 8. Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will
create the web.xml descriptor file for our Servlet -> Click finish -> Code the Servlet file
Step 9. Right click on the HTML file and select run.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 19


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Brief Introduction

1. RequestDispatcher class is mainly used to 'pass on' the current request to another program
(servlet) and therefore allows 'chaining' of the programs. A RequestDispatcher primarily contains two
methods include() and forward(). include() method includes the response of another program while
forward() method forwards the request of the current program to another one.

2. forward(): The forward() method of RequestDispatcher forwards the request and response objects
of ServletRequest and ServletResponse interface respectively to the path specified in
getRequestDispatcher(String path). The response is sent back to the client therefore the client does
not know about this change of resource on the server. This method helps for communicating between
server resources, (servlet to servlet). Since request and response objects are forwarded to another
resource therefore all request parameters are maintained and available for use. Any code written after
forward(request, response) method will not execute as the request is already forwarded. As the client
is not aware about this forward on the server therefore no history will be stored on the client and as a
result backward and forward buttons does not work. This method is faster as compared to using
sendRedirect because no network round trip to the server and back is required.

3. include(): This method includes the content of a resource in the response. The resource may either
be a servlet, or a JSP page, or an HTML file. This method also enables programmatic server-side
includes. The included servlet can't change the status code or set headers of the response, any attempt
made to do so is ignored. This method can be called at any time. It can only use ServletOutputStream or
Writer of the response object to write the information.

Program:

//Prog4.html

<html>
<head>
<title></title>
</head>
<body bgcolor="violet">
<form action="Prog4Servlet" method="post">
<input type="hidden" name="decider" value="forward"/>
<input type="submit" value="forward"/>
</form>
<form action="Prog4Servlet" method="post">
<input type="hidden" name="decider" value="include"/>
<input type="submit" value="include"/>
</form>
</body>
</html>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 20


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

//Prog4Servlet.java

package mypackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Prog4Servlet extends HttpServlet
{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String decider=request.getParameter("decider");
RequestDispatcher rd=null;
if("forward".equals(decider))
{
rd=request.getRequestDispatcher("RegServlet");
rd.forward(request, response);
}
else
if("include".equals(decider))
{
rd=request.getRequestDispatcher("RegServlet");
rd.include(request, response);
}
PrintWriter out = response.getWriter();
out.println("Welcome to the requestdispatcher i am from requestdispatcher<br/>");
out.println("<br/>I am due to request dispatcher method include<br/>");
}
}

//RegServlet.java

package mypackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 21


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

out.println("<title>Servlet RegServlet</title>");
out.println("</head>");
out.println("<body bgcolor=pink>");
out.print("<p>Hi my name is Ravikumar am from RegServlet</p><br/>");
out.println("</body>");
out.println("</html>");
}
}

//Web.xml

<web-app>
<servlet>
<servlet-name>Prog4Servlet</servlet-name>
<servlet-class>mypackage.Prog4Servlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RegServlet</servlet-name>
<servlet-class>mypackage.RegServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Prog4Servlet</servlet-name>
<url-pattern>/Prog4Servlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RegServlet</servlet-name>
<url-pattern>/RegServlet</url-pattern>
</servlet-mapping>
</web-app>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 22


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 23


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

5) Write a JAVA Servlet Program to implement and demonstrate get() and Post methods(Using
HTTP Servlet Class).

Procedure for Execution.

Step1. Open the NetBean 7.1 Editor-> Select File->New Project


Step 2. Select Java Web Folder in Categories-> Select Web Application option-> click Next
Step 3. Give the project name and select Main project check box ->click Next.

Step 4. Select the Server-Tomcat-> Click Next -> Click Finish


Step 5. Right Click the webpages folder and select new then select html -> Give the name of
HTML file -> Click finish.
Step 6. Code the HTML file and save it.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 24


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Step 7. Right Click on project folder-> Select New -> Select Servlet -> Give the name of Servlet
and package name-> Click next.

Step 8. Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will
create the web.xml descriptor file for our Servlet -> Click finish -> Code the Servlet file
Step 9. Right click on the HTML file and select run.

Brief Introduction

1. The doGet() method is used to interact with a request sent using the method=”GET”
attribute from an HTML form, when passing parameters on the URL like a hyperlink,
The parameters values displayed in that url. A doGet() method is limited with 2k of data to be
Sent.

2. The doPost() method is used to interact with a request sent using the method=”POST”.
Implicitly sends the request parameter values to the servlet. It supports huge amount of
data requests.

Program:
//Prog5.html

<html>
<head>
<title>Illustration of Get and Post methods </title>
</head>
<body>
<form name="md1" action="Prog5GetPostServlet" method="post">
POST method Illustration<br><br>
Username <input type="text" name="username">
Password <input type="password" name="password">
<input type="submit" value="submit">
</form>
<form name="md1" action="Prog5GetPostServlet" method="get">
GET method Illustration<br><br>
Username <input type="text" name="username">

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 25


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Password <input type="password" name="password">


<input type="submit" value="submit">
</form>
</body>
</html>

//Prog5GetPostServlet.java

package mypackage;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Prog5GetPostServlet extends HttpServlet


{
protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,
IOException
{
PrintWriter out=res.getWriter();
String username=req.getParameter("username");
String password=req.getParameter("password");
if(username.length()==0||password.length()==0)
{
out.println("<script type=text/javascript>");
out.println("alert('userid or password couldnot be blank'");
out.println("</script>");
}
else
{
out.println("<html><body>");
out.println("username="+username);
out.println("password="+password);
out.println("</body></html>");
}
}
protected void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,
IOException
{
PrintWriter out=res.getWriter();
String username=req.getParameter("username");
String password=req.getParameter("password");
if(username.length()==0||password.length()==0)
{
out.println("<script type=text/javascript>");
out.println("alert('userid or password couldnot be blank'");
out.println("</script>");
}
else
{

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 26


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

out.println("<html><body>");
out.println("username="+username);
out.println("password="+password);
out.println("</body></html>");
}
}
}
//Web.xml

<web-app>
<servlet>
<servlet-name>Prog5GetPostServlet</servlet-name>
<servlet-class>mypackage.Prog5GetPostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Prog5GetPostServlet</servlet-name>
<url-pattern>/Prog5GetPostServlet</url-pattern>
</servlet-mapping>
</web-app>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 27


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 28


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

6) Write a JAVA Servlet Program to implement sendRedirect() method(using HTTP Servlet


Class).

Procedure for Execution.

Step1. Open the NetBean 7.1 Editor-> Select File->New Project


Step 2. Select Java Web Folder in Categories-> Select Web Application option-> click Next
Step 3. Give the project name and select Main project check box ->click Next.

Step 4. Select the Server-Tomcat-> Click Next -> Click Finish


Step 5. Right Click the webpages folder and select new then select html -> Give the name of
HTML file -> Click finish.
Step 6. Code the HTML file and save it.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 29


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Step 7.1. Right Click on project folder-> Select New -> Select Servlet -> Give the name of Servlet
and package name-> Click next

Step 7.2. Right Click on project folder-> Select New -> Select Servlet -> Give the name of Servlet
and package name-> Click next

Step 8. Observe the Configure Servlet Deployment as Servlet Name and URL pattern; it will
create the web.xml descriptor file for our Servlet -> Click finish -> Code the Servlet file
Step 9. Right click on the HTML file and select run.

Brief Introduction

sendRedirect():When we want that someone else should handle the response of our servlet, then
there we should use sendRedirect() method.
In send Redirect whenever the client makes any request it goes to the container, there the container
decides whether the concerned servlet can handle the request or not. If not then the servlet decides
that the request can be handle by other servlet or jsp. Then the servlet calls the sendRedirect()
method of the response object and sends back the response to the browser along with the status code.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 30


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Then the browser sees the status code and look for that servlet which can now handle the request.
Again the browser makes a new request, but with the name of that servlet which can now handle the
request and the result will be displayed to you by the browser. In all this process the client is unaware
of the processing.

Program:

//Prog6.html

<html>
<head>
<title> SendRedirectPage </title>
</head>
<body bgcolor="pink">
<form method="post" action="Prog6SendRedirectServlet">
<p>Enter username:<input type="text" name="username" size="20"/> </p>
<p>Enter password:<input type="password" name="password" size="10"/></p>
<p>Enter Phone number:<input type="text" name="phoneno" size="10"/></p>
<p><input type="submit" value="submit"/></p>
</form>
</body>
</html>

//Prog6SendRedirectServlet.java

package mypackage;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Prog6SendRedirectServlet extends HttpServlet
{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = req.getParameter("username");
String password = req.getParameter("password");
String phoneno = req.getParameter("phoneno");
if((username.equals("Ravi")&&
password.equals("Kumar"))||(username.equals("Shashi")&& password.equals("Kumar")))
{
out.println("<html>");
out.println("<head><title>Program 6 </title></head>");
out.println("<body>");
out.println("<h1>User Information</h1>");
out.println("<br><hr><br>");
out.println("Dear User.<br>");
out.println("Your Information.<br><br>");
out.println("UserName: "+username+"<br>");
out.println("password :"+password+"<br>");

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 31


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

out.println("Contact Number:"+phoneno+"<br>");
out.println("</body>");
out.println("</html>");
}
else
{
response.sendRedirect("validUser");
}
}
}
// validUser.java

package mypackage;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class validUser extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<h1> <font color = red> u r not a valid user " + " ");
out.println("<br><h2><font color = purple>please enter the valid data");
}
}
//Web.xml

<web-app>
<servlet>
<servlet-name>Prog6SendRedirectServlet</servlet-name>
<servlet-class>mypackage.Prog6SendRedirectServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>validUser</servlet-name>
<servlet-class>mypackage.validUser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Prog6SendRedirectServlet</servlet-name>
<url-pattern>/Prog6SendRedirectServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>validUser</servlet-name>
<url-pattern>/validUser</url-pattern>
</servlet-mapping>
</web-app>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 32


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 33


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

7) Write a JAVA Servlet Program to implement sessions (Using HTTP Session Interface).

Procedure for Execution.

Step1. Open the NetBean 7.1 Editor-> Select File->New Project


Step 2. Select Java Web Folder in Categories-> Select Web Application option-> click Next
Step 3. Give the project name and select Main project check box ->click Next.

Step 4. Select the Server-Tomcat-> Click Next -> Click Finish


Step 5. Right Click on project folder-> Select New -> Select Servlet -> Give the name of Servlet
and package name-> Click next

Step6:Create the Servlet named SessionTracking.java


Step7: Save and compile it.
Step8 Right click on the SessionTracking.java file and run it.
Step9: Set Servlet Execution URI as /SessionTracking. Press OK.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 34


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Brief Introduction

1. Session: - A Session refers to all the request that a single client makes to a server. A session is
specific to the user and for each user a new session is created to track all the request from that user.
Every user has a separate session and separate session variable is associated with that session. In case
of web applications the default time-out value for session variable is 20 minutes, which can be
changed as per the requirement.

2. Session ID: - A session ID is an unique identification string usually a long, random and alpha-
numeric string, that is transmitted between the client and the server. Session IDs are usually stored in
the cookies, URLs (in case url rewriting) and hidden fields of Web pages.

3. Session Tracking: - HTTP is stateless protocol and it does not maintain the client state. But there
exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the
series of requests from the same user across some period of time.

4. Types of Session Tracking: -


a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions

5. HTTPSession Class: -
HttpSession Class provides a way to identify a user across across multiple request. The servlet
container uses HttpSession interface to create a session between an HTTP client and an HTTP server.
The session lives only for a specified time period, across more than one connection or page request
from the user.

6. Session Tracking in HttpServlet: -


In HttpServlet you can use Session Tracking to track the user state. Session is required if you are
developing shopping cart application or in any e-commerce application.

7. Advantage of Cookies over URL rewriting:-


Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be
used with other mechanism of Session Tracking like url rewriting. Cookies are stored at client side so
some clients may disable cookies so we may not sure that the cookies may work or not. In url
BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 35
ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

rewriting requites large data transfer from and to the server. So, it leads to network traffic and access
may be become slow.

8. Track a user session in Servlets:-


The interface HttpSession can be used to track the session in the Servlet. Following code can be used
to create session object in the Servlet: HttpSession session = req.getSession(true);

9. Destroy the session in Servlet:-


You can call invalidate() method on the session object to destroy the session. e.g.session.invalidate();

Program:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class sessiontracking extends HttpServlet
{

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String heading;
Integer accessCount=new Integer(0);
if(session.isNew())
{
heading="welcome,newcomer";
}
else
{
heading="welcome,back";
Integer oldaccesscount=(Integer)session.getAttribute("accessCount");
if(oldaccesscount!=null)
{
accessCount=new Integer(oldaccesscount.intValue()+1);
}
}
session.putValue("accessCount",accessCount);
out.println("<body bgcolor=\"#df5e6\">\n");
out.println("<h1 align=\"center\">"+heading+"</h1>\n");
out.println("<table border=1 align=center>\n"+"<trbgcolor=\"ffad00\">\n"
+"<th>infotype</th><th>value</th>\n"+"<tr>\n"+"<td>ID\n"
+"<td>"+session.getId()+ "\n"+"<tr>\n"+"<td>creation time\n"

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 36


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

+"<td>"+new Date(session.getCreationTime()) +"\n"+"<tr>\n"


+"<td>time of cost access\n"+"<td>"+new Date(session.getLastAccessedTime())
+"\n"+"<tr>\n"+"<td>Number of previous Accesses\n"
+"<td>"+accessCount+"\n"+"</body></html>" );
}
@Override
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,
IOException
{
doGet(req,res);
}
}
//Web.xml
<web-app >
<servlet>
<servlet-name>sessiontracking</servlet-name>
<servlet-class>sessiontracking</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sessiontracking</servlet-name>
<url-pattern>/sessiontracking</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 37


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Output:

After 2 time reloading the page

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 38


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

8) a. Write a JAVA JSP Program to print 10 even and 10 odd number.


b. Write a JAVA JSP Program to implement verification of a particular user login and display
a welcome page.

Procedure for Execution.


Step 1: Create the new web application and give the name.
Step 2: Right click on the web pages folder-New-select jsp file.

Step 3. Code the jsp file, save and run it by right clicking.
Step 4. Create another three jsp page named as forward1.jsp, forward2.jsp, login.jsp in the same
project for question 8b.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 39


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Brief Introduction

1. JavaServer Pages :-
JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to
web clients in a portable, secure and well-defined way. The JavaServer Pages specification extends the
Java Servlet API to provide web application developers with a robust framework for creating dynamic
web content on the server using HTML, and XML templates, and Java code, which is secure, fast, and
independent of server platforms. JSP has been built on top of the Servlet API and utilizes Servlet
semantics. JSP has become the preferred request handler and response mechanism. Although JSP
technology is going to be a powerful successor to basic Servlets.

2. Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating
complex HTML. Most servlets contain a little code that handles application logic and a lot more code
that handles output formatting. This can make it difficult to separate and reuse portions of the code
when a different output format is needed. For these reasons, web application developers turn towards
JSP as their preferred Servlet environment.

3. Life of the the jsp page is just same as the servlet life cycle. After get translated the jsp file is just
like a servlet. The life cycle of the jsp page is given below:

jspInit(): This method is the called form the init() method. This method is of interface
javax.servlet.jsp.JspPage. We can override this method. This method will be called once when the
container loads the servlet for the first time.

_jspService(): This method is called from the servlet's service method. The container passes the
Request and Response objects to this method. We can't override this method. It is a method of
javax.servlet.jsp.HttpJspPage interface.

jspDestroy: This method is called by the servlet's destroy() method. We can override this method. It
is a method of javax.servlet.jsp.JspPage interface.

1. JSP tags can be divided into 4 different types:


i. Declarations
This tag is used for defining the functions and variables to be used in the JSP.
<%! Script code (allow multiple statements) %>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 40


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

ii. Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in
_jspService method by the JSP engine.
<% script code (allow multiple statements) %>

iii. Expressions
We can use this tag to output any data on the generated page. These data are
automatically converted to string and printed on the output stream.
<%= script code (allow multiple statements) %>

iv. Directives
In the directives we can import packages, define error handling pages or the session information of
the JSP page.
<%@directive attribute="value" %>

Where directive may be:


1. page: page is used to provide the information about it.
Example: <%@page language="java" %>
2. include: include is used to include a file in the JSP page.
Example: <%@ include file="/header.jsp" %>
3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our
own tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
and attribute may be:
1. language="java"
This tells the server that the page is using the java language. Current JSP specification supports only
java language.
Example: <%@page language="java" %>

2. extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to import more than
one packages.
Example: <%@page language="java" import="java.sql.*,mypackage.myclass" % >

3. session="true"
When this value is true session data is available to the JSP page otherwise not. By default this value is
true.
Example: <%@page language="java" session="true" %>

4. errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language="java" session="true" errorPage="error.jsp" %>

5. contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page language="java" session="true" contentType="text/html; charset=ISO-
8859-1" %>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 41


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Program:

//Oddeven.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Script for even and odd numbers</title>
</head>
<body bgcolor="purple">
<h1>
10 Even and 10 Odd numbers
</h1>
<%
out.print("<br><br><b><u>10 Even numbers between 1 and 20</u></b><br>");
for(int i=1;i<=20;i++)
{
if((i%2)==0)
{
out.print("<b><br>"+i+"</b>");
}
}
out.print("<br><br><b><u>10 Odd numbers between 1 and 20</u></b><br>");
for(int i=1;i<=20;i++)
{
if((i%2)!=0)
{
out.print("<b><br>"+i+"</b>");
}
}

%>
</body>
</html>

//login.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP page</title>
</head>
<body>
<h1>Hello USERS!</h1>
<form method="post" action="forward1.jsp">
<p>please enter your name:
<input type="text" name="Username">
</p>
<p>Enter the password:
<input type="password" name="password">
</p>
<p><input type="submit" value="login"></p>
</form>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 42


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

</body>
</html>

//forward1.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
if(request.getParameter("Username").equals("ravikumara")&&
request.getParameter("password").equals("kumararavi"))
{
%>
<jsp:forward page="forward2.jsp"/>
<%
}
else
{
%>
<h3> Invalid userName OR Password</h3>
<%@include file="login.jsp" %>
<% } %>
</body>
</html>

//forward2.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello</title>
</head>
<body bgcolor="#ff66f">
<h1>forward action test:Login successful</h1><br>
<h2> welcome to home page Mr/Miss:
<%=request.getParameter("Username")%></h2>
</body>
</html>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 43


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 44


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

9) Write a JAVA JSP Program to get student information through a HTML and create a JAVA
Bean Class, populate Bean and display the same information through another JSP.

Procedure for Execution.

1. Create the new project,

2. Create StudentInput.html , FirstPage.jsp, SecondPage.jsp files under web pages folder.

3. Create the new package named Bean, under this Create the StudentBean.java.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 45


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

4. Right click on the StudentInput.html file to run.

Brief Introduction

Javabean:- A Javabean is just a java class with the following requirements.


i) It has a public no-args constructor
ii) It has 'set' and 'get' methods for its properties.
iii) It may have any general functions.
iv) If required it must be Serializable.
However, It is not necessary always that a bean should have properties.
If there are no properties, we need not provide 'set' & 'get' methods either.
( Even the no-args constructor is provided by the compiler by default!)
If the bean uses library classes alone, it is automatically serializable.
In that case, it becomes just a class for encapsulating some functionality (ie) business logic.

Program:

//Prog9Input.html
<html>
<head> <title>User login Page</title>
</head>
<body bgcolor="silver">
<form action="FirstPage.jsp" method=Post>
<center><h1>Welcome to Student Information System</h1></center>
<h2>Please Enter Student Name</h2>
<input type="text" name="sname"><br><br>
Please Enter Student USN&nbsp;&nbsp;&nbsp;
<input type="text" name="usn"><br>
<br>Please Enter Student Marks1
<input type="text" name="m1"><br>
<br>Please Enter Student Marks2
<input type="text" name="m2"><br>
<br>Please Enter Student Marks3
<input type="text" name="m3"><br>
<br> <input type="submit" value="submit">
</form>
</body>
</html>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 46


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

//Firstpage.jsp

<jsp:useBean id="StudentBean" scope="request" class="Bean.StudentBean">


<jsp:setProperty name="StudentBean" property="*"/>
</jsp:useBean>
<html> <body bgcolor="silver"><br>
<jsp:forward page="SecondPage.jsp"/>
</body></html>

//Secondpage.jsp

<jsp:useBean id="StudentBean" scope="request" class="Bean.StudentBean">


</jsp:useBean>
<html> <body bgcolor="silver">
<h1><center> Student Information Retrieval</center></h1>
<table border='10' width=300>
<tr><td><h2> Student Name:<jsp:getProperty name="StudentBean"
property="sname"/></h2></td></tr>
<tr><td><h2> USN:<jsp:getProperty name="StudentBean" property="usn"/></h2></td></tr>
<tr><td><h2> Marks1:<jsp:getProperty name="StudentBean" property="m1"/></h2></td></tr>
<tr><td><h2>Marks2:<jsp:getProperty name="StudentBean" property="m2"/></h2></td>
<tr><td><h2> Marks3:<jsp:getProperty name="StudentBean" property="m3"/></h2></td></tr>
</table>
</body>
</html>

//StudentBean.java

package Bean;
import java.io.Serializable;
public class StudentBean implements Serializable
{
private String sname;
private String usn;
private String m1;
private String m2;
private String m3;
public void setsname(String sname) { this.sname=sname;
}
public void setusn(String usn)
{
this.usn=usn;
}
public void setm1(String m1)
{
this.m1=m1;
}
public void setm2(String m2)
{
this.m2=m2;
}
public void setm3(String m3)

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 47


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

{
this.m3=m3;
}
public String getsname()
{
return sname;
}
public String getusn()
{
return usn;
}
public String getm1()
{
return m1;
}
public String getm2()
{
return m2;
}
public String getm3()
{
return m3;
}
}
//web.xml

<web-app>
<servlet>
<servlet-name>StudentBean</servlet-name>
<servlet-class>Bean.StudentBean</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentBean</servlet-name>
<url-pattern>/StudentBean</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 48


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 49


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

10) Write a JAVA JSP Program which uses <jsp:plugin> tag to run a applet.

Procedure for Execution.

1. Create a New java web project and give the name as Prog10

2. Create the java source file under source package


3. Create the AppletJsp.jsp page under web pages folder.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 50


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

4. Compile the java source file and copy the java class file ButtonMoveApplet.class file under web
pages folder.
5. Select – Tools – plugins – Activate all installed plugins.
6. Run the file AppletJsp.jsp file.

Brief Introduction

1. Applet : Applet is java program that can be embedded into HTML pages. Java applets runs on the
java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely
on the client browser, so there are some restrictions on it. Applet can't access system resources on the
local computer. Applets are used to make the web site more dynamic and entertaining.

2. JSP-Applet: To use applet in JSP page we can use <jsp:plugin>. By the use of <jsp:plugin> you
can include an applet and JavaBean in your JSP page.

Syntax of <jsp:plugin> is :
<jsp:plugin
type="bean|applet"
code="classFile"
codebase="classFileDirectory"
[ name="instancename" ]
[ align="bottom|top|middle|left|right" ]
[ height="displayPixels" ]
[ width="displayPixels" ]
[ jreversion="JREVersion" ]
................. >
[<jsp:params>
<jsp:param name="parametername"
value="parametervalue" />
..........
</jsp:params>]
[<jsp:fallback>
text message
..........
</jsp:fallback>]
</jsp:plugin>

Attributes:
1. type: this is the type of object plugin will execute. You have to specify it either bean or applet since
it has no default value.
2. code: name of the java class file. You must have to write ".class" with class file name.
3. codebase: absolute or relative path of directory where applet code file exists.
4. name: name of bean or applet instance.
5. align: position of applet or bean display on the browser.
6. height: as its name signifies, height of applet or bean display
7. width: as its name signifies, width of applet or bean display
8. jreversion: version of Java Runtime environment
9. <jsp:params>: name and parameters value passed to applet or bean.
10. <jsp:fallback>: a text message to be displayed if applet plugin cannot be started.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 51


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Program:
//Applet.jsp

<html>
<head>
<title>Welcome JSP-Applet Page</title>
</head>
<body>
<jsp:plugin type="applet" code="ButtonMoveApplet.class" width="400" height="400">
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>
</jsp:plugin>
</body>
</html>

//ButtonMoveApplet.java

import java.awt.*;
import java.util.*;
import java.applet.*;
public class ButtonMoveApplet extends Applet
{
Button move;
Random r;
@Override
public void init()
{
setLayout(null);
move = new Button("Click me");
add(move);
move.reshape(10,10,70,30);
r = new Random();
setBackground(Color.red);
setForeground(Color.yellow);
}
@Override
public void paint(Graphics g)
{
g.drawString("Welcome JSP-Applet",100,100);
}
@Override
public boolean action(Event evt, Object whatAction)
{
if (!(evt.target instanceof Button))
return false;
String buttonLabel = (String)whatAction;
if ( buttonLabel == null ? "Click me" == null : buttonLabel.equals("Click me"))
{
move.reshape(Math.abs(r.nextInt())%(size().width-70),
Math.abs(r.nextInt())%(size().height-30),70,30);
repaint();

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 52


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

}
return true;
}
}

//web.xml

<web-app >
<servlet>
<servlet-name>ButtonMoveApplet</servlet-name>
<servlet-class>ButtonMoveApplet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ButtonMoveApplet</servlet-name>
<url-pattern>/ButtonMoveApplet</url-pattern>
</servlet-mapping>
</web-app>

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 53


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

11) Write a JAVA JSP Program which implements nested tags and also uses TagSupport Class.

Procedure for Execution.

1. Select New Project -> java web -> web application -> give the name as Program11 ->
Next -> select tomcat server-> next->finish

2. Create the newjsp.jsp page and edit the code.

3. Create the new nested.tld file under /WEB-INF/tlds/ directory

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 54


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

4. Create the TagHandler Class – NestLevel.java (i.e., java class file) under mypack
package.

5. Compile the NestLevel.java file and finally


6. Right click on the newjsp.jsp file and click run.

Brief Introduction

JSP Custom Tags :


• Provide a mechanism to a Web programmer to reuse and encapsulate complex recurring
code in a JSP application.
• Provide simplicity and reusability of Java code.
• Enable you to perform various functions, such as:
1. Accessing all implicit variables of a JSP page, such as request, response, in, and out.
2. Modifying the response generated by a calling JSP page.
3. Initializing and instantiating a JavaBean component.
Types of Custom Tags
The various types of custom tags that you can develop in JSP are :
• Empty tags: Refer to the custom tags that do not have any attribute or body. The
following code snippet shows an empty custom tag:
<td:welcome />
• Tags with attributes: Refer to custom tags for which you can define attributes to
customize the behavior of the custom tag. The following code snippet shows a custom tag
with an attribute color:
<td: welcome color=?blue?></td:welcome>
• Tags with a body: Refer to the custom tag within which you can define nested custom
tags, scripting elements, actions, HTML text, and JSP directives. The following code
snippet shows a custom tag that contains a JSP scripting element as its body:
<td: welcome>
<%=today_date%>
</td:welcome>
• Nested tags: Refer to the set of custom tags in which one custom tag encloses one or
more custom tags. The following code snippet shows a nested custom tag:
<td1:ifTag condition ?<%=eval>? >
<td2:valueTrue>
The expression evaluates to true
</td2:valueTrue>
</td1:ifTag>/font>
BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 55
ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Development of Custom Tag :


To develop a custom tag, you need to perform following steps:
• Include the Tag Library in a JSP page
• Develop the Tag Library Descriptor (TLD) file
• Develop a tag handler or class file(.java)
• Deploy the application
Tag Handler File : Build a class that implements the javax.servlet.jsp.tagext tag interface as
follows. Compile it and place it under the /WEB-INF/classes directory (in the appropriate
package structure).

Tag Library Descriptor (TLD) file : Now we need to describe the tag, so create a file called
nested.tld and place it under the /WEB-INF/tlds directory.

Program:

//newjsp.jsp

<%@taglib uri="/WEB-INF/tlds/nested.tld" prefix="x"%>


<x:nest>
<x:nest>
<x:nest/>
</x:nest>
</x:nest>

//nested.tld

<?xml version="1.0" encoding="UTF-8"?>


<taglib version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>nested</short-name>
<uri>/WEB-INF/tlds/nested</uri>
<tag>
<name>nest</name>
<tag-class>mypack.NestLevel</tag-class>
</tag>
</taglib>

//NestLevelTag.java

package mypack;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class NestLevel extends TagSupport
{
private int nestLevel=0;
@Override
public int doStartTag() throws JspException
{
nestLevel=0;
Tag parent =getParent();
while(parent!=null)

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 56


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

{
parent=parent.getParent();
nestLevel++;
}
try
{
pageContext.getOut().println("<br> Tag Nested Level: "+nestLevel);
}
catch(IOException e)
{
throw new JspException("IOException "+e.toString());
}
return EVAL_BODY_INCLUDE;
}
}

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 57


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

12) An EJB application that demonstrates Session Bean.

Procedure for Execution.

1. Select file -> new project -> java EE -> Enterprise Application -> next -> give project name and
project location -> next -> select glassFishServer -> Select all EJBModule, WebApplicationModule and
Client module -> finish.

2. It will create ejb,war and app-client with project folder.


3. Right click on project-ejb and select new-> session bean -> give EJBName, location,package and
session type & select both local and remote interface. It will create 3 *.javafiles like projectname.java,
local.java and remote.java

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 58


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

4. Right click inside projectname.java page -> click insert code -> add business method ->
and define business methods.

5. Create a servlet that accessed the stateless session beans.


6. Create a servlet by right clicking the war file and select -> new servlet, give name and
location -> next -> accept the servletname and URL pattern(s) fields and click finish.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 59


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

7. Add code to the servlet that accesses the stateless session bean.
8. Right click on the content of servlet session and select insert code then select call
Enterprise Bean -> Select sessionBean -> click ok.

9. Right click on the project name-war and click run. This opens the index.jsp page , input the values
and submit, it will display the result. Or extend the projectname-war ->webpages->index.jsp right
click on it and click run.

Brief Introduction

• Session Beans : Performs a task for a client; implements a web service


• Stateless
• Stateful.
• At any given time, only one client has access to the bean instance.
• The state of the bean is not persistent, existing only for a short period (perhaps a few
hours).
• The bean implements a web service.

Program:

//SessionBean.java

package mypack;
import javax.ejb.Stateless;
@Stateless
public class SessionBean implements SessionBeanRemote, SessionBeanLocal {
public int multiplication(int p1, int p2)
{
return p1 * p2;
}

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 60


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

//SessionBeanLocal.java

package mypack;
import javax.ejb.Local;
@Local
public interface SessionBeanLocal
{
int multiplication(int p1, int p2);
}

// SessionBeanRemote.java

package mypack;
import javax.ejb.Remote;
@Remote
public interface SessionBeanRemote
{

//NewServlet.java

package mypack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet
{
@EJB
private SessionBeanLocal sessionBean;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
int p1=Integer.parseInt(request.getParameter("n1"));
int p2=Integer.parseInt(request.getParameter("n2"));
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Multiplication is " +sessionBean.multiplication(p1,p2)+"</h1>");
out.println("</body>");
out.println("</html>");
}

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 61


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

finally
{
out.close();
}
}
}

//Index.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Multiplication of Two Numbers</title>
</head>
<body>
<form action="NewServlet" method="post">
<h1>Multiplication of two numbers,which call stateless business method</h1>
number 1:<input type="text" name="n1"><br><br>
number 2:<input type="text" name="n2"><br><br>
<input type="submit" value="Multiplication">
</form>
</body>
</html>

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 62


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

13) An EJB application that demonstrates Entity Bean.

Procedure for Execution.

1. Select – New Project – Java EE – Enterprise Application -> give project name as Prog13-> Then
select Only EJB & Web application module -> Click Finish.

2. Select Services option in NetBeans -> Databases -> Java DB-> Right click and start the server ->
Right Click on sample-> click connect
3. Look into jdbc://localhost:1527/Sample -> Click App-> Right Click on Table->Create New table and
add columns to table.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 63


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

4. Switch to project window -> Right Click prog13-ejb -> New-> Select Entity Classes from Database ->
Select Data Source as jdbc/sample -> Select Empinfo -> add -> next

5. Give package name as mypack -> next -> Finish. It creates mapping between table and Entity bean
and create Student.java class.

6. Right Click on prog13-ejb -> New -> Select -> Session Bean for entity classes.... Select available
entity classes -> Select mypacks.Empinfo -> Add -> Next -> Select local interface -> Finish. It will
creates AbstractFacade .java [Abstract class], StudentFacade.java [java class], StudentFacadeLocal.java
interface.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 64


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

7. In EmpinfoFacade.java -> Add the following code


@Override
public void persist(Object obj)
{
em.persist(obj);
}
public void addsEmp(String eid,String ename)
{
Empinfo obj=new Empinfo();
obj.setEid(eid);
obj.setEname(ename);
persist(obj);
}

8. Right click on program13-war -> new -> Servlet -> give the name as studEntity->give package name
mypack->next -> select deployment descriptor -> finish.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 65


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

9. The right click on code window -> Select insert code -> call enterprise bean -> Select studentFacade
-> ok. Observe the code appears inside the servlet as StudentFacadeLocal studentFacade.

10. Add the following code


try {
empinfoFacade.addsEmp("e100", "ravi");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Record inserted successfully" + "</h1>");
out.println("</body>");
out.println("</html>");

}
save it and leave the default additional doPost and doGet methods in the same page as it is.
11. Right click on the war file -> properties -> Select run -> give Relative URL as the /ServletName ->
ok.

12. Right click on the war file of servlet file and click run.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 66


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Brief Introduction

• Entity beans are persistent,


• Allow shared access, have primary keys, and can participate in relationships with other
entity beans.
• With bean-managed persistence, the entity bean code that you write contains the calls
that access the database.
• If your bean has container-managed persistence, the EJB container automatically
generates the necessary database access calls.
• The code that you write for the entity bean does not include these calls.

Program:

// AbstractFacade.java

package pack;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T>
{
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass)
{
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity)
{
getEntityManager().persist(entity);
}
public void edit(T entity)
{
getEntityManager().merge(entity);
}
public void remove(T entity)
{
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id)
{
return getEntityManager().find(entityClass, id);
}
public List<T> findAll()
{
javax.persistence.criteria.CriteriaQuery
cq=getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range)
{
javax.persistence.criteria.CriteriaQuery

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 67


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

cq=getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count()
{
javax.persistence.criteria.CriteriaQuery
cq=getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}

// Empinfo.java

package pack;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "EMPINFO")
@NamedQueries({ @NamedQuery(name = "Empinfo.findAll", query = "SELECT e FROM Empinfo e")})
public class Empinfo implements Serializable
{
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Lob
@Column(name = "EID")
private String eid;
@Lob
@Column(name = "ENAME")
private String ename;
@Lob
@Column(name = "CONTACTNO")
private String contactno;
public Empinfo()
{ }
public Empinfo(String eid)
{
this.eid = eid;

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 68


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

}
public String getEid()
{
return eid;
}
public void setEid(String eid)
{
this.eid = eid;
}
public String getEname()
{
return ename;
}
public void setEname(String ename)
{
this.ename = ename;
}
public String getContactno()
{
return contactno;
}
public void setContactno(String contactno)
{
this.contactno = contactno;
}
@Override
public int hashCode()
{
int hash = 0;
hash += (eid != null ? eid.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object)
{
if (!(object instanceof Empinfo))
{
return false;
}
Empinfo other = (Empinfo) object;
if ((this.eid == null && other.eid != null) || (this.eid != null && !this.eid.equals(other.eid)))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "mypack.Empinfo[eid=" + eid + "]";
}
}

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 69


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

//EmpinfoFacade.java

package pack;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class EmpinfoFacade extends AbstractFacade<Empinfo> implements EmpinfoFacadeLocal
{
@PersistenceContext(unitName = "Prog13-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager()
{
return em;
}
public EmpinfoFacade()
{
super(Empinfo.class);
}
@Override
public void persist(Object obj)
{
em.persist(obj);
}
public void addsEmp(String eid,String ename)
{
Empinfo obj=new Empinfo();
obj.setEid(eid);
obj.setEname(ename);
persist(obj);
}
}
// EmpinfoFacadeLocal.java

package pack;
import java.util.List;
import javax.ejb.Local;
@Local
public interface EmpinfoFacadeLocal
{
void create(Empinfo empinfo);
void edit(Empinfo empinfo);
void remove(Empinfo empinfo);
Empinfo find(Object id);
List<Empinfo> findAll();
List<Empinfo> findRange(int[] range);
int count();
public void persist(java.lang.Object obj);
public void addsEmp(java.lang.String eid, java.lang.String ename);
}

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 70


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

//NewServlet.java

package pack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pack.EmpinfoFacadeLocal;
public class NewServlet extends HttpServlet
{
@EJB
private EmpinfoFacadeLocal empinfoFacade;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
empinfoFacade.addsEmp("e100", "ravi");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Record inserted successfully" + "</h1>");
out.println("</body>");
out.println("</html>");

}
finally
{
out.close();
}
}
}

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 71


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Output:

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 72


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

14) An EJB application that demonstrates MDB.

Procedure for Execution.

Step1: Open the NetBeans IDE 6.9.1 switch to Services double click on the database select Java DB
right click on sample click connect
Step2: Select Servers in that GlassFish server Start that.

Step3:Right click on the GlassFish Server and select View Admin Console

Step4: Select Resources and expand itClick JMS Resources in that again Click Connection
Factories  then click New and give Pool name like jms/mypool and Resource Type is
javax.jms.QueueConnectionFactory and description is mypool and click OK

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 73


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Step5:Click Destination Resources Click New and give JNDI Name jms/destination, Physical
Destination namedestination and Resource Typejavax.jms.Queue and Click OK

Step6: Select New project -> JavaEE -> Enterprise Application-> click next ->Prog14 and Set as Main
project -> next -> finish.

Step7: Right click on the NewMessage-Driven-Beangive EJB name Callingmdb package


namegoldServer Destinationjms/destinationFinish

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 74


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Step8: Write the below code in Callingmdb file and by clicking on bubble select the appropriate
action.
public void onMessage(Message message)
{
try
{
System.out.println("My Name Is" + message.getStringProperty("name"));
System.out.println("My Usn Is" + message.getStringProperty("usn"));
System.out.println("The Sem is" + message.getIntProperty("sem"));
}
catch (JMSException ex)
{
Logger.getLogger(Callingmdb.class.getName()).log(Level.SEVERE, null, ex);
}
}

Step9: Right click on Prog14-warNew Servletgive class name CallingClient  package name
silver Click Next and click the check box add information to deployment descriptor(web.xml)
and Click Finish

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 75


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Step10: Right click in first try and catch block(CallingClient.java file) and select insert CodeSend
JMS Message  select Server Destinations:jms/destinationConnection Factory:jms/mypool 
Click OK and Write the below code in the first try-catch block and Override it.
try
{
sendJMSMessageToDestination();
out.println("Your Message has been sent check it the log");
}
catch (JMSException ex)
{
Logger.getLogger(CallingClient.class.getName()).log(Level.SEVERE, null, ex);
}

Step11: Write the below code in the sendJMSMessageToDestination() method and Save all the Files.
private void sendJMSMessageToDestination() throws JMSException
{
Connection connection = null;
Session session = null;
try {
connection = mypool.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(destination);
Message ms=session.createMessage();
ms.setStringProperty("name","Ravikumara");
ms.setStringProperty("usn","1BYMCA");
ms.setIntProperty("sem", 4);
messageProducer.send(ms);
}

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 76


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Brief Introduction

• A message-driven bean is an enterprise bean that allows J2EE applications to process


messages asynchronously. It acts as a JMS message listener, which is similar to an event
listener except that it receives messages instead of events.

• The messages may be sent by any J2EE component--an application client, another
enterprise bean, or a Web component--or by a JMS application or system that does not
use J2EE technology.

• Message-driven beans currently process only JMS messages, but in the future they may
be used to process other kinds of messages.

• A message driven bean’s instances retain no data or conversational state for a specific
client, i.e., they are stateless.

• A message-driven bean has only a bean class i.e., unlike a session bean, the client’s don’t
access message-driven beans through interfaces.

• They don’t have the remote or local interfaces that define client access.

• Java Message Service (JMS) is an API for java messaging clients. It provides two
models, i. point-to-point ii. Publish and subscribe.

Program:

//Callingmdb.java
package gold;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
@MessageDriven(mappedName = "jms/destination", activationConfig =
{@ActivationConfigProperty(propertyName="acknowledgeMode",propertyValue="Auto-acknowledge
"),@ActivationConfigProperty(propertyName="destinationType",propertyValue= "javax.jms.Queue")
})
public class Callingmdb implements MessageListener
{
public Callingmdb()
{
}
@Override
public void onMessage(Message message)
{
try {
System.out.println("My Name Is" + message.getStringProperty("name"));
System.out.println("My Usn Is" + message.getStringProperty("usn"));
System.out.println("The Sem is" + message.getIntProperty("sem"));

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 77


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

}
catch (JMSException ex)
{
Logger.getLogger(Callingmdb.class.getName()).log(Level.SEVERE, null, ex);
}
}

}
//CallingClient.java

package silver;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CallingClient extends HttpServlet
{
@Resource(name = "jms/destination")
private Queue destination;
@Resource(name = "jms/mypool")
private ConnectionFactory mypool;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
sendJMSMessageToDestination();
out.println("Your Message has been sent check it the log");
}
catch (JMSException ex)
{
Logger.getLogger(CallingClient.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
out.close();
}

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 78


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

}
private Message createJMSMessageForjmsDestination(Session session, Object messageData) throws
JMSException
{
TextMessage tm = session.createTextMessage();
tm.setText(messageData.toString());
return tm;
}
private void sendJMSMessageToDestination() throws JMSException
{
Connection connection = null;
Session session = null;
try
{
connection = mypool.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(destination);
Message ms=session.createMessage();
ms.setStringProperty("name","Ravikumara");
ms.setStringProperty("usn","1BYMCA");
ms.setIntProperty("sem", 4);
messageProducer.send(ms);
}
finally
{
if (session != null)
{
try
{
session.close();
}
catch (JMSException e)
{
Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
}
}
if (connection != null)
{
connection.close();
}
}
}
}

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 79


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Output:
Right Click on Prog14-warPropertiesRunRelative path/CallingClient Ok
Right Click on Prog14-war and Click Run.

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 80


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

Viva Questions:
1. Draw a neat diagram for J2EE architecture
2. Define JDBC, & how many JDBC driver types?
3. List Data types supported by JDBC
4. Which package is used for JDBC program?
5. Define class.forName() method?
6. Write the JDBC Connection code in java?
7. Define Statement Object?
8. How many types of Statement Objects?
9. Define Statement, PreparedStatement and CallableStatement?
10. What do you mean by ResultSet?
11. Define execute(), executeQuery(), and executeUpdate() methods?
12. Define Meta Data in JDBC?
13. How to create index in JDBC program?
14. Write the example query for Existence Test, Membership Test, and Any Test?
15. How Servlets different from CGI?
16. Write the life cycle of Servlet?
17. Which package mandatory for Servlet program?
18. Give the example for deployment descriptor of Servlet?
19. What the HTTP header carries the information along with client request?
20. What is Status code represents? And Define 400, 401, 403, 404, 405, 415, 500, 501, 503, & 505?
21. Define cookie & its types?
22. Write example code for cookie?
23. Define Session?
24. What are different Tracking mechanisms?
25. Define JSP?
26. How JSP different from Servlet?
27. What are Standard JSP tags?
28. Write the example code for JSP include, import, sql, and custom tags?
29. Define Web Server, Application Server?
30. Define JavaBeans?
31. What are the two design patterns in JavaBeans?
32. Define Introspection?
33. Define Customizer?
34. Which package is mandatory for JavaBeans?
35. Write a snippet code to add colour as property to JavaBean?
36. Write the hierarchy of classes for JavaBeans?
37. Which package is mandatory for EJB?
38. Explain bound and constraint properties of JavaBeans?
39. Define EJB?
40. Write the architecture diagram of EJB?
41. Write the entity java bean deployment descriptor?
42. How many environment element of an EJB?
43. What is the Transaction attributes in EJB?
44. Define Session Java Bean?
45. What are the types of Session Beans?
46. Define Entity Java Bean?
47. What are the types of Entity Java Bean?
48. Define Message Driven Bean?
49. How Session Bean is different from Entity Bean and Message-Driven Bean?
50. Define the components of EJB jar file?

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 81


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

51.Use of Class.forName
52.Use of Driver Manager.getconnection
53.Result set
54.Use of next ( ) method in result set
55.Prepared Statement
56.Explain i. Servlets Life Cycle (with diagram) ii. Servlets API
57.Explain doGet, doPost types in Servlet, write a program to implement doGet or doPost using
servlets
58.Explain different types of JSP Tags
59.List the three kinds of EJB classes.
60. Explain the two important interfaces of EJB.
61. Explain the creation of Session Java Bean.
62. Explain the Entity Java Bean
63. Explain the creation of Message-Driven Bean.
64. List some of the applications of java beans.
65. Give an example to Implementing Event Handling with Adapter class
66. Explain the methods, rebind() and lookup() in Naming class?
67. How do you pass data (including JavaBeans) to a JSP from a servlet?
68. What is Servlet chaining?
69. What is the life cycle of a servlet?
70. What is the difference between doPost and doGet methods?
71. What are the steps involved for making a connection with a database or how do you connect to a
database?
72. What are drivers available for database connections?
73. What are the three bean times?
74. What are the five features of a JavaBean?
75. What is a property?
76. What is the EventTargetDialog in the BeanBox?
77. Where do the jar files for beans go in the BeanBox?
78. How do we compile and execute a Java class that resides in a package?
79. What goes in a manifest file for a JavaBean?
80. What is the advantage of denormalization?
81. Is the JDBC-ODBC Bridge multi-threaded?
82. What is the fastest type of JDBC driver?
83. What are the different JDB drivers available?
84. What is Connection pooling?
85. What is Connection?
86. What is JDBC?
87. What are the steps required to execute a query in JDBC?
88. What is JDBC Driver ?
89. What is the servlet?
90. What are the JSP atrributes?
91. What is the need of super.init(config) in servlets?
92. How to know whether we have to use jsp or servlet in our project?
93. Can we call destroy() method on servlets from service method?
94. What is the Servlet Interface?
95. What is the difference between GenericServlet and HttpServlet?
96. How we can check in particular page the session will be alive or not?
97. What is the importance of deployment descriptor in servlet?
98. When we increase the buffer size in our project using page directive attribute ‘buffer’ what
changes we observe?
99. What is the difference between ServetConfig and ServletContext..?

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 82


ADVANCED JAVA LAB MANUAL – 10MCA46 / 13MCA46 , SHIVAKUMARA T

100. When a servlet accepts a call from a client, it receives two objects. What are they?
101. What are the differences between GET and POST service methods?
102. In which conditions we have to use the ServletContext?
103. What methods will be called in which order?((i.e)service(),doget(),dopost())

BMS Institute of Technology & Management, Yelahanka, Bangalore-560064 Page 83

You might also like