Adv Java Lab Record

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 49

NIZAM COLLEGE

(AUTONOMOUS)

BCA VI Semester
ADVANCED JAVA PROGRAMMING
Lab Record

OSMANIA UNIVERSITY
HYDERABAD
2019
NIZAM COLLEGE
(Autonomous)
Basheerbagh, Hyderabad.
Ph. No: 040-23233317

CERTIFICATE

Department of Informatics

This is to certify that ________________________________________________

Bearing Hall Ticket No_________________________________


student of BCA VI Semester has completed Advanced Programming Lab Record
work during the year 2018-2019.

Internal Examiner
External Examiner

Head of the Department


1 Experiment : Working with NetBeans 8.2
1.1 Installing NetBeans on Windows
1.2 Executing “Hello World” Java program
1.3 Establishing Connection to Oracle Database
1.4 Implementing Servlet progam
2 Experiment : JDBC Programs using Statement
2.1 A program to test the connection with the database
2.2 A program to create a table
2.3 A program to insert record in a table
2.4 A program to fetch records from a table
2.5 A program to update record in a table
2.6 A program to delete record from a table
3 Experiment : JDBC Programs using PreparedStatement
3.1 A program to insert a record and select records
3.2 A program to update a record
4 Experiment : JDBC Programs using CallableStatement
4.1A program to execute a procedure to compute a square
5 Experiment : Servlet Programming
5.1 Servlet Execution on tomcat
5.2 A servlet program to print hello world
5.3A servlet program to display request details
5.4A servlet program to handle user form
5.5A servlet program to create a cookie
5.6A servlet program to display cookie
5.7A servlet program to do session tracking
6 Experiment : JSP Programming
6.1JSP program to display hello world.
6.2JSP program to demonstrate arithmetic operations
6.3JSP program to demonstrate jsp:forward action tag
6.4JSP program to request implicit object
6.5Developing a web application to insert record into Oracle Database using
JSP and JDBC
7 Experiment : JSTL Programs
7.1Write a JSTL program to demonstrate core tags
7.2 Write a JSTL program to find the given Number is Even OR Odd using
CORE Tags in JSTL
7.3 Write a JSTL program to demonstrate IF Statement using Core Tags
7.4Write a JSTL program to demonstrate Nested IF Statement Using Core
Tags
7.5Write a JSTL program to demonstrate XML tags to parse an XML
document
7.6Write a JSTL program to demonstrate XML tags to read an XML
document
Experiment 1: Working with NetBeans 8.2
Objective: To learn the steps for the installation of NetBeans on Windows.
Establish connection with the database from NetBeans. Execute Java and Servlet
programs on NetBeans.
1.1Installing NetBeans on Windows: Steps to install NetBeans

Step 0: Install JDK


