0% found this document useful (0 votes)
4 views14 pages

Java Servlet Examples for Web Development

The document contains multiple Java Servlet examples demonstrating various functionalities such as printing the current date and time, handling form data, auto-refreshing a page, session tracking, and performing CRUD operations on a database. Each example includes the necessary Java code and HTML forms, showcasing how to interact with a MySQL database and manage cookies. Overall, it serves as a practical guide for implementing servlet applications in Java.

Uploaded by

yasaswinisrit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views14 pages

Java Servlet Examples for Web Development

The document contains multiple Java Servlet examples demonstrating various functionalities such as printing the current date and time, handling form data, auto-refreshing a page, session tracking, and performing CRUD operations on a database. Each example includes the necessary Java code and HTML forms, showcasing how to interact with a MySQL database and manage cookies. Overall, it serves as a practical guide for implementing servlet applications in Java.

Uploaded by

yasaswinisrit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Exercise - 2

//Write Servlet application to print current date & time

package ex2;

import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/printdatetime")
public class Printdate extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException {
[Link]("text/html");
PrintWriter out=[Link]();
Date dt=new Date();
[Link](dt);
}
}
Output:
// Write Servlet program to link Html & Servlet Communication.

//[Link]
package ex2;

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/printdetails")
public class Printformdata extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
IOException {
[Link]("text/html");
PrintWriter out=[Link]();
String s1=[Link]("t1");
[Link]("Welcome"+s1);
}

[Link]
<html>
<head>

<title>Insert title here</title>


</head>
<body>
<form method="post" action="printdetails">
Enter your name <input type="text"name="t1">
<button type="submit">submit</button>

</form>
</body>
</html>

Output:
// Write Servlet program to Auto refresh a page.

package ex2;

import [Link];
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/refreshpage")
public class Refreshpage extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException{
[Link]("text/html");
[Link]("refresh",5);
PrintWriter out=[Link]();
Date dt=new Date();
[Link](dt);

}
}
Output:
// Demonstrate session tracking using small program.

package ex2;

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/session")
public class SessionHandler extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException


