Java Programming (BCSE 3074) Lab File: JULY 2020

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

JAVA PROGRAMMING

(BCSE 3074) Lab File

Submitted by

Name : Shashank Singh

Enrollment No. 18021011648

Admission No. 18SCSE1010417

SCHOOL OF COMPUTER SCIENCE AND ENGINEERING

JULY ‘2020

Shashank Singh (18SCSE1010417)


INDEX
Exp Page.No. REMARKS
Experiment name
NO
1 Write a Java program to create an ArrayList, add all the months of a year and
print the same.
1

2 Create an ArrayList that can store only Strings.


Create a printAll method that will print all the elements of the ArrayList using 2
an Iterator.
3 Write a program that will have a Vector which is capable of storing Employee
objects. Use an Iterator and enumeration to list all the elements of the Vector.
3

4 Develop a java class with a instance variable H1 (HashSet) add a method


saveCountryNames(String CountryName) , the method should add the passed
4
country to a HashSet (H1) and return the added HashSet(H1).
Develop a method getCountry(String CountryName) which iterates through the
HashSet and returns the country if exist else return null.
NOTE: You can test the methods using a main method.
5
6

Create a table USER with above details using SQL commands. Establish JDBC
connection and insert 3 records into the table USER as follows using a java
program :

6 For the same table created in Program 5, display all the records existing in the
table USER using java program. 9

7 Using the table of Program 5, change the UserType for Ganesh to Admin
11

Shashank Singh (18SCSE1010417)


8 Delete the row form table USER (Program 5) where the Name is Hari using a
java progrm. 13

9 Write a servlet application to print the current date and time


15

10 Write a servlet application to establish communication between html and servlet


page using hyperlink 16

11 Write an application to demonstrate the session tracking in Servlet.


18

12 Write a simple JSP program to print the current date and time.
21

13 Write a program in JSP to auto refresh a page.


22

Shashank Singh (18SCSE1010417)


EXPERIMENT- 1

Aim: Write a Java program to create an ArrayList, add all the months of a year and print the
same.

CODE:

import java.util.*;
class Exp1{
public static void main(String args[]){
ArrayList<String> alist=new ArrayList<String>();

alist.add("Jan");
alist.add("Feb");
alist.add("Mar");
alist.add("Apr");
alist.add("May");
alist.add("Jun");
alist.add("Jul");
alist.add("Aug");
alist.add("Sep");
alist.add("Oct");
alist.add("Nov");
alist.add("Dec");

//displaying elements
System.out.println(alist);

}
}

Output:

Shashank Singh (18SCSE1010417)


EXPERIMENT- 2

Aim: Create an ArrayList that can store only Strings. Create a printAll method that will print all
the elements of the ArrayList using an Iterator.
Code:

import java.util.*;

public class Exp1 {

public static void main(String[] args)


{
ArrayList<String> list
= new ArrayList<>();
list.add("MOHIT");
list.add("odyssey");
list.add("origin");
list.add("alexandrio");
list.add("ezio");
System.out.println("The list is: \n"
+ list);
Iterator<String> iter
= list.iterator();
System.out.println("\nThe iterator values"
+ " of list are: ");
while (iter.hasNext()) {
System.out.print(iter.next() + " ");
}
}
}

Output:

Shashank Singh (18SCSE1010417)


EXPERIMENT- 3

Aim: Write a program that will have a Vector which is capable of storing Employee objects. Use
an Iterator and enumeration to list all the elements of the Vector.

Code:

import java.util.Vector;
import java.util.Enumeration;

public class Exp2 {


public static void main(String[] args) {
// Create a Vector
Vector<String> vector = new Vector<String>();

// Add elements into Vector


vector.add("MOHIT");
vector.add("odyssey");
vector.add("origin");
vector.add("alexandrio");
vector.add("ezio");

// Get Enumeration of Vector elements


Enumeration en = vector.elements();

/* Display Vector elements using hashMoreElements()


* and nextElement() methods.
*/
System.out.println("Vector elements are: ");
while(en.hasMoreElements())
System.out.println(en.nextElement());
}
}

Output:

Shashank Singh (18SCSE1010417)


EXPERIMENT- 4

Aim: Develop a java class with a instance variable H1 (HashSet) add a method
saveCountryNames(String CountryName) , the method should add the passed country to a
HashSet (H1) and return the added HashSet(H1).
Develop a method getCountry(String CountryName) which iterates through the HashSet and
returns the country if exist else return null.
NOTE: You can test the methods using a main method.

Code:
import java.util.HashSet;
import java.util.Iterator;

