You are on page 1of 27

Advanced Java Programming Laboratory (13MCA47)

Advanced Java Programming Laboratory


Subject Code : 13MCA47 I.A. Marks : 50
Hours/Week : 3 Exam Marks: 50
Total Hours : 42 Exam Hours : 3

1. 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).

index.html (HTML file it can be JSP file also)

<html><body>
<center>
<form action="LoginServlet" method="POST">
<b> Login form </b><br><br>
Username: <input type="text" name="uname" value="" /><br><br>
Password: <input type="password" name="pass" value="" /><br><br>
<input type="submit" value="submit" />

</form>
</center>
</body></html>

LoginServlet.java (Servlet File)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>UserPassword</title></head>");
out.println("<body>");
String username = request.getParameter("uname");
String password = request.getParameter("pass");
out.println("Username " + username);
out.println("<br>");
out.println("Password is : " + password);
out.println("</body></html>");
out.close();
}
}

1
Advanced Java Programming Laboratory (13MCA47)

2. Write a JAVA Servlet Program to Auto Web Page Refresh (Consider a webpage which
is displaying Date and time or stock market status. For all such type of pages, you would
need to refresh your web page regularly; Java Servlet makes this job easy by providing
refresh automatically after a given interval).
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>JAVA Servlet Program to Auto Web Page Refresh</p>
<p>Click on the following link for Auto Web Page Refresh:</p>
<!-- this will redirect to ServletApplication as URL-pattern for ServletApplication was
mentioned as /home -->
<a href="home"><b>More...</b></a> <hr />
</body>
</html>

TestServlet.java
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
response.setContentType("text/html");
response.addHeader("Refresh", "2");
out.println("TestServlet says hi at " + new Date());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);

2
Advanced Java Programming Laboratory (13MCA47)

}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

3
Advanced Java Programming Laboratory (13MCA47)

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

index.html

<html><head><title>Demonstration of Get and Post Method</title></head>


<body bgcolor="pink">
<center>
<form action="Prog3" method="post">
<a href="Prog3"><b>Click here to call get method</b></a><br><br>
<p><b>Press submit button to call Post method</b></p><br><B>color:</B>
<select name="color" size="1">
<option value="red">red</option>
<option value="green">green</option>
<option value="blue">blue</option>
</select><br><br>
<input type=submit value="submit">
</form>
</body>
</html>

Prog3.java (Servlet File)

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Prog3 extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
String color=request.getParameter("color");
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Prog3</title>");
out.println("</head>");
out.println("<body bgcolor="+color+">");
out.println("<b>Hello from Post method</b><br><br>");
out.println("You have selected" + " " + color + " " + "color");
out.println("</body></html>");
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
4
Advanced Java Programming Laboratory (13MCA47)

out.println("<b>Hello from Get method</b>");


out.println("<h1>Welcome to AIT</h1>");
}
}

4. Write a JAVA Servlet Program using cookies to remember user preferences.

index.html

<html>
<head>
<title>Cookies</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form id="form1" action="SetCookieServlet" method="post">
<table>
<tr>
<td>Name</td><td><input type="text" name="uname"/></td>
</tr>
<tr>
<td>Email</td><td><input type="email" name="uemail"/></td>
</tr>
<tr>
<td>Password</td><td><input type="password" name="upass"/></td>
</tr>
</table>
<input type="submit" value="Set Cookie"/>
</form>
<br/>
<form id="form2" action="FetchCookieServlet" method="post">
<input type="submit" value="Fetch Cookie"/>
</form>
</center>
</body>
</html>

SetCookieServlet.java

package com;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SetCookieServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

5
Advanced Java Programming Laboratory (13MCA47)

Cookie cookie_name = new Cookie("uname",request.getParameter("uname"));


Cookie cookie_email = new Cookie("uemail",request.getParameter("uemail"));
Cookie cookie_pass = new Cookie("upass",request.getParameter("upass"));