To use NetBeans for Java programming, you need to first install Java Development
Kit (JDK).
Step 1: Download
Download "NetBeans IDE" installer
from http://netbeans.org/downloads/index.html. There are many "bundles"
available. For beginners, choose the 1st entry "Java SE" (e.g., "netbeans-8.2-
javase-windows.exe" 95MB).
Step 2: Run the Installer
Run the downloaded installer.

1.2Executing “Hello World” Java program: Steps to execute “Hello World”


program on NetBeans

Step 0: Launch NetBeans


Launch NetBeans. If the "Start Page" appears, close it by clicking the "cross"
button next to the "Start Page" title.
Step 1: Create a New Project

For each Java application, you need to create a "project" to keep all the source
files, classes and relevant resources.
1. From "File" menu ⇒ Choose "New Project...”.
2. The "Choose Project" dialog pops up ⇒ Under "Categories", choose "Java" ⇒
Under "Projects", choose "Java Application" ⇒ "Next".
3. The "Name and Location" dialog pops up ⇒ Under "Project Name", enter
"FirstProject" ⇒ In "Project Location", select a suitable directory to save your
works ⇒ Uncheck "Use Dedicated Folder for Storing Libraries" ⇒ Uncheck
"Create Main class" ⇒ Finish.
Step 2: Write a Hello-world Java Program

1. Right-click on "FirstProject" ⇒ New ⇒ Java Class (OR choose the "File"


menu ⇒ "New File..." ⇒ Categories: "Java", File Types: "Java Class" ⇒
"Next").
2. The "Name and Location" dialog pops up ⇒ In "Class Name", enter "Hello"
⇒ Delete the content in "Package" if it is not empty ⇒ "Finish".
3. The source file "Hello.java" appears in the editor panel. Enter the following
codes:
Public class Hello {
Public static void main(String [] args) {
System.ou.println(“Hello World”);
}
}
Step 3: Compile & Execute

There is no need to "compile" the source code in NetBeans explicitly, as NetBeans


performs the so-called incremental compilation (i.e., the source statement is
compiled as and when it is entered).
To run the program, right-click anywhere in the source (or from the "Run" menu)
⇒ Run File. Observe the output on the output console.
Notes:
 You should create a NEW Java project for EACH of your Java application.
 Nonetheless, NetBeans allows you to keep more than one programs in a
project. To run a particular program, open and right-click on the source file ⇒
Run File.

1.3Establishing a Connection to Oracle Database: steps to create a new


connection to the database.
1. Start the Oracle database.
2. Open the Services window (Window > Services). In the Services window,
right-click the Databases node and choose New Connection.

3. In the New Connection wizard, select Oracle Thin in the Driver dropdown
list.
4. Click Add and locate the ojdbc6.jar file that you previously downloaded.
Click Next.
5. In the Customize Connection panel of the wizard, enter the following values
and click Next.

Name Value

Driver Name Oracle Thin (with Service ID (SID))

localhost or127.0.0.1.
Note: In the case of a remote connection, provide the IP
Host
address or resolvable hostname of the machine where the
database is installed.

Port 1521 (default

XE (default SID for Oracle Database XE).


Service ID
Note: If you are connecting to a remote database, ask the
(SID)
database administrator to provide you with the database SID.

Username Enter the username that you used during database installation.
The default is “system”.
Enter the password for the selected username. The default is
Password
“manager”

6. Click Test Connection to confirm that the IDE is able to connect to the
database. Click Next. If the attempt is successful, the message "Connection
succeeded" is displayed in the wizard.

7. Select HR in the Select Schema dropdown list. Click Finish.


.
The new connection will appear under the Databases node in the Services window.
You can expand it and start browsing the database object's structure.
Change the display name for the connection node: choose Properties from the
node's popup menu and click the ellipsis button for the Display Name property.
Enter OracleDB as the Display Name and click OK.
Note. Although the steps above demonstrate the case of connecting to a local
database instance, the steps for connecting to a remote database are the same. The
only difference is that instead of specifying localhost as the hostname, enter the IP
address or hostname of the remote machine where Oracle Database is installed.
Java Database Connectivity with Oracle
To connect java application with the oracle database, we need to know following
information for the oracle database:

1. Driver class: The driver class for the oracle database


is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is
running, we may also use IP address, 1521 is the port number and XE is the
Oracle service name. You may get all these information from the
tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the
oracle database

1.4Implementing a Servlet progam: Writing a Hello-World Servlet/JSP


Web Application

Create a New Servlet/JSP Project

1. From "File" menu ⇒ choose "New Project...".


2. "Choose Project" ⇒ Under "Categories", choose "Java Web" ⇒ Under
"Projects", choose "Web Application" ⇒ "Next".
3. "Name and Location" ⇒ In "Project Name", enter "HelloServletJSP" ⇒ In
"Project Location", select a suitable directory to save your works ⇒ Check
"Set as Main Project" ⇒ Next.
4. "Server and settings" ⇒ Choose your server, or "add" a new server ⇒ Next.
5. "Frameworks" ⇒ Select none for pure servlet/JSP application ⇒ Finish.
Writing a Hello-World JSP
A JSP page called "index.jsp" is automatically created, which says "Hello world!".
To execute this JSP, right-click on the project ⇒ "Run". The URL
is http://localhost:8080/HelloServletJSP/index.jsp.
Writing a Hello-World Servlet
1. Right-click on the project "HelloServletJSP" ⇒ New ⇒ Servlet.
2. "Name and Location" ⇒ In "Class Name", enter "HelloServlet" ⇒ In
"Package", enter "hello" ⇒ Next.
3. "Configure Servlet Deployment" ⇒ In "Servlet Name", enter
"HelloServletExample" ⇒ In "URL Pattern", enter "sayhello" ⇒ Finish.
4. Enter the following codes for " HelloWorldSrv.java":
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldSrv extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse
resp) throws ServletException, IOException {
//set response content type
resp.setContentType("text/html");
//get PrintWriter object from response object
PrintWriter out = resp.getWriter();
out.println("<h1>Welcome to Servlet</h1>");
out.println("<h3>Hello World</h3>");
//close the stream
out.close();
}// doGet(-,-)
}// class
5. To execute the servlet: Right-click on the project ⇒ run ⇒ Change the URL
to http://localhost:8080/HelloServletJSP/sayhello.

