0% found this document useful (0 votes)
2 views

ADV JAVA LAB RECORD

The document provides a series of Java JDBC programs that demonstrate how to connect to an Oracle and MySQL database, create and manipulate tables, insert, update, delete records, and read data using ResultSet. It also includes instructions for installing and configuring Apache Tomcat and IDEs like NetBeans and Eclipse, along with a servlet example showcasing lifecycle methods. Each section includes code snippets, expected outputs, and step-by-step guides for installation and configuration.

Uploaded by

naikotivanaja02
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

ADV JAVA LAB RECORD

The document provides a series of Java JDBC programs that demonstrate how to connect to an Oracle and MySQL database, create and manipulate tables, insert, update, delete records, and read data using ResultSet. It also includes instructions for installing and configuring Apache Tomcat and IDEs like NetBeans and Eclipse, along with a servlet example showcasing lifecycle methods. Each section includes code snippets, expected outputs, and step-by-step guides for installation and configuration.

Uploaded by

naikotivanaja02
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

1.Jdbc Program to conncet the Oracle Database.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class OracleConnectionExample {

public static void main(String[] args) {

// JDBC URL, username, and password

String url = "jdbc:oracle:thin:@localhost:1521:ORCL"; // Replace localhost:1521:ORCL with


your Oracle database URL

String username = "your_username"; // Replace your_username with your Oracle database


username

String password = "your_password"; // Replace your_password with your Oracle database


password

// Establish connection

try (Connection connection = DriverManager.getConnection(url, username, password)) {

if (connection != null) {

System.out.println("Connected to the Oracle database!");

} else {

System.out.println("Failed to make connection!") }

} catch (SQLException e) {

System.err.println("Connection failed! Error message: " + e.getMessage());

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;

public class CreateTableMySQLExample {

public static void main(String[] args) {

// JDBC URL, username, and password

String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace


your_database_name with your MySQL database name

String username = "your_username"; // Replace your_username with your MySQL database


username

String password = "your_password"; // Replace your_password with your MySQL database


password

// SQL statement to create a new table

String createTableSQL = "CREATE TABLE employees ("

+ "id INT PRIMARY KEY AUTO_INCREMENT,"

+ "name VARCHAR(50),"

+ "age INT,"

+ "salary FLOAT)";

// Establish connection and create the table

try (Connection connection = DriverManager.getConnection(url, username, password);

Statement statement = connection.createStatement()) {

// Execute the SQL statement to create the table

statement.execute(createTableSQL);

System.out.println("Table created successfully!");


} catch (SQLException e) {

System.err.println("Table creation failed! Error message: " + e.getMessage());

Output:-
Table created successfully!

3.Jdbc program to insert the records into database.


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class InsertRecordsMySQLExample {

public static void main(String[] args) {

// JDBC URL, username, and password

String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace


your_database_name with your MySQL database name

String username = "your_username"; // Replace your_username with your MySQL database


username

String password = "your_password"; // Replace your_password with your MySQL database


password

// SQL statement to insert records

String insertSQL = "INSERT INTO employees (name, age, salary) VALUES (?, ?, ?)";

// Sample data for insertion

String[] names = {"John", "Alice", "Bob"};

int[] ages = {30, 25, 35};


float[] salaries = {50000.0f, 60000.0f, 70000.0f};

try (Connection connection = DriverManager.getConnection(url, username, password);

PreparedStatement preparedStatement = connection.prepareStatement(insertSQL)) {

for (int i = 0; i < names.length; i++) {

// Set parameters for the prepared statement

preparedStatement.setString(1, names[i]);

preparedStatement.setInt(2, ages[i]);

preparedStatement.setFloat(3, salaries[i]);

// Execute the insertion

preparedStatement.executeUpdate();

System.out.println("Records inserted successfully!");

} catch (SQLException e) {

System.err.println("Insertion failed! Error message: " + e.getMessage());

Output:- Records inserted successfully!

4.Jdbc program to read the data from Database using ResultSet


import java.sql.*;

public class ReadDataMySQLExample {

public static void main(String[] args) {

// JDBC URL, username, and password

String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace


your_database_name with your MySQL database name

String username = "your_username"; // Replace your_username with your MySQL database


username

String password = "your_password"; // Replace your_password with your MySQL database


password

// SQL query to select data

String selectSQL = "SELECT * FROM employees";

try (Connection connection = DriverManager.getConnection(url, username, password);

Statement statement = connection.createStatement();

ResultSet resultSet = statement.executeQuery(selectSQL)) {

// Iterate through the result set and print data

while (resultSet.next()) {

int id = resultSet.getInt("id");

String name = resultSet.getString("name");

int age = resultSet.getInt("age");

float salary = resultSet.getFloat("salary");

System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age + ", Salary: " + salary);

} catch (SQLException e) {

System.err.println("Reading data failed! Error message: " + e.getMessage());

Output:-

ID: 1, Name: John, Age: 30, Salary: 50000.0

ID: 2, Name: Alice, Age: 25, Salary: 60000.0

ID: 3, Name: Bob, Age: 35, Salary: 70000.0


5.Jdbc program to update the records into database.
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class UpdateRecordsMySQLExample {

public static void main(String[] args) {

// JDBC URL, username, and password

String url = "jdbc:mysql://localhost:3306/your_database_name"; // Replace


your_database_name with your MySQL database name

String username = "your_username"; // Replace your_username with your MySQL database


username

String password = "your_password"; // Replace your_password with your MySQL database


password

// SQL statement to update records

String updateSQL = "UPDATE employees SET salary = ? WHERE name = ?";

// Sample data for update

String nameToUpdate = "Alice";

float newSalary = 65000.0f;

try (Connection connection = DriverManager.getConnection(url, username, password);

PreparedStatement preparedStatement = connection.prepareStatement(updateSQL)) {

// Set parameters for the prepared statement

preparedStatement.setFloat(1, newSalary);

preparedStatement.setString(2, nameToUpdate);

// Execute the update

int rowsAffected = preparedStatement.executeUpdate();


if (rowsAffected > 0) {

System.out.println("Records updated successfully!");

} else {

System.out.println("No records were updated!");

} catch (SQLException e) {

System.err.println("Update failed! Error message: " + e.getMessage());

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

print:No records were updated!

If the update operation fails due to an error, it will print an error message indicating the reason
for the failure.

6. Jdbc program to delete the records into database.


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class DeleteRecords {

static final String JDBC_URL = "jdbc:mysql://localhost:3306/your_database_name";

static final String USER = "your_username";

static final String PASSWORD = "your_password";


public static void main(String[] args) {

try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD))


{

Statement statement = connection.createStatement();

// Delete records

String sql = "DELETE FROM your_table_name WHERE condition;";

int rowsAffected = statement.executeUpdate(sql);

System.out.println("Rows affected: " + rowsAffected);

} catch (SQLException e) {

e.printStackTrace();

Output:- Rows affected: 5


7.Jdbc program to demonstrate PreparedStatement.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class PreparedStatementInsertDemo {

static final String JDBC_URL = "jdbc:mysql://localhost:3306/your_database_name";

static final String USER = "your_username";

static final String PASSWORD = "your_password";

public static void main(String[] args) {

try (Connection connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD))


{

// Prepare a statement with a parameterized query for insertion

String query = "INSERT INTO your_table_name (name, age) VALUES (?, ?)";

PreparedStatement statement = connection.prepareStatement(query);

// Set values for parameters

statement.setString(1, "John");

statement.setInt(2, 30);

// Execute the statement

int rowsAffected = statement.executeUpdate();

System.out.println("Rows affected: " + rowsAffected);

} catch (SQLException e) {

e.printStackTrace();

Output:-

Rows affected: 1

8.Instalation and configuring Apache Tomcat Server.

Installing Apache Tomcat on Windows

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.

On clicking Environment Variables the following box will open.

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”.

Step 9: Check if the Startup Windows Batch File is running properly.

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.

A)Downloading and Installing NetBeans IDE.

Step 0: Install JDK

To use NetBeans for Java programming, you need to first install Java Development Kit (JDK).
See "JDK - How to Install ".

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.

How to Install NetBeans on Mac OS X

To use NetBeans for Java programming, you need to first install JDK. Read "How to install JDK
on Mac ".

To install NetBeans:

Download NetBeans from http://netbeans.org/downloads/ . Set "Platform" to "Mac OS X". There


are many "bundles" available. For beginners, choose "Java SE" (e.g., "netbeans-8.2-javase-
macosx.dmg " 116MB).

Double-click the download Disk Image (DMG) file.

Double-click the "NetBeans 8.x.mpkg", and follow the instructions to install NetBeans. NetBeans
will be installed under "/Applications/NetBeans ".

Eject the Disk Image (".dmg").


You can launch NetBeans from the "Applications".

B) Downloading and Installing Myeclips IDE.

1. Download the Eclipse Installer

Download Eclipse Installer from http://www.eclipse.org/downloads

2. Start the Eclipse Installer executable

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.

3. Select the package to install

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.

Select and click on the package you want to install.


4. Select your installation folder

Specify the folder where you want Eclipse to be installed. The default folder will be in your User
directory.

Select the ‘Install’ button to begin the installation.

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.

First, create a Java class named LifecycleDemo:

import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.*;

@WebServlet("/LifecycleDemo")

public class LifecycleDemo extends GenericServlet {

public void init(ServletConfig config) throws ServletException {

super.init(config);

System.out.println("Servlet initialized");

public void service(ServletRequest req, ServletResponse res) throws ServletException,


IOException {

System.out.println("Servlet service method called");

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

out.println("<html><head><title>Life Cycle Demo</title></head><body>");

out.println("<h1>Servlet Life Cycle Demo</h1>");

out.println("<p>Check your console for life cycle method logs.</p>");

out.println("</body></html>");

public void destroy() {

System.out.println("Servlet destroyed");

1.Compile the Java file.

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:

<?xml version="1.0" encoding="UTF-8"?>

<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">

<display-name>Servlet Lifecycle Demo</display-name>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

</welcome-file-list>

</web-app>

1.Start your Apache Tomcat server.


2.Access the servlet using the URL http://localhost:8080/{context-path}/LifecycleDemo, where
{context-path} is the context path of your web application.

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:-

The output of this servlet will be displayed in two places:

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>

<title>Life Cycle Demo</title>

</head>

<body>

<h1>Servlet Life Cycle Demo</h1>

<p>Check your console for life cycle method logs.</p>

</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 service method called

Servlet destroyed

11. Servlet Program to demonstrate RequestDispacher.


import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/ForwardDemo")

public class ForwardDemo extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Setting content type

response.setContentType("text/html");

// Creating PrintWriter object

PrintWriter out = response.getWriter()

// Writing HTML content

out.println("<html><head><title>Forward Demo</title></head><body>");

out.println("<h1>Forward Demo</h1>");

out.println("<p>This is the first servlet.</p>");

out.println("<p>Forwarding request to another servlet...</p>");

out.println("</body></html>");

// Creating RequestDispatcher object

RequestDispatcher dispatcher = request.getRequestDispatcher("/AnotherServlet");

// Forwarding the request

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>

<p>This is the first servlet.</p>

<p>Forwarding request to another servlet...</p>

</body>

</html>

12. Servlet Program to demonstrate Session Tracking.


import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.*;

@WebServlet("/SessionTrackingDemo")

public class SessionTrackingDemo extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Get the current session, or create a new one if it doesn't exist

HttpSession session = request.getSession(true)

// Set session attributes

Integer visitCount = (Integer) session.getAttribute("visitCount");

if (visitCount == null) {

visitCount = 1;

} else {

visitCount++;
}

session.setAttribute("visitCount", visitCount);

// Set response content type

response.setContentType("text/html");

// Writing HTML content

PrintWriter out = response.getWriter();

out.println("<html><head><title>Session Tracking Demo</title></head><body>");

out.println("<h1>Session Tracking Demo</h1>");

out.println("<p>You have visited this page " + visitCount + " times.</p>");

out.println("</body></html>");

This servlet demonstrates session tracking by maintaining a session attribute named


"visitCount". It increments the visit count every time the servlet is accessed within the same
session.

Output :-
The output will be:

```html

<html>

<head>

<title>Session Tracking Demo</title>

</head>

<body>

<h1>Session Tracking Demo</h1>

<p>You have visited this page [visitCount] times.</p>

</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:

```

You have visited this page 1 times.

```

If you refresh the page or visit the URL again within the same session, it will increment the visit
count and display:

```

You have visited this page 2 times.

```

This demonstrates session tracking where the servlet maintains state information across
multiple requests from the same client.

13. Servlet Program to demonstrate Cookies.


import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.*;

@WebServlet("/CookieDemo")

public class CookieDemo extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Creating or retrieving a cookie

Cookie cookie = new Cookie("username", "John");

// Setting cookie expiration time (optional)


cookie.setMaxAge(24 * 60 * 60); // Cookie expires in 1 day

// Adding cookie to the response

response.addCookie(cookie);

// Set response content type

response.setContentType("text/html");

// Writing HTML content

PrintWriter out = response.getWriter();

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>");

Here's a simple Servlet program demonstrating the use of cookies:

```java

import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.*;

@WebServlet("/CookieDemo")

public class CookieDemo extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Creating or retrieving a cookie

Cookie cookie = new Cookie("username", "John");

// Setting cookie expiration time (optional)


cookie.setMaxAge(24 * 60 * 60); // Cookie expires in 1 day

// Adding cookie to the response

response.addCookie(cookie);

// Set response content type

response.setContentType("text/html");

// Writing HTML content

PrintWriter out = response.getWriter();

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:-

The output will be:

```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")

public class LoggingFilter implements Filter {

public void init(FilterConfig config) throws ServletException {

// Initialization code

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws


ServletException, IOException {

// Log information about the incoming request

System.out.println("LoggingFilter: Request received from " + req.getRemoteAddr() + " for " +


((HttpServletRequest) req).getRequestURI());

// Pass the request along the filter chain

chain.doFilter(req, resp);

public void destroy() {

// Cleanup code

b) create a servlet that will be filtered:

import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.*;

@WebServlet("/FilterDemo")

public class FilterDemo extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Set response content type

response.setContentType("text/html");

// Writing HTML content

PrintWriter out = response.getWriter();

out.println("<html><head><title>Filter Demo</title></head><body>");

out.println("<h1>Filter Demo</h1>");

out.println("<p>This servlet is being filtered by the LoggingFilter.</p>");

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:

LoggingFilter: Request received from 127.0.0.1 for /FilterDemo

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.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>

<title>JSP Tag Elements Example</title>

</head>

<body>

<h2>Demonstrating JSP Tag Elements</h2>

<p><strong>1. JSP Directive</strong>: It is used to define the properties


of the JSP page such as language, content type, etc.</p>

<!-- JSP Directive -->

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


%>

<p><strong>2. JSP Declaration</strong>: It is used to declare variables


or methods that can be used later in the JSP page.</p>

<!-- JSP Declaration -->

<%!

String currentDate() {

return new java.util.Date().toString();

%>
<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>

<!-- JSP Scriptlet -->

<%

String userName = "John Doe";

%>

<p><strong>4. JSP Expression</strong>: It is used to print the value of a


Java expression directly to the output stream.</p>

<!-- JSP Expression -->

<h3>Welcome, <%= userName %>!</h3>

<h3>Current Date: <%= currentDate() %></h3>

<p><strong>5. JSP Action Element</strong>: It is used to invoke a built-


in tag or JavaBean components, such as
<code>&lt;jsp:useBean&gt;</code>, <code>&lt;jsp:setProperty&gt;</code>,
<code>&lt;jsp:getProperty&gt;</code>, and others.</p>

<!-- JSP Action Element: Example of using jsp:useBean -->

<jsp:useBean id="bean" class="java.util.Date" scope="page" />

<jsp:getProperty name="bean" property="toString" />

</body>

</html>

output:-

A greeting for John Doe.


The current date (the actual date when the page is accessed).

A java.util.Date object accessed using a JavaBean.

16. JSP program to demonstrate implecit objects.


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Implicit Objects Demo</title>

</head>

<body>

<h1>Implicit Objects Demo</h1>

<%-- out implicit object --%>

<% out.println("This is printed using out implicit object."); %>

<%-- request implicit object --%>

<p>Client IP Address: <%= request.getRemoteAddr() %></p>

<p>Requested URL: <%= request.getRequestURL() %></p>

<%-- response implicit object --%>

<% response.setContentType("text/plain"); %>

<%-- session implicit object --%>

<% session.setAttribute("username", "John"); %>

<%-- application implicit object --%>

<% application.setAttribute("appTitle", "My Application"); %>

<%-- page implicit object --%>


<p>Page URL: <%= pageContext.getAttribute("javax.servlet.forward.request_uri") %></p>

</body>

</html>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Implicit Objects Demo</title>

</head>

<body>

<h1>Implicit Objects Demo</h1>

This is printed using out implicit object.

<p>Client IP Address: [Client's IP Address]</p>

<p>Requested URL: [Requested URL]</p>

<p>Page URL: [/path/to/your/jsp/file.jsp]</p>

</body>

</html>

17. JSP program to demonstrate useBean tag.


<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>

<html>

<head>

<title>useBean Tag Example</title>

</head>
<body>

<jsp:useBean id="person" class="com.example.Person" scope="session" />

<jsp:setProperty name="person" property="name" value="John" />

<jsp:setProperty name="person" property="age" value="25" />

<h1>Person Details:</h1>

<p>Name: ${person.name}</p>

<p>Age: ${person.age}</p>

</body>

</html>

Output:-
Person Details:

Name: John

Age: 25

18. JSP program to demonstrate JSTL.


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<title>JSTL Example</title>

</head>

<body>

<c:set var="name" value="John" />

<c:set var="age" value="25" />

<h1>Person Details:</h1>

<p>Name: <c:out value="${name}" /></p>


<p>Age: <c:out value="${age}" /></p>

<c:if test="${age ge 18}">

<p>This person is an adult.</p>

</c:if>

<c:if test="${age lt 18}">

<p>This person is a minor.</p>

</c:if>

</body>

</html>

Output:-
The output of the JSP program would be:

Person Details:

Name: John

Age: 25

This person is an adult.

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.

19. JSP program to Process the Form.


<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Form Processing</title>
</head>

<body>

<h2>Form Processing</h2>

<form action="process.jsp" method="post">

<label for="name">Name:</label>

<input type="text" id="name" name="name"><br><br>

<label for="email">Email:</label>

<input type="email" id="email" name="email"><br><br>

<input type="submit" value="Submit">

</form>

</body>

</html>

And the process.jsp to handle the form submission:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Form Submission Result</title>

</head>

<body>

<h2>Form Submission Result</h2>

<%

String name = request.getParameter("name");


String email = request.getParameter("email");

%>

<p>Name: <%= name %></p>

<p>Email: <%= email %></p>

</body>

</html>

Output:-
Form Processing

Name: [Input field]

Email: [Input field]

[Submit button]

Form Submission Result

Name: [Value entered in the Name input field]

Email: [Value entered in the Email input field].

20.Develop simple application to process the registration form using jsp


and jdbc with the help of IDE. (Real time application development using
MVC architecture)

Tools and technologies used


JSP - 2.2 +

IDE - STS/Eclipse Neon.3

JDK - 1.8 or later

Apache Tomcat - 8.5

JSTL - 1.2.1

Servlet API - 2.5

MySQL - mysql-connector-java-8.0.13.jar
Development Steps

Create an Eclipse Dynamic Web Project

Add Dependencies

Project Structure

MySQL Database Setup

Create a JavaBean - Employee.java

Create a EmployeeDao.java

Create a EmployeeServlet.java

Create a employeeregister.jsp

Create a employeedetail.jsp

Demo

1. Create an Eclipse Dynamic Web Project

To create a new dynamic Web project in Eclipse:

1. On the main menu select File > New > Project....

2. In the upcoming wizard choose Web > Dynamic Web Project.

3. Click Next.

4. Enter project name as "jsp-servlet-jdbc-mysql-example";

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

Standard project structure for your reference -

4. MySQL Database Setup

Let's create a database named "employees" in MySQL. Now, let's create an employee table
using below DDL script:

CREATE TABLE `employee` (

`id` int(3) NOT NULL AUTO_INCREMENT,

`first_name` varchar(20) DEFAULT NULL,

`last_name` varchar(20) DEFAULT NULL,

`username` varchar(250) DEFAULT NULL,

`password` varchar(20) DEFAULT NULL,


`address` varchar(45) DEFAULT NULL,

`contact` varchar(45) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

5. Create a JavaBean - Employee.java

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;

/**

* JavaBean class used in jsp action tags.

* @author Ramesh Fadatare

*/

public class Employee implements Serializable {

/**

*/

private static final long serialVersionUID = 1 L;

private String firstName;

private String lastName;

private String username;

private String password;

private String address;

private String contact;

public String getFirstName() {


return firstName;

public void setFirstName(String firstName) {

this.firstName = firstName;

public String getLastName() {

return lastName;

public void setLastName(String lastName) {

this.lastName = lastName;

public String getUsername() {

return username;

public void setUsername(String username) {

this.username = username;

public String getPassword() {

return password;

public void setPassword(String password) {

this.password = password;

public String getAddress() {

return address;
}

public void setAddress(String address) {

this.address = address;

public String getContact() {

return contact;

public void setContact(String 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;

public class EmployeeDao {

public int registerEmployee(Employee employee) throws ClassNotFoundException {

String INSERT_USERS_SQL = "INSERT INTO employee" +

" (id, first_name, last_name, username, password, address, contact) VALUES " +

" (?, ?, ?, ?, ?,?,?);";


int result = 0;

Class.forName("com.mysql.jdbc.Driver");

try (Connection connection = DriverManager

.getConnection("jdbc:mysql://localhost:3306/employees?useSSL=false", "root", "root");

// Step 2:Create a statement using connection object

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);

// Step 3: Execute the query or update query

result = preparedStatement.executeUpdate();

} catch (SQLException e) {

// process sql exception

printSQLException(e);

return result;

private void printSQLException(SQLException ex) {

for (Throwable e: ex) {

if (e instanceof SQLException) {
e.printStackTrace(System.err);

System.err.println("SQLState: " + ((SQLException) e).getSQLState());

System.err.println("Error Code: " + ((SQLException) e).getErrorCode());

System.err.println("Message: " + e.getMessage());

Throwable t = ex.getCause();

while (t != null) {

System.out.println("Cause: " + t);

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

Registration Form using JSP + Servlet + JDBC + Mysql Example

author: Ramesh Fadatare

JDBC TUTORIAL JSP MYSQL SERVLET TUTORIAL

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

This tutorial explained in the below youtube video:

Below diagram shows the Employee Registration JSP page:

8. Create a employeeregister.jsp

Let's design employee registration HTML form with the following fields:

firstName

lastName

username

password

address

contact

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<div align="center">

<h1>Employee Register Form</h1>

<form action="<%= request.getContextPath() %>/register" method="post">

<table style="with: 80%">

<tr>
<td>First Name</td>

<td><input type="text" name="firstName" /></td>

</tr>

<tr>

<td>Last Name</td>

<td><input type="text" name="lastName" /></td>

</tr>

<tr>

<td>UserName</td>

<td><input type="text" name="username" /></td>

</tr>

<tr>

<td>Password</td>

<td><input type="password" name="password" /></td>

</tr>

<tr>

<td>Address</td>

<td><input type="text" name="address" /></td>

</tr>

<tr>

<td>Contact No</td>

<td><input type="text" name="contact" /></td>

</tr>

</table>

<input type="submit" value="Submit" />


</form>

</div>

</body>

</html>

9. Create an employeedetails.jsp

After an employee successfully registered then this page show a successful message on
screen:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@page import="net.javaguides.employeemanagement.dao.*"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<h1>User successfully registered!</h1>

</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

You might also like