{
[Link]("text/html");
PrintWriter out = [Link]();

// Try to get existing session without creating a new one


HttpSession session = [Link](false);

if (session == null) {
// No session exists → create a new one
session = [Link]();
[Link]("uname", "kumar");
[Link](10); // 60 seconds timeout

[Link]("<h2 style='color:green;'>New Session Created</h2>");


[Link]("<h1>Session ID: " + [Link]() + "</h1>");
[Link]("<h1>Stored 'uname' in session: " + [Link]("uname") +
"</h1>");
[Link]("<h1>Session Timeout: " + [Link]() + "
seconds</h1>");
} else {
// Session exists → show details
[Link]("<h2 style='color:blue;'>Session is Active</h2>");
[Link]("<h1>Session ID: " + [Link]() + "</h1>");
[Link]("<h1>Stored 'uname' in session: " + [Link]("uname") +
"</h1>");
[Link]("<h1>Session Timeout: " + [Link]() + "
seconds</h1>");
}
}
}

// Write Servlet program to select the records from the database table

package ex2;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/jdbc1")
public class Jdbcselect extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException


{
[Link]("text/html");
PrintWriter out = [Link]();

Connection con = null;


PreparedStatement ps = null;
ResultSet rs = null;

try {
// Load MySQL driver
[Link]("[Link]");
[Link]("<h3>Driver Loaded Successfully</h3>");

// Establish connection
con = [Link](
"jdbc:mysql://localhost:3306/abc", "root", "Anil@123");
[Link]("<h3>Connection Established</h3>");

// Prepare SQL query


String sql = "SELECT eno, ename FROM emp WHERE eno > ?";
ps = [Link](sql);

// Set parameter (example: all employees with eno > 100)


[Link](1, 100);

rs = [Link]();

[Link]("<h3>Employee Details:</h3>");
while ([Link]()) {
int eno = [Link]("eno");
String ename = [Link]("ename");
[Link]("Emp No: " + eno + " | Name: " + ename + "<br>");
}

} catch (ClassNotFoundException e) {
[Link]("Error loading MySQL Driver");
[Link]();
} catch (SQLException e) {
[Link]("SQL Error: " + [Link]());
[Link]();
} finally {
// Close all connections
try {
if (rs != null) [Link]();
if (ps != null) [Link]();
if (con != null) [Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}

Output:

// Write Servlet program to insert the record into database.

package ex2;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/insertEmp")
public class Jdbcinsert extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException


{
[Link]("text/html");
PrintWriter out = [Link]();

int eno = 103;


String ename = "John";

Connection con = null;


PreparedStatement ps = null;

try {
// Load MySQL driver
[Link]("[Link]");
[Link]("<h3>Driver Loaded Successfully</h3>");

// Establish connection
con = [Link](
"jdbc:mysql://localhost:3306/abc", "root", "Anil@123");
[Link]("<h3>Connection Established</h3>");

// Prepare SQL insert


String sql = "INSERT INTO emp (eno, ename) VALUES (?, ?)";
ps = [Link](sql);
[Link](1, eno);
[Link](2, ename);

// Execute insert
int rows = [Link]();
if (rows > 0) {
[Link]("<h3>Record inserted successfully! Emp No: " + eno + ", Name: " +
ename + "</h3>");
} else {
[Link]("<h3>Record insertion failed.</h3>");
}

} catch (ClassNotFoundException e) {
[Link]("<h3>Error loading MySQL Driver</h3>");
[Link]();
} catch (SQLException e) {
[Link]("<h3>SQL Error: " + [Link]() + "</h3>");
[Link]();
} finally {
try {
if (ps != null) [Link]();
if (con != null) [Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}

Output:

//Write Servlet program to delete the record into database.

package ex2;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/deleteEmp")
public class JdbcDelete extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException


{
[Link]("text/html");
PrintWriter out = [Link]();

Connection con = null;


PreparedStatement ps = null;

// Hardcoded eno to delete


int enoToDelete = 103;

try {
// Load MySQL driver
[Link]("[Link]");
[Link]("<h3>Driver Loaded Successfully</h3>");

// Establish connection
con = [Link](
"jdbc:mysql://localhost:3306/abc", "root", "Anil@123");
[Link]("<h3>Connection Established</h3>");

// Prepare SQL delete


String sql = "DELETE FROM emp WHERE eno = ?";
ps = [Link](sql);
[Link](1, enoToDelete);

// Execute delete
int rows = [Link]();
if (rows > 0) {
[Link]("<h3>Record deleted successfully! Emp No: " + enoToDelete +
"</h3>");
} else {
[Link]("<h3>No record found with Emp No: " + enoToDelete + "</h3>");
}

} catch (ClassNotFoundException e) {
[Link]("<h3>Error loading MySQL Driver</h3>");
[Link]();
} catch (SQLException e) {
[Link]("<h3>SQL Error: " + [Link]() + "</h3>");
[Link]();
} finally {
try {
if (ps != null) [Link]();
if (con != null) [Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}

Output:

//Write Servlet program to update the record into database.

package ex2;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/updateEmp")
public class JdbcUpdate extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException


{
[Link]("text/html");
PrintWriter out = [Link]();

Connection con = null;


PreparedStatement ps = null;

// update employee with eno 102 to new name "Ravi"


int enoToUpdate = 102;
String newEname = "Ravi";
try {
// Load MySQL driver
[Link]("[Link]");
[Link]("<h3>Driver Loaded Successfully</h3>");

// Establish connection
con = [Link](
"jdbc:mysql://localhost:3306/abc", "root", "Anil@123");
[Link]("<h3>Connection Established</h3>");

// Prepare SQL update


String sql = "UPDATE emp SET ename = ? WHERE eno = ?";
ps = [Link](sql);
[Link](1, newEname);
[Link](2, enoToUpdate);

// Execute update
int rows = [Link]();
if (rows > 0) {
[Link]("<h3>Record updated successfully! Emp No: " + enoToUpdate + ", New
Name: " + newEname + "</h3>");
} else {
[Link]("<h3>No record found with Emp No: " + enoToUpdate + "</h3>");
}

} catch (ClassNotFoundException e) {
[Link]("<h3>Error loading MySQL Driver</h3>");
[Link]();
} catch (SQLException e) {
[Link]("<h3>SQL Error: " + [Link]() + "</h3>");
[Link]();
} finally {
try {
if (ps != null) [Link]();
if (con != null) [Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}
Output:
//Write Servlet program to add cookie to selected value.

package ex2;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/cookieExample")
public class CookiesDemo extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


IOException {
[Link]("text/html");
PrintWriter out = [Link]();

// Step 1: Create a new cookie


Cookie myCookie = new Cookie("user", "Ashok");
[Link](20);
[Link](myCookie);

[Link]("<h3>Cookie 'user' has been created with value 'Ashok'</h3>");

// Step 2: Read all cookies


Cookie[] cookies = [Link]();
if (cookies != null && [Link] > 0) {
[Link]("<h3>All Cookies Received:</h3>");
for (Cookie c : cookies) {
[Link]("Name: " + [Link]() + ", Value: " + [Link]() + "<br>");
}
} else {
[Link]("<p>No cookies found from the browser yet.</p>");
}

[Link]("<br>Reload this page to see the cookie in action.");


}
}
Output:

You might also like