Generating a WAR-file for a Web Application


A WAR (Web Archive) file is basically a zip file for distributing web application
in single file. You can use WinZip or WinRAR to inspect or unzip the war file.
To distribute the project as a war-file, right-click project ⇒ "Clean and Build". The
war file is created in the "dist" directory. You can deploy the web application by
dropping the war-file into Tomcat's "webapps" directory. Tomcat will
automatically unzip the war-file and deploy the application upon startup.
Debugging Web Application
The most important reason for using IDE is to use the graphic debugger for
debugging the program. You can set a breakpoint in your server-side Java codes,
and "Debug" a web application, similar to a standalone application.
Experiment 2: JDBC Programs using Statement

Objective :- Write programs to provide database connectivity using statement


to a
employee table to insert, update, delete data.

JDBC interfaces and classes


Let’s take an overview look at the JDBC’s main interfaces and classes with which
we usually
work. They are all available under the java.sql package:
 DriverManager: this class is used to register driver for a specific database
type and to establish a database connection with the server via its
getConnection() method.
 Connection: this interface represents an established database connection
(session)
from which we can create statements to execute queries and retrieve results,
get metadata about the database, close connection, etc.
 Statement and PreparedStatement: these interfaces are used to execute
SQL query and parameterized SQL query, respectively. Statement is the
super interface of
the PreparedStatement interface. Their commonly used methods are:
boolean execute(String sql): executes a general SQL statement. It
returns true if
the query returns a ResultSet, false if the query returns an update
count or returns
nothing. This method can be used with a Statement only.
int executeUpdate(String sql): executes an INSERT, UPDATE or
DELETE statement and returns an update account indicating number
of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows
affected).
ResultSet executeQuery(String sql): executes a SELECT statement
and returns
a ResultSet object which contains results returned by the query.
 ResultSet: contains table data returned by a SELECT query. Use this object
to iterate over rows in the result set using next() method, and get value of a
column in the current row using getXXX() methods (e.g. getString(),
getInt(), getFloat() and so on). The column value can be retrieved either by
index number (1-based) or by column name.
 SQLException: this checked exception is declared to be thrown by all the
above methods, so we have to catch this exception explicitly when calling
the above classes’ methods.

1 A prepared statement is one that contains placeholders (in form question


marks ?) for dynamic values will be set at runtime. For example: SELECT *
from Users WHERE user_id=?
Here the value of user_id is parameterized by a question mark and will be set by
one of the setXXX() methods from the PreparedStatement interface, e.g.
setInt(int index, int value).

2 CallableStatement interface is used to call the stored procedures and


functions.
We can have business logic on the database by the use of stored procedures and
functions that will make the performance better because these are precompiled.
The prepareCall() method of Connection interface returns the instance of
CallableStatement. Syntax is given below:
public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
The example to get the instance of CallableStatement is given below:
CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
It calls the procedure myprocedure that receives 2 arguments.
Experiment 2: JDBC Programs using Statement
2.1A program to test the connection with the database