public class Exp3 {


HashSet<String> H1 = new HashSet<>();

public HashSet<String> saveCountryNames(String CountryName) {


H1.add(CountryName);
return H1;
}

public String getCountry(String CountryName) {


Iterator<String> it = H1.iterator();

while (it.hasNext()) {
if (it.next().equals(CountryName))
return CountryName;
}

return null;
}
public static void main(String[] args) {
Exp3 countries = new Exp3();
countries.saveCountryNames("India");
countries.saveCountryNames("USA");
countries.saveCountryNames("Pakistan");
countries.saveCountryNames("Bangladesh");
countries.saveCountryNames("China");

System.out.println("China: " + countries.getCountry("China"));


System.out.println("Japan: " + countries.getCountry("Japan"));
}

Shashank Singh (18SCSE1010417)


}

Output:

Shashank Singh (18SCSE1010417)


EXPERIMENT- 5

Aim:

Create a table USER with above details using SQL commands. Establish JDBC connection and insert 3
records into the table USER as follows using a java program :

Code:

mysql_tables.sql
create database SampleDB;

use SampleDB;

CREATE TABLE 'USER' (


'UserID' varchar(200) NOT NULL,
'Password' varchar(200) NOT NULL,
'Name' varchar(200) NOT NULL,
'IncorrectAttempts' int(2) NOT NULL,
'LockStatus' int(2) NOT NULL,
'UserType' varchar(200) NOT NULL,
PRIMARY KEY ('UserID')
);
Inserting Records (Java Program)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JdbcPrepared {

public static void main(String[] args) {

Shashank Singh (18SCSE1010417)


String dbURL = "jdbc:mysql://localhost:3306/sampledb";
String username = "root";
String password = "secret";

try {

Connection conn = DriverManager.getConnection(dbURL, username, password);

String sql = "INSERT INTO USER (UserID, Password, Name,


IncorrectAttempts, LockStatus, UserType) VALUES (?, ?, ?, ?,?,?)";

PreparedStatement statement1 = conn.prepareStatement(sql);


statement1.setString(1, "AB1001");
statement1.setString(2, "AB1001");
statement1.setString(3, "Hari");
statement1.setString(4, "0");
statement1.setString(5, "0");
statement1.setString(6, "Admin");

PreparedStatement statement2 = conn.prepareStatement(sql);


statement2.setString(1, "TA1002");
statement2.setString(2, "TA1002");
statement2.setString(3, "Prasath");
statement2.setString(4, "0");
statement2.setString(5, "0");
statement2.setString(6, "Employee");

PreparedStatement statement3 = conn.prepareStatement(sql);


statement3.setString(1, "RS1003");
statement3.setString(2, "RS1003");
statement3.setString(3, "Ganesh");
statement3.setString(4, "0");
statement3.setString(5, "0");
statement3.setString(6, "Employee");

} catch (SQLException ex) {


ex.printStackTrace();
}
}
}

Shashank Singh (18SCSE1010417)


Output:

Shashank Singh (18SCSE1010417)


EXPERIMENT- 6

Aim: For the same table created in Program 5, display all the records existing in the table USER
using java program.

Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JdbcPrepared {

public static void main(String[] args) {


String dbURL = "jdbc:mysql://localhost:3306/sampledb";
String username = "root";
String password = "secret";

try {

Connection conn = DriverManager.getConnection(dbURL, username, password);


String sql = "SELECT * FROM USER";
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql);
while (result.next()){
String userid = result.getString(“UserID”);
String pass = result.getString(“Password”);
String name = result.getString("Name");
String ia = result.getString("IncorrectAttempts ");
String ls = result.getString("LockStatus");
String ut = result.getString("UserType");

String output =”( %s, %s, %s, %d, %d, %s)";


System.out.println(String.format(userid, pass, name, ia, ls, ut));
}

} catch (SQLException ex) {


ex.printStackTrace();
}
}
}

Shashank Singh (18SCSE1010417)


Output:

Shashank Singh (18SCSE1010417)


Program: 7

Aim: Using the table of program 5, change the usertype for Ganesh to Admin

Code:

import java.sql.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

//STEP 4: Execute a query


System.out.println("Inserting records into the table...");
stmt = conn.createStatement();

String sql = "INSERT INTO Registration " +


"VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);

Shashank Singh (18SCSE1010417)


System.out.println("Inserted records into the table...");

}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");

Output:

C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Inserting records into the table...
Inserted records into the table...
Goodbye!

Shashank Singh (18SCSE1010417)


EXPERIMENT- 8

