ADV JAVA LAB RECORD
ADV JAVA LAB RECORD
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Establish connection
if (connection != null) {
} else {
} catch (SQLException e) {
Output:-
Connected to the Oracle database!
2.Create a new Database table using JDBC.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
+ "name VARCHAR(50),"
+ "age INT,"
+ "salary FLOAT)";
statement.execute(createTableSQL);
Output:-
Table created successfully!
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
String insertSQL = "INSERT INTO employees (name, age, salary) VALUES (?, ?, ?)";
preparedStatement.setString(1, names[i]);
preparedStatement.setInt(2, ages[i]);
preparedStatement.setFloat(3, salaries[i]);
preparedStatement.executeUpdate();
} catch (SQLException e) {
while (resultSet.next()) {
int id = resultSet.getInt("id");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age + ", Salary: " + salary);
} catch (SQLException e) {
Output:-
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
preparedStatement.setFloat(1, newSalary);
preparedStatement.setString(2, nameToUpdate);
} else {
} catch (SQLException e) {
Output:- The output of this program will depend on whether the update operation was
successful or not. If the update operation is successful and at least one record is updated, it will
print:Records updated successfully!
If no records match the specified condition for the update (e.g., no employee named "Alice"
exists), it will
If the update operation fails due to an error, it will print an error message indicating the reason
for the failure.
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
// Delete records
} catch (SQLException e) {
e.printStackTrace();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
String query = "INSERT INTO your_table_name (name, age) VALUES (?, ?)";
statement.setString(1, "John");
statement.setInt(2, 30);
} catch (SQLException e) {
e.printStackTrace();
Output:-
Rows affected: 1
Step 1: We need to first install the Tomcat 10 zip file from this website. On the website, select
the 64-bit Windows zip (PGP, sha512) in the Core section to start the download process for the
Tomcat zip file.
Step 2: Check If JDK Is Installed. Open Command Prompt and enter the following commands.
java -version
javac -version
If JDK is not installed on your computer, install JDK. In the above picture, we can see JDK is
already installed on our computer.
Step 3: Unzip Tomcat 10 Zip File. Go to the location where you have downloaded the Tomcat 10
zip file. Right-click on the apache tomcat file place the cursor on 7-Zip and click on Extract Here
to extract the folder.
Step 4: Creating JAVA_HOME Variable. Click Start then in the search bar, search for “Edit the
system environment variables” and click on it. The following System Properties box will open.
Select Environment Variables in the box.
Step 5: We have to create a JAVA_HOME variable and insert the path of the JDK file stored in
our computer, which will be shown below. So select New from the System variables in the above
picture. A New System Variable box will be opened where we will have to fill in the Variable
name and Variable value.
Step 6: Go to the location where you have stored the contents of the JDK file in My Computer or
PC. Copy the root path of the location of the JDK file as shown below.
Step 7: Paste the JDK path from the above picture into the Variable value field and in the
Variable name field, give the name JAVA_HOME as shown below.
Step 8: Check the Working of Tomcat. Open the extracted apache tomcat file. We will see all the
following files in them. Among them open the batch file named “startup”.
Here are the steps to install and configure Apache Tomcat Server:
Step 10: Successful Installation of Tomcat. Our next step is to open an internet browser like
Google and type in the address same
http://localhost:8080
Then click enter and the following browser will appear suggesting the successful installation of
Apache Tomcat.
9.Instalation and configuring Netbeans, MyEcplice IDEs.
To use NetBeans for Java programming, you need to first install Java Development Kit (JDK).
See "JDK - How to Install ".
Step 1: Download
To use NetBeans for Java programming, you need to first install JDK. Read "How to install JDK
on Mac ".
To install NetBeans:
Double-click the "NetBeans 8.x.mpkg", and follow the instructions to install NetBeans. NetBeans
will be installed under "/Applications/NetBeans ".
For Windows users, after the Eclipse Installer executable has finished downloading it should be
available in your download directory. Start the Eclipse Installer executable. You may get a
security warning to run this file. If the Eclipse Foundation is the Publisher, you are good to select
Run.
The new Eclipse Installer shows the packages available to Eclipse users. You can search for the
package you want to install or scroll through the list.
Specify the folder where you want Eclipse to be installed. The default folder will be in your User
directory.
5. Launch Eclipse
Once the installation is complete you can now launch Eclipse. The Eclipse Installer has done it's
work. Happy coding.
10. Servlet Program to demonstrate Life cycle methods using GenericServlet.
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/LifecycleDemo")
super.init(config);
System.out.println("Servlet initialized");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("</body></html>");
System.out.println("Servlet destroyed");
2.Place the compiled class file inside the WEB-INF/classes directory of your web application.
3.Create a deployment descriptor file named web.xml inside the WEB-INF directory with the
following content:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
3.You will see the HTML content generated by the servlet displayed in the browser window. At
the same time, you will see logs indicating the initialization, service method invocation, and
destruction of the servlet in the console where Tomcat is running.
Output:-
In the web browser: When you access the servlet using the URL http://localhost:8080/{context-
path}/LifecycleDemo, you will see the HTML content generated by the servlet displayed in the
browser window. The HTML content will be:
<html>
<head>
</head>
<body>
</body>
</html>
2.In the console where Apache Tomcat is running: You will see logs indicating the initialization,
service method invocation, and destruction of the servlet. For example
Servlet initialized
Servlet destroyed
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/ForwardDemo")
response.setContentType("text/html");
out.println("<html><head><title>Forward Demo</title></head><body>");
out.println("<h1>Forward Demo</h1>");
out.println("</body></html>");
dispatcher.forward(request, response);
Output:-
The output of this servlet program will depend on the implementation of the servlet named
AnotherServlet. When a request is made to the URL mapped to the ForwardDemo servlet, it will
execute the code inside the doGet() method.The output generated by the ForwardDemo servlet
will be:
<html>
<head>
<title>Forward Demo</title>
</head>
<body>
<h1>Forward Demo</h1>
</body>
</html>
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/SessionTrackingDemo")
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
}
session.setAttribute("visitCount", visitCount);
response.setContentType("text/html");
out.println("</body></html>");
Output :-
The output will be:
```html
<html>
<head>
</head>
<body>
</body>
</html>
```
In this output, `[visitCount]` will be replaced by the actual count of visits, which starts from 1 and
increments with each subsequent visit within the same session.
For example, if you visit the servlet URL for the first time, it will display:
```
```
If you refresh the page or visit the URL again within the same session, it will increment the visit
count and display:
```
```
This demonstrates session tracking where the servlet maintains state information across
multiple requests from the same client.
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/CookieDemo")
response.addCookie(cookie);
response.setContentType("text/html");
out.println("<html><head><title>Cookie Demo</title></head><body>");
out.println("<h1>Cookie Demo</h1>");
out.println("<p>A cookie named 'username' with value 'John' has been created.</p>");
out.println("</body></html>");
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/CookieDemo")
response.addCookie(cookie);
response.setContentType("text/html");
out.println("<html><head><title>Cookie Demo</title></head><body>");
out.println("<h1>Cookie Demo</h1>");
out.println("<p>A cookie named 'username' with value 'John' has been created.</p>");
out.println("</body></html>");
}. }
This servlet creates a cookie named "username" with the value "John" and adds it to the HTTP
response. The cookie is set to expire in 1 day.
Output:-
```html
<html>
<head>
<title>Cookie Demo</title>
</head>
<body>
<h1>Cookie Demo</h1>
<p>A cookie named 'username' with value 'John' has been created.</p>
</body>
</html>
14. Servlet Program to demonstrate Filters.
a)create a filter that logs information about incoming requests:
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
@WebFilter("/FilterDemo")
// Initialization code
chain.doFilter(req, resp);
// Cleanup code
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/FilterDemo")
response.setContentType("text/html");
out.println("<html><head><title>Filter Demo</title></head><body>");
out.println("<h1>Filter Demo</h1>");
out.println("</body></html>");
Output:-
In the console, you will see log messages generated by the LoggingFilter, indicating information
about each incoming request.
For example:
This log message indicates that a request was received from the client with IP address
127.0.0.1 for the servlet mapped to /FilterDemo.
15. JSP program to demonstrate JSP tag elements.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<%!
String currentDate() {
%>
<p><strong>3. JSP Scriptlet</strong>: It is used to insert Java code
directly into the JSP page. The code will be executed when the page is
requested.</p>
<%
%>
</body>
</html>
output:-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Person Details:</h1>
<p>Name: ${person.name}</p>
<p>Age: ${person.age}</p>
</body>
</html>
Output:-
Person Details:
Name: John
Age: 25
<!DOCTYPE html>
<html>
<head>
<title>JSTL Example</title>
</head>
<body>
<h1>Person Details:</h1>
</c:if>
</c:if>
</body>
</html>
Output:-
The output of the JSP program would be:
Person Details:
Name: John
Age: 25
This is because the name and age variables are set using <c:set>, and their values are displayed
using <c:out>. Additionally, since the age is 25, the <c:if> statement evaluates to true for age 18,
so the message "This person is an adult." is displayed.
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form Processing</title>
</head>
<body>
<h2>Form Processing</h2>
<label for="name">Name:</label>
<label for="email">Email:</label>
</form>
</body>
</html>
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<%
%>
</body>
</html>
Output:-
Form Processing
[Submit button]
JSTL - 1.2.1
MySQL - mysql-connector-java-8.0.13.jar
Development Steps
Add Dependencies
Project Structure
Create a EmployeeDao.java
Create a EmployeeServlet.java
Create a employeeregister.jsp
Create a employeedetail.jsp
Demo
3. Click Next.
5. Make sure that the target runtime is set to Apache Tomcat with the currently supported
version.
2. Add Dependencies
Add the latest release of below jar files to the lib folder.
jsp-api.2.3.1.jar
servlet-api.2.3.jar
mysql-connector-java-8.0.13.jar
jstl-1.2.jar
3. Project Structure
Let's create a database named "employees" in MySQL. Now, let's create an employee table
using below DDL script:
Let's create an Employee JavaBean class which we will use in JSP action tags.
package net.javaguides.jsp.jdbc.bean;
import java.io.Serializable;
/**
*/
/**
*/
this.firstName = firstName;
return lastName;
this.lastName = lastName;
return username;
this.username = username;
return password;
this.password = password;
return address;
}
this.address = address;
return contact;
this.contact = contact;
6. Create an EmployeeDao.java
Let's create EmployeeDao class which contains JDBC code to connect with MySQL database.
Add the following code to an EmployeeDao class:
package net.javaguides.jsp.jdbc.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import net.javaguides.jsp.jdbc.bean.Employee;
" (id, first_name, last_name, username, password, address, contact) VALUES " +
Class.forName("com.mysql.jdbc.Driver");
PreparedStatement preparedStatement =
connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, employee.getFirstName());
preparedStatement.setString(3, employee.getLastName());
preparedStatement.setString(4, employee.getUsername());
preparedStatement.setString(5, employee.getPassword());
preparedStatement.setString(6, employee.getAddress());
preparedStatement.setString(7, employee.getContact());
System.out.println(preparedStatement);
result = preparedStatement.executeUpdate();
} catch (SQLException e) {
printSQLException(e);
return result;
if (e instanceof SQLException) {
e.printStackTrace(System.err);
Throwable t = ex.getCause();
while (t != null) {
t = t.getCause();
7. Create an EmployeeServlet.java
Let's create an EmployeeServlet class to process HTTP request parameters and redirect to the
appropriate JSP page after request data stored in the database:
Java Guides
Java JavaEE Library REST Spring Boot Microservices Full Stack YouTubeUI Quiz Hibernate DB
Programs Kotlin Python Me
Check out my 10+ Udemy bestseller courses and discount coupons: Udemy Courses - Ramesh
Fadatare
In this article, we will build a simple Employee Registration module using JSP, Servlet, JDBC,
and MySQL database.
Check out Login Form using JSP + Servlet + JDBC + MySQL Example.
Video Tutorial
8. Create a employeeregister.jsp
Let's design employee registration HTML form with the following fields:
firstName
lastName
username
password
address
contact
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<div align="center">
<tr>
<td>First Name</td>
</tr>
<tr>
<td>Last Name</td>
</tr>
<tr>
<td>UserName</td>
</tr>
<tr>
<td>Password</td>
</tr>
<tr>
<td>Address</td>
</tr>
<tr>
<td>Contact No</td>
</tr>
</table>
</div>
</body>
</html>
9. Create an employeedetails.jsp
After an employee successfully registered then this page show a successful message on
screen:
pageEncoding="ISO-8859-1"%>
<%@page import="net.javaguides.employeemanagement.dao.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
</body>
</html>
Output:-
Once you deploy this application successfully then hit this link into a browser -
http://localhost:8080/jsp-servlet-jdbc-mysql-example/employeeregister.jsp
Registration Success Page