import java.sql.*;
public class ConnectionTest {
public static void main(String[] args) {
Connection con = null;
try {
// loading jdbc driver with DriverManager Service
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establish the connection
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
if (con != null) {
System.out.println("Connection is established Successfully");
}
else {
System.out.println("Connection is failed ");
}
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}// main
}// class
Experiment 2: JDBC Programs using Statement
2.2A program to create a table

import java.sql.*;
public class CreateTable {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
String qry = "create table employee(eid number(3) primary key,ename
varchar2(15),
addr varchar2(10))";
st = con.createStatement();
st.executeUpdate(qry);
System.out.println("employee table is created in database");
//close jdbc object
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}//main
}//class
Experiment 2: JDBC Programs using Statement
2.3A program to insert record into the database

import java.sql.*;
public class InsertData {
public static void main(String[] args) {
Connection con =null;
Statement st =null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"manager");
st =con.createStatement();
int eid=662;
String name ="John";
String addr = "Hyderabad";
name = "'"+name+"'";
addr = "'"+addr+"'";
String qry="insert into employee values("+eid+","+name+","+addr+")";
System.out.println(qry);
int result = st.executeUpdate(qry);
if(result!=0)
{
System.out.println("Record is inserted in database");
}
else {
System.out.println("Record is failed to insert");
}
st.close();
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}//main
}//class
Experiment 2: JDBC Programs using Statement
2.4A program to update a record in the database
import java.sql.*;
public class UpdateTable {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
String addr = "New Jersey";
addr = "'" + addr + "'";
String qry = "update employee set addr = " + addr + " where eid = 662";
System.out.println(qry);
st = con.createStatement();
int result = st.executeUpdate(qry);
if (result != 0) {
System.out.println(result+ " Record(s) is/are updated successfully");
} else {
System.out.println("Failed to update record(s)");
}
//close jdbc object
st.close();
con.close();
} catch(Exception e) {
e.printStackTrace();
}
}//main
}//class
Experiment 2: JDBC Programs using Statement
2.4 A program to delete a record in the database
import java.sql.*;
public class DeleteRecords {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
st = con.createStatement();
String name = "John";
name = "'" + name + "'";
String qry = "delete from employee where ename = " + name;
System.out.println(qry);
int result = st.executeUpdate(qry);
if (result != 0) {
System.out.println("Record is deleted from database");
}
else {
System.out.println("Deletion operation is unsuccessful");
}
//close jdbc objects
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}//main
}//class
Experiment 3: JDBC Programs using PreparedStatement
3.1 A program to insert a record and select records