Aim: Delete the row form table USER (Program 5) where the Name is Hari using a java
program.

Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JdbcPrepared {

public static void main(String[] args) {


String dbURL = "jdbc:mysql://localhost:3306/sampledb";
String username = "root";
String password = "secret";

try {

Connection conn = DriverManager.getConnection(dbURL, username, password);


String sql = "DELETE FROM USER WHERE Name=?";

PreparedStatement statement = conn.prepareStatement(sql);


statement.setString(1, "Hari");

int rowsDeleted = statement.executeUpdate();


if (rowsDeleted > 0) {
System.out.println("The row Hari is deleted.");
}
String sql2 = "SELECT * FROM USER";
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql2);
while (result.next()){
String userid = result.getString(“UserID”);
String pass = result.getString(“Password”);
String name = result.getString("Name");
String ia = result.getString("IncorrectAttempts ");
String ls = result.getString("LockStatus");
String ut = result.getString("UserType");

Shashank Singh (18SCSE1010417)


String output =”( %s, %s, %s, %d, %d, %s)";
System.out.println(String.format(userid, pass, name, ia, ls, ut));
}

} catch (SQLException ex) {


ex.printStackTrace();
}
}
}

Output:

Shashank Singh (18SCSE1010417)


Program: 9

Title: Write the servlet application to print the current date and time.

Code:

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

public class DateSrv extends GenericServlet


{
//implement service()
public void service(ServletRequest req, ServletResponse res) throws IOException,
ServletException
{
//set response content type
res.setContentType("text/html");
//get stream obj
PrintWriter pw = res.getWriter();
//write req processing logic
java.util.Date date = new java.util.Date();
pw.println("<h2>"+"Current Date & Time: " +date.toString()+"</h2>");
//close stream object
pw.close();
}
}

Output:

Shashank Singh (18SCSE1010417)


EXPERIMENT- 10
Aim: Write a servlet application to establish communication between html and servlet page using
hyperlink.

Code:

index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wishing message</title>
</head>
<body>
<a href = "http://localhost:2020/WishSrvApp/test">Get wishing</a>
</body>
</html>

WishApp.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WishApp extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException,
ServletException
{
//set response content type
res.setContentType("text/html");
//get printWrite obj
PrintWriter pw = res.getWriter();
//write request processing logic to generate wish message
Calendar cal = Calendar.getInstance();
//get current hours of the day
int hour = cal.get(Calendar.HOUR_OF_DAY);//24 hrs format
//generate wish message
if(hour<12)
pw.println("Good Morning!!");
else if (hour < 16)
pw.println("Good afternoon");
else if(hour<20)
pw.println("Good evening");

Shashank Singh (18SCSE1010417)


else
pw.println("Good night");

pw.println("<br><br><a href= '../WishSrvApp/index.html'>Home</a>");


//close stream object
pw.close();
}
}

web.xml
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>WishApp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

Output:

(When we click on the above link In the morning it displays following message.)

Shashank Singh (18SCSE1010417)


EXPERIMENT- 11
Aim: Write an application to demonstrate the session tracking in Servlet.

Code:

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

// Extend HttpServlet class


public class SessionDemo extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("Surendra");

// Check if this is new comer on your web page.


if (session.isNew())
{
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
}
else
{
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);

// Set response content type

Shashank Singh (18SCSE1010417)


response.setContentType("text/html");
PrintWriter out = response.getWriter();

String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#e5f7c0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#eadf8c\">\n" +
"<th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}

web.xml
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>SessionDemo</servlet-class>
</servlet>
<servlet-mapping>

Shashank Singh (18SCSE1010417)


<servlet-name>abc</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

Output:

Shashank Singh (18SCSE1010417)


EXPERIMENT- 12

Aim: Write a simple JSP program to print the current date and time.

Code:

test.jsp
<%@ page import="java.io.*,java.util.*" %>
<html>
<head><title>JSPApp</title></head>
<body>
<form>
<fieldset style="width:20%; background-color: #ccffeb;">
<legend><b><i>JSP Application<i><b></legend>
<h3>Current Date and Time is :</h3>
<% java.util.Date d = new java.util.Date();
out.println(d.toString()); %>
</fieldset>
</form>
</body>
</html>

web.xml
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/test.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

Output:

Shashank Singh (18SCSE1010417)


EXPERIMENT- 13
Aim: Write a program in JSP to auto refresh a page.

Code:
auto-refresh.jsp
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh</title>
</head>
<body>
<center>
<form>
<fieldset style="width:20%; background-color:#e6ffe6;">
<legend>Auto refresh</legend>
<h2>Auto Refresh Example</h2>
<%
// Set refresh, autoload time as 1 seconds
response.setIntHeader("Refresh", 1);
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Crrent Time: " + CT + "\n");
%>
</fieldset>
</form>
</center>
</body>
</html>

web.xml
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/auto-refresh.jsp</jsp-file>
</servlet>

Shashank Singh (18SCSE1010417)


<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

Output:

Shashank Singh (18SCSE1010417)

You might also like