cookie_name.setMaxAge(60*60*24);
cookie_email.setMaxAge(60*60*24);
cookie_pass.setMaxAge(60*60*24);

response.addCookie(cookie_name);
response.addCookie(cookie_email);
response.addCookie(cookie_pass);

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML><html><head><title>Set Cookie</title></head>"+
"<body><center>"+
"<h1>Cookie has been set successfully!</h1><br/>"+
"<a href='index.html'>Click here to go back to previous page</a>"+
"</body></html>");

}
}

FetchCookieServlet

package com;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FetchCookieServlet extends HttpServlet {


Cookie cookie = null;
Cookie[] cookies = null;
PrintWriter out;

private String searchCookie(String s)


{
for (Cookie cookie1 : cookies) {
cookie = cookie1;
if((cookie.getName( )).compareTo(s)==0)
return cookie.getValue( );
}
return "";
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

cookies = request.getCookies();

6
Advanced Java Programming Laboratory (13MCA47)

response.setContentType("text/html");
out = response.getWriter();
out.println("<!DOCTYPE HTML><html><head><title>Fetch Cookie</title> </head> <body>
<center>");
if( cookies != null )
{
out.println("<h1>Welcome "+searchCookie("uname")+"</h1><br/>"+
"Your Email ID: "+searchCookie("uemail")+"<br/>"+
"Your Password: "+searchCookie("upass"));
}
else
{
out.println("<h1>No Cookies found!</h1>");
}
out.println("<br/><a href='index.html'>Click here to go back to previous
page</a></center></body></html>");
}
}

7
Advanced Java Programming Laboratory (13MCA47)

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

login.jsp

<html>
<head> <title> Login page </title>
</head>
<body>
<form action="validation.jsp">
<table border="0">
<tr>
<td> USER ID: </td>
<td>
<input type="text" name="uname" /> <br>
</td>
</tr>
<tr>
<td> PASSWORD: </td>
<td>
<input type="password" name="password" /> <br>
</td>
</tr>
<tr> <td align ="center">
<input type="submit" value="submit" >
<input type="reset" value="reset">
</td>
</tr>
</form>
</body>
</html>

validation.jsp

<html>
<body>
<%! String uid="student"; %>
<%! String pass="aitmca"; %>
<%! String id, password; %>
<% id=request.getParameter("uname"); %>
<% password=request.getParameter("password"); %>
<% if(uid.equals(id)&&pass.equals(password))

{
%>
<jsp:forward page="welcome.jsp"/>
<%
}
else
{
8
Advanced Java Programming Laboratory (13MCA47)

%>
<jsp:forward page="error.jsp" />
<%
}
%>
</body>
</html>

welcome.jsp

<html>
<body bgcolor="pink">
<center>
<%! String id; %>
<% id=request.getParameter("uname"); %>
<h1> welcome <%=id%> to the home page </h1>
</center>
</body>
</html>

error.jsp

<html>
<head> <title>JSP Page</title> </head>
<body bgcolor="pink">
<h1>INVALID ENTRY</h1>
</body>
</html>

5 b. Write a JSP program to demonstrate the import attribute.

lab5b.jsp

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


<HTML>
<BODY>
<%
System.out.println( "Evaluating date now" );
Date date = new Date();
%>
Hello! The time is now <%= date %>
</BODY>
</HTML>

9
Advanced Java Programming Laboratory (13MCA47)

6. Write a JAVA JSP Program which uses jsp:include and jsp:forward action to display a
Webpage.

header.jsp
<%@ page import="java.util.Date" %>
<html>
<head>
<title> </title>
</head>
<body>
<h1>
My website. Time:
<% Date d=new Date();%>
<%=d%>
</h1>
</body>
</html>

index.jsp

<html>
<head>
<title>Index Page</title>
</head>
<body>
<center>
<jsp:include page="header.jsp"/>
<br />
<h1>
Enter Data
</h1>
<br />
<form method="post" action="val.jsp">
Username:
<input type="text" name="uname"/>
<br/> password:
<input type="password" name="upass"/>
<br/>
<input type="submit" value="login">
</form>
</center>
</body>
</html>

10
Advanced Java Programming Laboratory (13MCA47)

val.jsp

<% if(request.getParameter("uname").equals("student") &&


request.getParameter("upass").equals("ait")){%>
<jsp:forward page="welcome.jsp" />
<%}
else{ %>
<jsp:forward page="index.jsp" />
<% } %>

welcome.jsp

<!DOCTYPE html>
<html>
<head>

<title>welcome page</title>
</head>
<body bgcolor="pink">
<center>
<jsp:include page="header.jsp"/><br/>
<h1>Welcome Mr./Ms. <%=request.getParameter("uname") %></h1>
</center>
</body>
</html>

11
Advanced Java Programming Laboratory (13MCA47)

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

index.jsp

<%@ page language="java" %>


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

p7.java

import java.awt.*;
import java.applet.*;
public class Myapplet extends Applet
{
public void init()
{
setBackground(Color.blue);

}
public void paint(Graphics g)
{
int y=50,x=50;
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
if((i+j)%2!=0)
{
g.setColor(Color.black);
}
else
{
g.setColor(Color.white);
}
g.fillRect(x,y,50,50);
x=x+50;

}
y=y+50;
x=50;
}

}
}