import java.sql.*;
public class SelectPrepared {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
ps = con.prepareStatement("insert into employee values(?,?,?)");
// set values to query parameters
ps.setInt(1, 10);
ps.setString(2, "Alice");
ps.setString(3, "Hyd");
int result = ps.executeUpdate();
if (result != 0) {
System.out.println("Record is successfully inserted");
} else {
System.out.println("Inserting record is failed");
}
String qry = "select * from employee where ename = ?";
ps = con.prepareStatement(qry);
// set value to query parameter
ps.setString(1, "Alice");
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t"
+ rs.getString(3));
}
// close jdbc objects
rs.close();
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}}}
Experiment 3: JDBC Programs using PreparedStatement
3.2 A Program to update records
import java.sql.*;
public class UpdatePrepared {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
ps = con.prepareStatement("update employee set addr=? where
eid=?");
// set values to query parameters
ps.setString(1, "Telangana");
ps.setInt(2, 10);
int result = ps.executeUpdate();
if (result != 0) {
System.out.println("RECORD IS SUCCEFULLY
UPDATED");
} else {
System.out.println("RECORD IS FAILED TO UPDAE");
}
// selecting data from student
ps = con.prepareStatement("select * from employee where
ename=?");
// set value to query parameter
ps.setString(1, "Alice");
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t"
+ rs.getString(3));
}
// close jdbc objects
rs.close();
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Experiment 4: JDBC Programs using CallableStatement
4.1 A program to execute a procedure to compute a square
Square procedure
create or replace procedure square(x IN number, y out number) is
BEGIN
y := x * x;
END;
/

A program to execute a procedure to compute a square

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;

public class Callable {


public static void main(String[] args) throws Exception {
Connection connection = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
connection =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system", "manager");
CallableStatement cStmt = connection.prepareCall("{call square(?,?)}");
cStmt.setInt(1, 20);
cStmt.registerOutParameter(2, Types.INTEGER);
cStmt.execute();
System.out.println("The Square is : " + cStmt.getInt(2));
cStmt.close();
}
}
Experiment 5: Servlet Programming
5.1Servlet Execution on tomcat
Servlets Tomcat: Install Tomcat server of your choice version by downloading
from Apache site. Many versions of Tomcat can be found in the following link.
https://tomcat.apache.org/download-80.cgi
Check with the documentation of what JDK or JRE version is compatible to the
specific Tomcat version. For example I loaded Tomcat 5.0 and is compatible
with JDK 6.0.
While installation, it asks the port number and I have entered 8089 (default is
displayed as 8080. I have not preferred 8080 for the reason on many
systems Oracle server will be working on 8080. For this reason better choose a
different port number). Later, give your own password.
Step 1: When installed, Tomcat gives many folders of which a few are given
hereunder used for execution. See the following one.
C:\Program Files\Apache Software Foundation\Tomcat 5.0\common\lib\servlet-
api.jar;
Keep the above JAR file in the classpath of Windows Environment Variables;
else the servlet program will not be compiled.
Note: Now, a fresher should be careful here in the following steps. Steps are very
simple but should be followed carefully. Any small mistake committed, Tomcat
simply refuses to execute your servlet.
Step 2: Creating your own directory structure.
You also get the following folders.
C:\Program Files\Apache Software Foundation\Tomcat\webapps
In the above webapps folder create your own new folder xxx.
Step 3: create a servlet
Write a servlet program, say demo.java in your current directoty and compile it as
usual with javac command and obtain demo.class. Copy the demo.class file from
your current directory to classes folder available in the above mentioned classpath.
C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\xxx\WEB-
INF\classes

Copying the .class file of servlet to classes folder is known as deployment.


Step 3: create deployment descriptor.
Open the web.xml file available in the following folder.
C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\india\WEB-
INF

In the web.xml file add the following code.


<web-app>
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>demo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/example</url-pattern >
</servlet-mapping >
</web-app>
Now the alias name of demo servlet is example. Client should call the demo
Servlet with the name example. Observe, this example you used in HTML file.
The web.xml file is known as deployment descriptor as it describes the
deployment information of a servlet. Learn more at Deployment Descriptor –
web.xml in Servlets.
Step 4: Run the Tomcat server.
Step 7: Open a browser. Run the servlet program
http://localhost:8089/xxx/example
Experiment 5: Servlet Programming
5.2A servlet program to print hello world

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldSrv extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//set response content type
resp.setContentType("text/html");
//get PrintWriter object from response object
PrintWriter out = resp.getWriter();
out.println("<h1>Welcome to Servlet</h1>");
out.println("<h3>Hello World</h3>");
//close the stream
out.close();
}// doGet(-,-)
}// class

Web.xml

<web-app>
<servlet>
<servlet-name> HelloWorldSrv </servlet-name>
<servlet-class> HelloWorldSrv </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> HelloWorldSrv </servlet-name>
<url-pattern>/hello</url-pattern >
</servlet-mapping >
</web-app>
Experiment 5: Servlet Programming
5.3A servlet program to print request details

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestInfoSrv extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<h3>REQUEST INFORMATION</h3>");
out.println("<h3>Method: " + req.getMethod() + "</h3>");
out.println("<h3>Request URI: " + req.getRequestURI() + "</h3>");
out.println("<h3>Request URL: " + req.getRequestURL() + "</h3>");
out.println("<h3>Protocol: " + req.getProtocol() + "</h3>");
out.println("<h3>PathInfo: " + req.getPathInfo() + "</h3>");
out.println("<h3>Remote Address: " + req.getRemoteAddr() +
"</h3>");
out.println("<h3>Context path: " + req.getContextPath() + "</h3>");
//close stream out.close();
}//doGet
}//class
Web.xml

