J2EE Lab Manual
J2EE Lab Manual
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
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
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
f1) Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on
particular queries.
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.
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.
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);
}
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();
}
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());
}
}
public static void main(String args[])
{
final Lab1 stud1= new Lab1();
}
}
Output:
desc studinfo;
Record1=>usn
varchar(10)
NO
PRI
Record2=>name
varchar(20)
YES
Null
Queries Like:Insert
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).
Step 5:Right Click the WebPages folder and select new then select html -> Give the name of
HTML file -> Click finish.
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.
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>");
}
}
//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:
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).
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
//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
Output:
4) Write a JAVA Servlet Program to implement RequestDispatcher object (use include() and
forward() methods).
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
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>
//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>");
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>
Output:
5) Write a JAVA Servlet Program to implement and demonstrate get() and Post methods(Using
HTTP Servlet Class).
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">
//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;
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>
Output:
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.
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>");
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>
Output:
7) Write a JAVA Servlet Program to implement sessions (Using HTTP Session Interface).
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.
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.
rewriting requites large data transfer from and to the server. So, it leads to network traffic and access
may be become slow.
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"
Output:
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.
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.
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" %>
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" %>
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>
</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>
Output:
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.
3. Create the new package named Bean, under this Create the StudentBean.java.
Brief Introduction
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
<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>
//Firstpage.jsp
//Secondpage.jsp
//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)
{
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>
Output:
10) Write a JAVA JSP Program which uses <jsp:plugin> tag to run a applet.
1. Create a New java web project and give the name as Prog10
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.
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();
}
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:
11) Write a JAVA JSP Program which implements nested tags and also uses TagSupport Class.
1. Select New Project -> java web -> web application -> give the name as Program11 ->
Next -> select tomcat server-> next->finish
4. Create the TagHandler Class – NestLevel.java (i.e., java class file) under mypack
package.
Brief Introduction
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
//nested.tld
//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)
{
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:
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.
4. Right click inside projectname.java page -> click insert code -> add business method ->
and define business methods.
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
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;
}
//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>");
}
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:
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.
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.
8. Right click on program13-war -> new -> Servlet -> give the name as studEntity->give package name
mypack->next -> select deployment descriptor -> finish.
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.
}
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.
Brief Introduction
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
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;
}
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 + "]";
}
}
//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);
}
//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();
}
}
}
Output:
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 itClick 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
Step5:Click Destination Resources Click New and give JNDI Name jms/destination, Physical
Destination namedestination and Resource Typejavax.jms.Queue and Click OK
Step6: Select New project -> JavaEE -> Enterprise Application-> click next ->Prog14 and Set as Main
project -> next -> finish.
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-warNew Servletgive class name CallingClient package name
silver Click Next and click the check box add information to deployment descriptor(web.xml)
and Click Finish
Step10: Right click in first try and catch block(CallingClient.java file) and select insert CodeSend
JMS Message select Server Destinations:jms/destinationConnection 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);
}
Brief Introduction
• 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"));
}
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();
}
}
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();
}
}
}
}
Output:
Right Click on Prog14-warPropertiesRunRelative path/CallingClient Ok
Right Click on Prog14-war and Click Run.
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?
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..?
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())