12
Advanced Java Programming Laboratory (13MCA47)

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

index.jsp
<html>

<head>

<title> Regisration </title>

</head>

<body bgcolor="pink">

<h1> <pre> <font size="18pt"> Registration Page </font> </pre> <br>

<form action="StudInfo.jsp" method="post">

<pre>

FirstName : <input type="text" name="firstName" length="30" />

SurName : <input type="text" name="surname" length="30" />

USN : <input type="text" name="usn" length="30" />

Course : <input type="text" name="course" length="30" />

Sem : <input type="text" name="sem" length="30" />

Age : <input type="text" name="age" length="30" />

Address : <input type="text" name="address" length="30" />

<input type ="submit" value="submit" /> <input type ="reset" value="reset"/>

</pre>

<form>

</body>
</html>

StudInfo.jsp
<html>
<head>
<title>
Register User
</title>
</head>
<body>
<jsp:useBean id="stud" scope="session" class="com.Student">
<jsp:setProperty name="stud" property="*" />
</jsp:useBean>

13
Advanced Java Programming Laboratory (13MCA47)

<p> your First Name is: <jsp:getProperty name="stud" property="firstName" />.</p>

<p> Your Last Name is :

<jsp:getProperty name="stud" property="surname" />.</p>

<p> Your USN is :

<jsp:getProperty name="stud" property="usn" />.</p>

<p> Your COURSE Name is :

<jsp:getProperty name="stud" property="course" />.</p>

<p> Your SEM is :

<jsp:getProperty name="stud" property="sem" />.</p>

<p> Your AGE is :

<jsp:getProperty name="stud" property="age" />.</p>

<p> Your Address is :

<jsp:getProperty name="stud" property="address" />.</p>

</body>

</html>

Student.java

package com;