<web-app>
<servlet>
<servlet-name> RequestInfoSrv</servlet-name>
<servlet-class> RequestInfoSrv</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> RequestInfoSrv</servlet-name>
<url-pattern>/request</url-pattern >
</servlet-mapping >
</web-app>
Experiment 5: Servlet Programming
5.4A servlet program to handle user forms
RequestParams.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>RequestParams</title>
</head>
<body>
<form action="RequestParametersSrv" method="get">
<pre>
<h1>Request Parameters</h1>
Enter First Name: <input type="text" name="fname"><br>
Enter Last Name: <input type="text" name="lname"><br>
Enter Course: <input type="text" name="cname"><br>
<input type="submit" value="Submit">
</pre>
</form>
</body>
</html>

RequestParametersSrv

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestParametersSrv extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
// reading request parameters
String firstName = req.getParameter("fname");
String lastName = req.getParameter("lname");
String cource = req.getParameter("cname");
out.println("<h4>Reading Request Paramter values</h4>");
out.println("<h4>First Name: " + firstName + "</h4>");
out.println("<h4>Last Name: " + lastName + "</h4>");
out.println("<h4>Cource : " + cource + "</h4>"); //close stream
out.close();
}//doGet
}//class

Web.xml

<web-app>
<servlet>
<servlet-name> RequestParametersSrv</servlet-name>
<servlet-class> RequestParametersSrv</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> RequestParametersSrv</servlet-name>
<url-pattern>/RequestParametersSrv</url-pattern >
</servlet-mapping >
</web-app>
Experiment 5: Servlet Programming
5.5A servlet program to create a cookie
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetCookiesSrv extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
// create in memory cookies
Cookie ck1 = new Cookie("TS", "Hyderabad"); Cookie ck2 = new
Cookie("KA", "Banglore"); // add cookies
resp.addCookie(ck1);
resp.addCookie(ck2);
// create persistent cookies
Cookie ck3 = new Cookie("India", "Delhi");
Cookie ck4 = new Cookie("USA", "Washington");
ck3.setMaxAge(1800);
ck4.setMaxAge(1800);
// add cookies
resp.addCookie(ck3);
resp.addCookie(ck4);
// generate Response
out.println("<h1>Cookies are successfully created</h1>");
//close the stream out.close();
}
}
Web.xml

<web-app>
<servlet>
<servlet-name> SetCookiesSrv</servlet-name>
<servlet-class> SetCookiesSrv</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> SetCookiesSrv</servlet-name>
<url-pattern>/cookie</url-pattern >
</servlet-mapping >
</web-app>
Experiment 5: Servlet Programming
5.6A servlet program to display a cookie
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowCookiesSrv extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<h3>Cookies are displayed below</h3>");
//read and display cookies
Cookie ck[] = req.getCookies();
//gives all cookies along with the request
out.println("<h2> COOKIE NAME || COOKIE VALUE </h2>");
if (ck != null) {
for (Cookie cck : ck) {
out.println("<h2>" + cck.getName() + " || " + cck.getValue()+
"</h2>");
}
}
}//doGet
}//class
Web.xml

