Professional Documents
Culture Documents
(AUTONOMOUS)
RASIPURAM – 637 408.
FOR
B.Tech ( IT ) - V SEMESTER
Name: ______________________________________________________
Year/Sem:___________________ Branch:________________________
LIST OF EXPERIMENTS:
1. Write a Java program to store, delete and update data in a database with the support of jdbc-odbc
connectivity.
2. Write a Java program with servlets to create a dynamic html form to accept and display user
name and password with the help of ‘get ()’ and ‘post ()’ methods.
3. Write a Java program with servlets to store only valid data in a database with the support of jdbc-
odbc connectivity.
4. Write Java servlet program for ‘auto refreshing’ the webpage after given period of time.
5. Write a Java servlet program to demonstrate the use of cookies.
6. Write JSP program to implement form data validation to accept correct data.
7. Write a JSP script to demonstrate the use of <jsp: include …..> by displaying an external
webpage and <jsp: plugin ……> to run an applet.
8. Write a JSP program for demonstrating creation and accessing java beans.
9. Write a Java program to demonstrate the use of java swing components
TOTAL HOURS: 30
OUTCOMES:
At the end of the course, the student should be able to:
Design and implement Java programs to store, delete and update data in a database with the
support of jdbc-odbc connectivity.
Apply the different operation in web pages using servlet and JSP.
Designation
Signature
Date
INDEX
ALGORITHM :
1. Start the program.
2. Create the database for storing data.
3. Include the necessary packages in the java program.
4. Create connection statement and query statements.
5. Performing store , update and delete operation using jdbc-odbc connectivity.
6. Stop the program.
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
RESULT :
Thus a java program to store, delete and update data in a database with the support of jdbc-
odbc connectivity is implemented and executed successfully.
WRITE A JAVA PROGRAM WITH SERVLETS TO CREATE A
EX.NO: 2
DYNAMIC HTML FORM TO ACCEPT AND DISPLAY USER NAME
DATE: AND PASSWORD WITH THE HELP OF ‘GET ()’ AND ‘POST ()’
METHODS
AIM :
To write a java program with servlets to create a dynamic html form to accept and display
user name and password with the help of ‘get ()’ and ‘post ()’ methods
ALGORITHM :
1. Start the program.
2. Include the necessary servlets packages in the java program.
3. Create the index html program.
4. Create login page using java servlet.
5. Performing get() and post() operation using HTTPSERVLET.
6. Stop the program.
Brief Introduction
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the
protected service method by converting the request and response object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the
request from the service method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET
request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST
request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the
HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the
OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT
request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the
TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the
DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified
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 :
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
OUTPUT :
RESULT :
Thus a java program with servlets to create a dynamic html form to accept and
display user name and password with the help of ‘get ()’ and ‘post ()’ methods is implemented and
executed successfully.
EX.NO: 3 WRITE A JAVA PROGRAM WITH SERVLETS TO STORE ONLY
VALID DATA IN A DATABASE WITH THE SUPPORT OF JDBC-ODBC
DATE:
CONNECTIVITY.
AIM :
To write a java program with servlets to store only valid data in a database with the support
of jdbc-odbc connectivity.
ALGORITHM :
1. Start the program.
2. Include the necessary servlets packages in the java program.
3. Create the register html file.
4. Create Register page using java servlet.
5. Create xml for accessing web file.
6. Execute the program.
7. Stop the program.
PROGRAM :
register.html
We have getting input from the user using text fields and combobox. The information entered
by the user is forwarded to Register servlet, which is responsible to store the data into the
database.
<html>
<body>
<form action="servlet/Register" method="post">
<br/><br/>
<input type="submit" value="register"/>
</form>
</body>
</html>
Register.java
This servlet class receives all the data entered by user and stores it into the database
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);
int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
out.close();
}
web.xml file
The is the configuration file, providing information about the servlet.
<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>
</web-app>
OUTPUT :
USERNAME: RAMU
PASSWORD: ******
EMAIL ID : abcd@gamil.com
COUNTRY :INNDIA
RESULT :
Thus a java program with servlets to store only valid data in a database with the support of
jdbc-odbc connectivity is implemented and executed successfully.
EX.NO: 4 WRITE JAVA SERVLET PROGRAM FOR ‘AUTO REFRESHING’ THE
DATE: WEBPAGE AFTER GIVEN PERIOD OF TIME.
AIM :
To write java servlet program for ‘auto refreshing’ the webpage after given period of time.
ALGORITHM :
1. Start the program.
2. Include the necessary servlets packages in the java program.
3. Create the servlet program.
4. Create get method using java servlet.
5. Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5) using
httpservlet.
6. Execute the program.
7. Stop the program.
SERVLETS
Servlets provide a component-based, platform-independent method for building Webbased
applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases.
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or applications
on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to protect the resources on
a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software via the sockets and RMI mechanisms that you
have seen already.
Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.
Servlets Tasks
Servlets perform the following major tasks −
Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports the
Java Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.httppackages, which are a
standard part of the Java's enterprise edition, an expanded version of the Java class library that
supports large-scale development projects.
A servlet life cycle can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in detail.
The init() Method
The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as with the init
method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException {
// Initialization code...
}
The service() Method
The service() method is the main method to perform the actual task. The servlet container
(i.e. web server) calls the service() method to handle requests coming from the client( browsers) and
to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and
calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but
you override either doGet() or doPost() depending on what type of request you receive from the
client.
The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives
your servlet a chance to close database connections, halt background threads, write cookie lists or
hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy
method definition looks like this −
public void destroy() {
// Finalization code...
}
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
PROGRAM :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n"
);
}
doGet(request, response);
}
}
Now let us compile the above servlet and create the following entries in web.xml
<servlet>
<servlet-name>Refresh</servlet-name>
<servlet-class>Refresh</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Refresh</servlet-name>
<url-pattern>/Refresh</url-pattern>
</servlet-mapping>
OUTPUT :
RESULT :
Thus a java servlet program for ‘auto refreshing’ the webpage after given period of time is
implemented and executed successfully.
EX.NO: 5 WRITE A JAVA SERVLET PROGRAM TO DEMONSTRATE THE USE
DATE: OF COOKIES.
AIM :
ALGORITHM :
PROGRAM :
index.html
<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
//Reading cookies
Cookie c[]=request.getCookies();
//Displaying User name value from cookie
pwriter.print("Name: "+c[1].getValue());
//Displaying user password value from cookie
pwriter.print("Password: "+c[2].getValue());
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
web.xml
<web-app>
<display-name>BeginnersBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT :
Welcome Screen:
RESULT :
Thus a java servlet program to demonstrate the use of cookies is implemented and executed
successfully.
EX.NO: 6 WRITE JSP PROGRAM TO IMPLEMENT FORM DATA VALIDATION
DATE: TO ACCEPT CORRECT DATA.
AIM :
To write jsp program to implement form data validation to accept correct data.
ALGORITHM :
1. Start the program.
2. Create login jsp using HTML scripting.
3. Create acceptuser jsp program for verifying details.
4. Create a java program ValidateUser.java with importing Serializable.
5. Executing the program and get the output.
6. Stop the program.
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container
is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has
built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other
services a JSP needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web application.
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and
all JSP elements are converted to Java code. This code implements the corresponding
dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format. The output is furthur
passed on to the web server by the servlet engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML
content.
Finally, the web browser handles the dynamically-generated HTML page inside the HTTP
response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and
whether the modification date on the JSP is older than the servlet. If the JSP is older than its
generated servlet, the JSP container assumes that the JSP hasn't changed and that the generated
servlet still matches the JSP's contents. This makes the process more efficient than with the other
scripting languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a
Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular
servlet.
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four phases
have been described below −
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified since it was
last compiled, the JSP engine compiles the page.
PROGRAM :
Form to accept username and password : login.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Accept User Page</title>
</head>
<body>
<h1>Verifying Details</h1>
<%-- Include the ValidateUser.java class whose method
boolean validate(String, String) we will be using
--%>
<%-- Create and instantiate a bean and assign an id to
uniquely identify the action element throughout the jsp
--%>
<jsp:useBean id="snr" class="saagnik.ValidateUser"/>
<%-- Set the value of the created bean using form data --%>
<jsp:setProperty name="snr" property="user"/>
<jsp:setProperty name="snr" property="pass"/>
package saagnik;
import java.io.Serializable;
OUTPUT :
login.jsp
acceptuser.jsp
RESULT :
Thus a jsp program to form data validation and accept correct data is to be implemented and
executed successfully.
EX.NO: 7 WRITE A JSP SCRIPT TO DEMONSTRATE THE USE OF <JSP:
INCLUDE …..> BY DISPLAYING AN EXTERNAL WEBPAGE AND
DATE:
<JSP: PLUGIN ……> TO RUN AN APPLET.
AIM :
To write a jsp script to demonstrate the use of <jsp: include …..> by displaying an external
webpage and <jsp: plugin ……> to run an applet.
ALGORITHM :
1. Start the program.
2. Import the necessary packages in the java program.
3. Create MyApplet java program.
4. Perform Init() and start() methods.
5. Create a jsp program PluginDemo.jsp.
6. Executing the program and get the output.
7. Stop the program
JavaServer Page
JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special JSP tags,
most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of
a user interface for a Java web application. Web developers write JSPs as text files that combine
HTML or XHTML code, XML elements, and embedded JSP actions and commands.
Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control between
pages, and sharing information between requests, pages etc.
JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is requested.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications.
This means that JSP can play a part in the simplest applications to the most complex and
demanding.
Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −
vs. Active Server Pages (ASP)
The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable
to other operating systems and non-Microsoft Web servers.
vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with the web
server to perform complex tasks like database access and image processing etc.
<jsp:params> action
This action is an optional, direct child of the <jsp:plugin> action. It cannot be used elsewhere. If
specified, it must contain one or more <jsp:param> actions to provide additional parameters for the
component. For example:
<jsp:params>
</jsp:params>
<jsp:fallback> action
This action is an optional, direct child of the <jsp:plugin> action. Its purpose is to specify some
content which is used by the client browser in case the plugin cannot be started. Common usage is
to show some text that indicates there’s a problem of loading the component. For example:
1 <jsp:fallback>
2 <p>Could not load applet!</p>
3 </jsp:fallback>
This action cannot be used elsewhere outside the <jsp:plugin> action.
PROGRAM :
package net.codejava.applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JApplet;
import javax.swing.JLabel;
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
}
<jsp:params>
<jsp:param name="firstName" value="HI" />
<jsp:param name="lastName" value="JAVA" />
</jsp:params>
<jsp:fallback>
<p>Could not load applet!</p>
</jsp:fallback>
</jsp:plugin>
</div>
</body>
</html>
OUTPUT :
RESULT :
Thus a jsp script to demonstrate the use of <jsp: include …..> by displaying an external
webpage and <jsp: plugin ……> to run an applet is executed successfully.
EX.NO: 8 WRITE A JSP PROGRAM FOR DEMONSTRATING CREATION AND
DATE: ACCESSING JAVA BEANS.
AIM :
To write a jsp program for demonstrating creation and accessing java beans.
ALGORITHM :
Java Bean
A Java Bean is a java class that should follow following conventions:
It should have a no-arg constructor.
It should be Serializable.
It should provide methods to set and get the values of the properties, known as getter and
setter methods.
JavaBeans Properties
A JavaBean property is a named attribute that can be accessed by the user of the object. The
attribute can be of any Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class.
1.getPropertyName()
For example, if property name is firstName, your method name would be getFirstName() to
read that property. This method is called accessor.
2.setPropertyName()
For example, if property name is firstName, your method name would be setFirstName() to
write that property. This method is called mutator.
Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used in the
JSP. The full syntax for the useBean tag is as follows −
PROGRAM :
JavaBeans
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}
Accessing JavaBeans
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>
</body>
</html>
OUTPUT :
Student Age: 10
RESULT :
Thus a JSP program for demonstrating creation and accessing java beans is implemented
and executed successfully.
EX.NO: 9 WRITE A JAVA PROGRAM TO DEMONSTRATE THE USE OF JAVA
DATE: SWING COMPONENTS
AIM :
To write a java program to demonstrate the use of java swing components
ALGORITHM :
PROGRAM :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
if(e.getActionCommand().equals("Result"))
{
if(check())
count=count+1;
current++;
//System.out.println("correct ans="+count);
JOptionPane.showMessageDialog(this,"correct ans="+count);
System.exit(0);
}
}
void set()
{
jb[4].setSelected(true);
if(current==0)
{
l.setText("Que1: Which one among these is not a primitive datatype?");
jb[0].setText("int");jb[1].setText("Float");jb[2].setText("boolean");jb[3].setText("char");
}
if(current==1)
{
l.setText("Que2: Which class is available to all the class automatically?");
jb[0].setText("Swing");jb[1].setText("Applet");jb[2].setText("Object");jb[3].setText("Actio
nEvent");
}
if(current==2)
{
l.setText("Que3: Which package is directly available to our class without importing it?");
jb[0].setText("swing");jb[1].setText("applet");jb[2].setText("net");jb[3].setText("lang");
}
if(current==3)
{
l.setText("Que4: String class is defined in which package?");
jb[0].setText("lang");jb[1].setText("Swing");jb[2].setText("Applet");jb[3].setText("awt");
}
if(current==4)
{
l.setText("Que5: Which institute is best for java coaching?");
jb[0].setText("Utek");jb[1].setText("Aptech");jb[2].setText("SSS IT");jb[3].setText("jtek");
}
if(current==5)
{
l.setText("Que6: Which one among these is not a keyword?");
jb[0].setText("class");jb[1].setText("int");jb[2].setText("get");jb[3].setText("if");
}
if(current==6)
{
l.setText("Que7: Which one among these is not a class? ");
jb[0].setText("Swing");jb[1].setText("Actionperformed");jb[2].setText("ActionEvent");
jb[3].setText("Button");
}
if(current==7)
{
l.setText("Que8: which one among these is not a function of Object class?");
jb[0].setText("toString");jb[1].setText("finalize");jb[2].setText("equals");
jb[3].setText("getDocumentBase");
}
if(current==8)
{
l.setText("Que9: which function is not present in Applet class?");
jb[0].setText("init");jb[1].setText("main");jb[2].setText("start");jb[3].setText("destroy");
}
if(current==9)
{
l.setText("Que10: Which one among these is not a valid component?");
jb[0].setText("JButton");jb[1].setText("JList");jb[2].setText("JButtonGroup");
jb[3].setText("JTextArea");
}
l.setBounds(30,40,450,20);
for(int i=0,j=0;i<=90;i+=30,j++)
jb[j].setBounds(50,80+i,200,20);
}
boolean check()
{
if(current==0)
return(jb[1].isSelected());
if(current==1)
return(jb[2].isSelected());
if(current==2)
return(jb[3].isSelected());
if(current==3)
return(jb[0].isSelected());
if(current==4)
return(jb[2].isSelected());
if(current==5)
return(jb[2].isSelected());
if(current==6)
return(jb[1].isSelected());
if(current==7)
return(jb[3].isSelected());
if(current==8)
return(jb[1].isSelected());
if(current==9)
return(jb[2].isSelected());
return false;
}
public static void main(String s[])
{
new OnlineTest("Online Test Of Java");
}
}
OUTPUT :
RESULT :
Thus a Java program to demonstrate the use of Java swing components is implemented and
executed successfully
SAMPLE VIVA QUESTIONS
1. Name some OOPS Concepts in Java?
2. What do you mean by platform independence of Java?
3. What is JVM and is it platform independent?
4. What is the difference between JDK and JVM?
5. What is the difference between JVM and JRE?
6. Which class is the superclass of all classes?
7. Why Java doesn’t support multiple inheritance?
8. Why Java is not pure Object Oriented language?
9. What is difference between path and classpath variables?
10. What is the importance of main method in Java?
11. What is overloading and overriding in java?
12. What are access modifiers?
13. What is final keyword?
14. What is static keyword?
15. What is a servlet?
16. What are the advantages of Servlet over CGI?
17. What are common tasks performed by Servlet Container?
18. What is ServletConfig object?
19. What is ServletContext object?
20. What are the phases of servlet life cycle?
21. What are life cycle methods of a servlet?
22. why we should override only no-agrs init() method.
23. What is URL Encoding?
24. What are different methods of session management in servlets?
25. What is URL Rewriting?
26. What is JSP and why do we need it?
27. What are the JSP lifecycle phases?
28. What are JSP lifecycle methods?
29. Which JSP lifecycle methods can be overridden?
30. How can we avoid direct access of JSP pages from client browser?
31. What are different types of comments in JSP?
32. What is Scriptlet, Expression and Declaration in JSP?
33. What are JSP implicit objects?
34. When will Container initialize multiple JSP/Servlet Objects?
35. Can we use JavaScript with JSP Pages?
36. How can we prevent implicit session creation in JSP?
37. What is difference between JspWriter and Servlet PrintWriter?
38. How can we extend JSP technology?
39. Provide some JSP Best Practices?
40. What is a Java Bean?
41. What is a Stored Procedure in JDBC?
42. What are differences between Swing and AWT?
43. Why Swing components are called lightweight components?
44. What is JDBC API and when do we use it?
45. What are different types of JDBC Drivers?
46. What is JDBC Connection? Explain steps to get Database connection in a simple java
program.
47. What is the use of JDBC DriverManager class?
48. How to get the Database server details in java program?