public class Student{

private String firstName;

private String surname;

private String usn;

private String course;

private int sem;

private int age;

private String address;

public String getFirstName(){

return firstName;

public String getSurname(){

14
Advanced Java Programming Laboratory (13MCA47)

return surname ;

public String getUsn(){


return usn;

public String getCourse(){

return course;

public int getAge(){

return age;

public int getSem(){

return sem;

public String getAddress(){

return address;

public void setFirstName(String newFirstName)

this.firstName =newFirstName;

public void setSurname(String newSurname )

this.surname =newSurname;

public void setUsn(String newUsn)

this.usn =newUsn;

15
Advanced Java Programming Laboratory (13MCA47)

public void setCourse(String newCourse)

this.course =newCourse;

public void setSem(int newSem )

this.sem = newSem;

public void setAge(int newAge )

this.age =newAge;
}
public void setAddress(String newAddress )
{
this.address =newAddress;
}
}

16
Advanced Java Programming Laboratory (13MCA47)

9. Write a JAVA Program to insert data into Student DATA BASE and retrieve info based
on particular queries(For example update, delete, search etc…).

Student.java
package student;

import java.io.*;
import java.sql.*;

public class Student {


private Connection Database;
private Statement DataRequest;
private ResultSet Results2;
public Student()
{ String url = "jdbc:mysql://localhost:3306/studentdb";
String userID = "root";
String password = "";
try {
Class.forName( "com.mysql.jdbc.Driver");
Database = DriverManager.getConnection(url,userID,password);
}
catch (ClassNotFoundException error){
System.err.println("Unable to load the MySql Driver" + error);
System.exit(1); }
catch (SQLException error){
System.err.println("Cannot connect to the database." + error);
System.exit(2);}
try{
while(true)
{ System.out.println("1. Queries like:: create table/view,alter,drop,update and
delete");
System.out.println("2. Quries like:: Insert");
System.out.println("3. Queries like:: Selection/Calculation/Group
By/OrderBy/Join/Conditional Testing Query");
System.out.println("4. Exit");
InputStreamReader isr = new InputStreamReader(System.in) ;
BufferedReader br = new BufferedReader(isr) ;
System.out.println("Select your choice");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{ case 1:
try {
System.out.println("Enter your query");
String q1 = br.readLine();
DataRequest = Database.createStatement();
DataRequest.execute(q1);
System.out.println("Query Executed successfully");
DataRequest.close();
}

17
Advanced Java Programming Laboratory (13MCA47)

catch(SQLException sqle){System.err.println(sqle);}
break;
case 2:
try {
PreparedStatement pst ;
System.out.println("Enter your query");
String q2 = br.readLine();
pst=Database.prepareStatement(q2);
pst.execute();
System.out.println("Record inserted Successfully.....");
pst.close();
}
catch(SQLException e){System.out.println(e);}
break;
case 3:
try
{
System.out.println("\nEnter the query to be executed\n");
String str=br.readLine();
DataRequest=Database.createStatement();
Results2=DataRequest.executeQuery(str);
DisplayResults(Results2);
DataRequest.close();
}
catch(Exception e){System.err.println(e);}
break;
case 4: System.exit(0);
}
}
}
catch(IOException ioe1){System.err.println(ioe1);}
}
private void DisplayResults (ResultSet Results2) throws SQLException
{
ResultSetMetaData rmd=Results2.getMetaData();
int col=rmd.getColumnCount();
int count=1;
boolean b=Results2.next();
if(!b)
{
System.out.println("No Data Found");
}
else
{
do
{ System.out.print("RECORD " +(count++)+" => ");
for(int i=0;i<col;i++)
System.out.print(Results2.getString(i+1)+"\t");
System.out.println();
}while(Results2.next());

18
Advanced Java Programming Laboratory (13MCA47)

}
}

public static void main(String[] args) {


// TODO code application logic here
final Student sdb = new Student();
}

}
Output:
1. Queries like:: create table/view,alter,drop,update and delete
2. Quries like:: Insert
3. Queries like:: Selection/Calculation/Group By/Order By/Join/Conditional Testing Query
4. Exit

Select your choice: 1


Enter your query:
create table studinfo(usn varchar(10) primary key, name varchar(20));
Query Executed successfully
Select your choice: 3
Enter the query to be executed
desc studinfo
usn varchar(10) NO PRI
name varchar(20) YES null

Select your choice: 2


Enter your query
insert into studinfo values('1AY10MCA99','ARUN');
Record inserted Successfully.....

Select your choice: 3


Enter the query to be executed
select * from studinfo
RECORD 1 => 1BY10MCA99 ARUN

Select your choice: 1


Enter your query
Alter table studinfo add column course varchar(10)
Query Executed successfully

Select your choice: 3


Enter the query to be executed
desc studinfo;
usn varchar(10) NO PRI
name varchar(20) YES null
course varchar(10) YES null

Select your choice: 1


Enter your query
update studinfo set course='MCA' where usn='1AY10MCA99';

19
Advanced Java Programming Laboratory (13MCA47)

Query Executed successfully

Select your choice: 1


Enter your query
create unique index studnum on studinfo(usn);
Query Executed successfully

Select your choice: 1


Enter your query
create table faculty(fid varchar(10) primary key, fname varchar(20), subject varchar(20), usn
varchar(10) references studinfo(usn));
Query Executed successfully

Select your choice: 2


Enter your query
insert into faculty values('f2323','skt','MCA','1AY10MCA99');
Record inserted Successfully.....

Select your choice: 3


Enter the query to be executed
select name, fid, fname from studinfo left join faculty on studinfo.usn=faculty.usn;
RECORD 1 => ARUN f2323 skt

20
Advanced Java Programming Laboratory (13MCA47)

10. Write a JSP program to implement all the attributes of page directive tag.
index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes </title>
</head>
<body>
<form action="Directive.jsp">
<h1>Enter the value of n1 and n2: </h1>
Number1: <input type="number" name="n1"/><br/>
Number:2 <input type="number" name="n2"/><br/>
<input type="submit"/>
</form>
</body>
</html>

Directive.jsp

<%@ page contentType="text/html" pageEncoding="UTF-8"%>


<%@ page import="java.util.*" %>
<%@ page info="composed by DSATM" %>
<%@ page language="java"%>
<%@ page buffer="16kb" %>
<%@ page autoFlush="true" %>
<%@ page isThreadSafe="true" %>
<%@ page errorPage="error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes</title>
</head>
<body bgcolor="orange">
<h2> Usage of Import Attributes </h2>
<h2>Todays Date is: <%=new Date() %></h2>
<h2>To See the use of Error page enter n2 value zero and click submit </h2>
<% int n1=Integer.parseInt(request.getParameter("n1"));
int n2=Integer.parseInt(request.getParameter("n2"));
%>
<h2>Value of n1/n2 ==><%=n1/n2 %></h2>
</body>
</html>

21
Advanced Java Programming Laboratory (13MCA47)

error.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes</title>
</head>
<body>
<h2>Value of n2 variable of zero (n/0 is infinity)</h2>
<h3> Sorry an exception occured!</h3><br/>
<h3> The exception is: <%= exception%></h3>
</body>
</html>

22
Advanced Java Programming Laboratory (13MCA47)

11. An EJB application that demonstrates Session Bean (with appropriate business logic).

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

2. It will create ejb,war with project folder.

3. Right click on project-ejb and select new-> session bean -> give EJBName, location,package
and

session type (stateless)& select local interface. It will create java files like projectname.java,

local.java

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

business methods.

method : add

returnType:int

param1:int -a

param2:int-b (Press OK)

5. change in add method return (a + b)

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.

7. Right click on the content of servlet session and select insert code then select callEnterprise
Bean -

> Select sessionBean -> click ok.

8. Add the following line in the end of try block

out.println("Addition :" + sessionBeandemo.add(10, 20));

9. Set the relative URL of the project -> right click the project folder -> select properties -> run -
>

select display browser on run relative URL /MyServlet -> OK.

10. Build and run the project

23
Advanced Java Programming Laboratory (13MCA47)

12. An EJB application that demonstrates MDB (with appropriate business logic).

Services->glassfishserver3.1->right click start->right click view admin console->JMS Resource-


>Click on Connection Factories->New->

Pool Name: jms/queue -> Resource Type: javax.jms.QueueConnectionFactory

Click on Destination Resources -> New ->

JNDI Name: jms/dest -> Resource Type: javax.jms.Queue minimize the window

File -> NewProject -> Java EE -> EnterpriseApplication -> next -> Java EE Version: select Java
EE 5 ->

Check Create EJB module and Web Application module -> finish

In EJB Module

Right click EJB module -> select new message driven bean -> give EJB Name as MyBean and
package name as com -> Select server destinations as jms/dest

Type the following code in the method onMessage()

TextMessage tmsg=null;

tmsg=(TextMessage)message;

System.out.println(tmsg.getText()); /*Left click on error indicator and select surround statement


with try catch*/

In war Module

Select index.jsp file and type the following code inside body tag

<form action="NewServlet">

<table border="1">

<thead>

<tr>

<th></th>

<th></th>

</tr>

</thead>

<tbody>

24
Advanced Java Programming Laboratory (13MCA47)

<tr>

<td>Enter message</td>

<td><input type="text" name="msg" value="" /></td>

</tr>

</tbody>

</table>

<input type="submit" value="submit" />

</form>

Right Click on war module -> New -> Servlet -> write servlet name and package name -> finish

In NewServlet before try block of processRequest() method ->right click select insert code -
>Select send JMS message ->Connection factory : jms/queue

Before try block of processRequest type

String str=request.getParameter("msg");

sendJMSMessageToDest(str); /*Left click on error indicator and select surround statement with
try catch*/

clean and build application

deploy EJB module

In glass fish server select Applications click deployed file

Run war file

25
Advanced Java Programming Laboratory (13MCA47)

13. An EJB application that demonstrates persistence (with appropriate business logic).

Step 1: Creation of Project Application

1. File -> New Project -> Java EE -> Enterprise Application -> click next -> Give name for
project (ex: employee -> set Java EE version as Java EE 5 -> Finish.
2. At the end of creation you can see three modules generated.

Step 2: Create database

1. Select services-> Databases ->right click JavaDB ->create database ->right click
jdbc:derby://….. and connect

Step 3: Creation of Entity Bean

1. Right click on projects ejb module -> new -> Entity class -> Give class name and
package -> click next -> Select data source with your database -> Finish.
2. Change AUTO to IDENTITY and add the following code
String name;
int salary;
3. Select the variables -> right click over the selection -> insert code -> Getter and Setter…
-> select all -> Generate. You can see getter and setter method generated.

Step 4: Creation of Session bean for Entity Class

1. Right click on projects ejb module -> new -> Other -> Enterprise Java beans -> Session
bean for entity classes -> click Add all -> click next -> select local.

Step 5: Creating Servlet file

1. Right click on project war module -> new -> servlet -> Give name for servlet and
package -> next -> finish.
2. Inside the class definition -> Right click -> Insert code -> call enterprise bean -> select
your entity class( ex: EmployeeFacade) -> click ok.
3. Inside processRequest method add the following code,
employee dan=new employee();
dan.setName(request.getParameter("name"));
dan.setSalary(Integer.parseInt(request.getParameter("salary")));
empFacade.create(dan);
4. Left click on the error of first line code -> Add import (for your entity class).

Step 6: Creating jsp file

1. Change the code in index.jsp with your code.


2. Your code should produce two label and 2 text boxes and make sure that mapping servlet
with jsp file done correctly.

26
Advanced Java Programming Laboratory (13MCA47)

(<form action="EmployeeServlet">
Name: <input type="text" name="name" value="">
<br>
Salary: <input type="text" name="salary" value="">
<br><br>
<input type="submit" value="submit">
</form>)

Step 7: Executing the project

1. Right click on Application module -> Clean and bulid -> Right click on Application
module -> Deploy.
2. Under services window -> right click on glassfish server -> start the server -> right click
on glassfish server -> view admin console -> Applications -> click on entity bean class
name -> Launch -> click on first link -> Enter data and submit->
3. You can see the data on database by -> right click on your database -> refresh -> expand
your table -> view data.

Note: In the examination each student should do one question out of the above 13 questions

27

You might also like