<web-app>
<servlet>
<servlet-name> ShowCookiesSrv</servlet-name>
<servlet-class> ShowCookiesSrv</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> ShowCookiesSrv</servlet-name>
<url-pattern>/showcookie</url-pattern >
</servlet-mapping >
</web-app>
Experiment 5: Servlet Programming
5.7A servlet program to do session tracking
Session.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>SessionTraking</title>
</head>
<body>
<form action="FirstSrv" method="get">
<h1 style="text-align: center;">HttpSession Tracking</h1> <h1>IT Filling
Registration</h1> <pre>
Enter PName:<input type="text" name="pname">
Enter FName:<input type="text" name="fname">
<input type="submit" value="Continue">
</pre>
</form>
</body>
</html>
Firstsrv.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstSrv extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
// read form1 data
String pname = req.getParameter("pname");
String fname = req.getParameter("fname");
//create Session for browser window
HttpSession ses = req.getSession(true);
//store form1/req1 data in Session Attribute
ses.setAttribute("pname", pname);
ses.setAttribute("fname", fname);
//generate dynamic form2 data
out.println("<form action='SecondSrv' method='get'>");
out.println("<pre><h1>SESSION TRACKING</h1>");
out.println("<h1>IT FILING REGISTRATION</h1>");
out.println("Income for this year <input type ='text' name='income'>");
out.println("Tax <input type ='text' name='tax'>");
out.println("<input type ='submit' value='Register'><pre>");
out.println("</form>");
out.println("<br>Session ID: " + ses.getId());
Date created = new Date(ses.getCreationTime());
Date accessed = new Date(ses.getLastAccessedTime());
out.println("Session Created: " + created);
out.println("Last Accessed: " + accessed);
}
}
Secondsrv.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondSrv extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
// read form2/req2 data
int income = Integer.parseInt(req.getParameter("income"));
int tax = Integer.parseInt(req.getParameter("tax"));
//Get access to Session object
HttpSession ses = req.getSession(false);
//read form2/req2 data from session attributes
String pname = (String) ses.getAttribute("pname");
String fname = (String) ses.getAttribute("fname");
//display form1, form2 data
out.println("<pre><h1>SESSION TRACKING</h1>");
out.println("<h1>FORM1 DATA: Name: " + pname + " & " +
"F_Name: "+fname + "<h1>");
out.println("<h1>FORM2 DATA: Income: " + income + " & " + "Tax:
" + tax+"</h1><pre>");
out.println("<br>Session ID: " + ses.getId()); Date created = new
Date(ses.getCreationTime()); Date accessed = new
Date(ses.getLastAccessedTime());
out.println("Session Created: " + created);
out.println("Last Accessed: " + accessed);
//invalidate the session ses.invalidate();
out.println("<a href='SessionTracking.html'><h4>Home</h4></a>");
}
}

Web.xml
<web-app>
<servlet>
<servlet-name> FirstSrv </servlet-name>
<servlet-class>FirstSrv</servlet-
class> </servlet>
<servlet-mapping>
<servlet-name> FirstSrv </servlet-name>
<url-pattern>/ FirstSrv </url-pattern>
</servlet-mapping>
<servlet>
<servlet-name> SecondSrv </servlet-name>
<servlet-class>SecondSrv</servlet-
class> </servlet>
<servlet-mapping>
<servlet-name> SecondSrv </servlet-name>
<url-pattern>/ SecondSrv </url-pattern>
</servlet-mapping>
</web-app>
Experiment 6 : JSP Programming
6.1JSP program to display hello world.
<html>
<body>
<! -- This is the JSP file-->
<%
out.println ("Hello World !");
%>
</body>
</html>
Experiment 6 : JSP Programming
6.2JSP program to demonstrate arithmetic operations\
Arithmetic.html

<html>
<body>
<form action="arithmetic.jsp">
operator1:<input type="text" name="op1"/><br>
operator2:<input type="text" name="op2"/><br>
<input type="submit" name="operation" value="SUBMIT" />
</form>
</body>
</html>

Arithmetic.jsp
<%
int opr1=Integer.parseInt(request.getParameter("op1"));
int opr2=Integer.parseInt(request.getParameter("op2"));
int sum=opr1+opr2;
int diff=opr1-opr2;
int mul=opr1*opr2;
int div=opr1/opr2;
%>
Sum of 2 numbers = <%= sum %><br>
Difference of 2 numbers = <%= diff %><br>
Multiplication of 2 numbers = <%= mul %><br>
Division of 2 numbers = <%= div %>
Experiment 6 : JSP Programming
6.3JSP program to demonstrate jsp:forward action tag
printdate1.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate2.jsp" />
</body>
</html>

printdate2.jsp
<html>
<body>
<%out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Experiment 6 : JSP Programming
6.4JSP program to request implicit object
Implicitobj.html
<form action="implicitobj.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

Implicitobj.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
Experiment 6 : JSP Programming
6.5Developing a web application to insert record into Oracle Database using
JSP and JDBC
Insertrec.html
<html>
<head>
<title> Insert Record using JSP </title>
</head>
<body>
<form action="InsertRec">
Id : <input type="text" name="id"><br>
Name : <input type="text" name="name"><br>
Sal : <input type="text" name="sal"><br>
<input type="submit" name="Submit" value="Insert">
</form>
</body>
</html>
insertrec.jsp

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


<%
int id = Integer.parseInt(request.getParameter("id"));
String name=request.getParameter("name").toString();
int sal = Integer.parseInt(request.getParameter("sal"));
%>
Id: <%= id %> <br>
Name: <%= name %> <br>
Sal: <%= sal %> <br>
<%Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system",
"manager");
%>
Connection Established
<% Statement stat = conn.createStatement();
stat.executeUpdate("insert into emp values('" +id+ "','" +name +"','"+ sal+ "')");
%>
Experiment 7 : JSTL Programs
7.1Write a JSTL program to demonstrate core tags
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Tag Example</title>
</head>
<body>
<c:out value="${'Welcome to Nizam College'}"/>
</body>
</html>
Experiment 7 : JSTL Programs
7.2 Write a JSTL program to find the given Number is Even OR Odd using
CORE Tags in JSTL
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<h1>JSTL c:when, c:otherwise, c:choose</h1>
<c:set value="10" var="num"></c:set>
<c:choose>
<c:when test="${num%2==0}">
<c:out value="${num} is even number"></c:out>
</c:when>
<c:otherwise>
<c:out value="${num} is odd number"></c:out>
</c:otherwise>
</c:choose>
</body>
</html>
Experiment 7 : JSTL Programs
7.3 Write a JSTL program to demonstrate IF Statement using Core Tags
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="income" scope="session" value="${4000*4}"/>
<c:if test="${income > 8000}">
<p>My income is: <c:out value="${income}"/><p>
</c:if>
</body>
</html>
Experiment 7 : JSTL Programs
7.4Write a JSTL program to demonstrate Nested IF Statement Using Core
Tags
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="income" scope="session" value="${4000*4}"/>
<p>Your income is : <c:out value="${income}"/></p>
<c:choose>
<c:when test="${income <= 1000}">
Income is not good.
</c:when>
<c:when test="${income > 10000}">
Income is very good.
</c:when>
<c:otherwise>
Income is undetermined...
</c:otherwise>
</c:choose>
</body>
</html>
Experiment 7 : JSTL Programs
7.5Write a JSTL program to demonstrate XML tags to parse an XML
document
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>x:if Tags</title>
</head>
<body>
<h2>Vegetable Information:</h2>
<c:set var="vegetables">
<vegetables>
<vegetable>
<name>onion</name>
<price>40</price>
</vegetable>
<vegetable>
<name>Potato</name>
<price>30</price>
</vegetable>
<vegetable>
<name>Tomato</name>
<price>90</price>
</vegetable>
</vegetables>
</c:set>
<x:parse xml="${vegetables}" var="output"/>
<x:if select="$output/vegetables/vegetable/price < 100">
Vegetables prices are very low.
</x:if>
</body>
</html>
Experiment 7 : JSTL Programs
7.6 Write a JSTL program to demonstrate XML tags to read an XML
document
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html> <head>
<title>XML Tags</title></head>
<body>
<h2>Vegetable Information:</h2>
<c:set var="vegetable">
<vegetables>
<vegetable>
<name>onion</name>
<price>40/kg</price>
</vegetable>
<vegetable>
<name>Potato</name>
<price>30/kg</price>
</vegetable>
<vegetable>
<name>Tomato</name>
<price>90/kg</price>
</vegetable> </vegetables>
</c:set>
<x:parse xml="${vegetable}" var="output"/>
<b>Name of the vegetable is</b>:
<x:out select="$output/vegetables/vegetable[1]/name" /><br>
<b>Price of the Onion is</b>:
<x:out select="$output/vegetables/vegetable[1]/price" /><br>
<b>Name of the vegetable is</b>:
<x:out select="$output/vegetables/vegetable[2]/name" /><br>
<b>Price of the Potato is</b>:
<x:out select="$output/vegetables/vegetable[2]/price" /><br>
<b>Name of the vegetable is</b>:
<x:out select="$output/vegetables/vegetable[3]/name" /><br>
<b>Price of the Veg is</b>:
<x:out select="$output/vegetables/vegetable[3]/price" /><br>
</body>

You might also like