0% found this document useful (0 votes)
2 views55 pages

Java All Practicals

The document outlines practical exercises for implementing servlet applications in Java, including a simple calculator, a login page, and a user registration form using JDBC. It provides HTML and Java code for each application, detailing the structure and functionality required. Additionally, it covers the use of cookies and sessions for user authentication and tracking visits to a servlet.

Uploaded by

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

Java All Practicals

The document outlines practical exercises for implementing servlet applications in Java, including a simple calculator, a login page, and a user registration form using JDBC. It provides HTML and Java code for each application, detailing the structure and functionality required. Additionally, it covers the use of cookies and sessions for user authentication and tracking visits to a servlet.

Uploaded by

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

Practical No.

01
Name:
Sub:Advanced Java Technologies Class:TYBSCIT

Implement the following simple servlet application.


A) Create a simple calculator application using servlet.
[Link]:
Code:
<!doctype html>
<html>
<head>
<title>Calculator </title>
</head>
<body>
<h1>Calculator App</h1>
<form action="Calculator" method="get">
<p>
Enter First Number:
<input type="text" name="txtN1" required>
</p>
<p>
Enter Second Number:
<input type="text" name="txtN2" required>
</p>
<p>
<b>Select an operation:</b>
<br>
<input type="radio" name="opr" value="+" required >Addition<br>
<input type="radio" name="opr" value="-" required
>Subtraction<br>
<input type="radio" name="opr" value="*" required
>Multiplication<br>
<input type="radio" name="opr" value="/" required >Division<br>
</p>
<p>
<input type="reset" value="Reset">
<input type="submit" value="Calculate">
</p>
1
</form>
</body>
</html>

[Link]:
Code:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Calculator extends HttpServlet {


@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out=[Link]();
[Link]("<html><head><title>Servlet
Calculator</title></head></body>");
double n1=[Link]([Link]("txtN1"));
double n2=[Link]([Link]("txtN2"));
double result=0;
String opr=[Link]("opr");
if([Link]("+"))result=n1+n2;
if([Link]("-"))result=n1-n2;
if([Link]("*"))result=n1*n2;
if([Link]("/"))result=n1/n2;
[Link]("<h1> Result="+result);
2
[Link]("</body></html>");
}
}

Output:

1)Addition

2)Subtraction

3
3)Multiplication

4)Division

4
B) Create a servlet for a login page if the username and password are
correct then it says message “Hello <username>” else print a message
as “login failed”.

[Link]:

Code:

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="LoginServlet" method="get">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
if([Link]("username").equals("admin")
&& [Link]("password").equals(“admin")){
[Link]("<h1>Hello,"+"" +[Link]("username") +
"</h1>");
5
}
else{
[Link]("<h1>Invalid User!</h1>");
}
}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}
}

Output:

6
c) Create a registration servlet in Java using JDBC. Accept the details such as
Username, Password, Email, and Country from the user using HTML Form
and store the registration details in the database.
Solution:
Pre-requisites:
1)Download and Install MySQL Server – version 8.4.0 for 64 Bit ->once
installed open mysql and set password for mysql.
2) Download MySQL Connector JAR file having version 8.4.0 -> copy that file
from downloads and paste it on desktop.
3)Once jar file installed u need to add that as connector .so,Open Netbeans
IDE and go to services -> Databases -> New Connection(add driver
connection) -> select : Mysql (coonector/J Driver)-> Add ->select path for
downloaded jar file(which we have already copied on desktop) ->add ->enter
username and password(which we have given in mysql( [Link]=”root”
and password=”root”) ->Finish.
4)Then click on mysql->connect.
5)Now,create database and table so we can directly insert data into that table
in this code.
7
So,for that right mysql->create database->Enter database name : BSCIT -
>Ok.
6)Then DB created right cilick on it and click on connect [Link]
BSCIT(DB) ->Tables ->create table ->Give table name as : Registration -
>now add columns in that table

Column
Data Type Size Constraint
Name

Username VARCHAR 50 Primary Key

Password VARCHAR 20

Email VARCHAR 50 Unique

Country VARCHAR 50

7)Here, all DB related connections are [Link] create new project in


netbeans IDE and give name as “Practical02A “ and then once project is
created, add same jar file into project library - > Practical02A -> Libraries -
>Add JAR file.
8)Now create html form so we can accept values using form and add it into
out table.
[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
<style>
body {
font-family: Arial, sans-serif;
background: #f4f6f9;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.form-container {
background: #fff;
padding: 25px 30px;
border-radius: 10px;

8
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
width: 350px;
}
.form-container h2 {
text-align: center;
margin-bottom: 20px;
color: #333;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 6px;
font-weight: bold;
color: #444;
}
input, select {
width: 100%;
padding: 8px 10px;
border: 1px solid #ccc;
border-radius: 6px;
font-size: 14px;
}
input:focus, select:focus {
border-color: #007bff;
outline: none;
}
.submit-btn {
width: 100%;
padding: 10px;
background: #007bff;
border: none;
border-radius: 6px;
color: white;
font-size: 16px;
cursor: pointer;
}
.submit-btn:hover {
background: #0056b3;
}
</style>
</head>
<body>

<div class="form-container">
<h2>User Registration</h2>
<form action="UserRegistration" method="post">

<div class="form-group">
<label for="username">Username</label>
9
<input type="text" id="username" name="username" required>
</div>

<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
</div>

<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
</div>

<div class="form-group">
<label for="country">Country</label>
<select id="country" name="country" required>
<option value="">-- Select Country --</option>
<option value="India">India</option>
<option value="Thailand">Thailand</option>
<option value="Costa Rica">Costa Rica</option>
<option value="Other">Other</option>
</select>
</div>

<button type="submit" class="submit-btn">Register</button>


</form>
</div>

</body>
</html>

[Link] :
import [Link].*;
import [Link].*;

import [Link].*;

import [Link].*;

public class UserRegistration extends HttpServlet {

private static final String DB_URL =


"jdbc:mysql://localhost:3306/bscit?useSSL=false";

private static final String DB_USER = "root"; // change if needed

private static final String DB_PASS = "root"; // change if needed

public void doPost(HttpServletRequest request, HttpServletResponse response)

10
throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

try {

// Load MySQL JDBC Driver

[Link]("[Link]");

// Create Connection

Connection con = [Link](DB_URL, DB_USER,


DB_PASS);

// Prepare SQL Insert

String query = "INSERT INTO registration VALUES (?, ?, ?, ?)";

PreparedStatement ps = [Link](query);

[Link](1, [Link]("username"));

[Link](2, [Link]("password"));

[Link](3, [Link]("email"));

[Link](4, [Link]("country"));
int result = [Link]();

if (result > 0) {

[Link]("<h3>Registration successful!</h3>");

} else {

[Link]("<h3>Registration failed. Please try again.</h3>");

[Link]();
[Link]();

catch (Exception e)

11
[Link]();
[Link]("<h3>Error: " + [Link]() + "</h3>");

Output:
Database setup:

[Link]:

12
Verify whether data is inserted into table :

13
Practical NO.02
Name: Roll No:
Subject :Advanced Java Technologies

Aim: Implement the following Servlet applications with Cookies and Sessions.
a) Using Request Dispatcher Interface create a Servlet which will validate the
password entered by the user, if the user has entered "Servlet" as password,
then he will be forwarded to Welcome Servlet else the user will stay on the
[Link] page and an error message will be displayed.
Solution:
1)Create new netbeans project->named as Practical_02_A
2)[Link]
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Page</h2>
<form action="LoginServlet" method="get">
Enter User ID: <input type="text" name="txtid"><br><br>
Enter Password: <input type="password" name="txtpass"><br><br>
<input type="reset">
<input type="submit" value="Click to Login">
</form>
</body>
</html>

3)[Link]:

14
import [Link].*;
import [Link].*;
import [Link].*;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String username = [Link]("txtid");
String password = [Link]("txtpass");

if ([Link]("admin") &&
[Link]("servlet")) {
// Forward to WelcomeServlet
RequestDispatcher rd =
[Link]("WelcomeServlet");
[Link](request, response);
} else {
// Invalid login: show error and include form again
[Link]("<p style='background-color:red; color:white;
padding:5px;'>Invalid credentials! Please try again.</p>");
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
}
}
}

4)[Link]:
import [Link].*;
import [Link].*;
import [Link].*;

public class WelcomeServlet extends HttpServlet {


15
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();
String uname = [Link]("txtid");
[Link]("<html><head>");
[Link]("<title>Welcome Page</title></head>");
[Link]("<body bgcolor='lightgreen'>");
[Link]("<h1>Welcome, " + uname + "</h1>");
[Link]("<h2>You have successfully logged in!</h2>");
[Link]("</body></html>");
}
}

Output:

After successful login

16
If login failed / password not matched

B) Create a servlet that uses Cookies to store the number of times a user

has visited servlet. Solution:


[Link]
Code:
<!DOCTYPE html>
<html>
<head>
<title>Cookie Demo</title>
</head>
<body>
<form action="Page1">
Enter your Name
<input type="text" name="txtName"><br>
<input type="submit" value="~~~Click to Enter~~~">
</form>
</body>
</html>

17
[Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Page1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
[Link]("<html><head><title>Page1</title></head>");
[Link]("<body bgcolor='pink'>");
String uname = [Link]("txtName");
[Link]("<h1>~~~ Welcome " + uname + " ~~~</h1>");
// Create cookies
Cookie ck1 = new Cookie("username", uname);
Cookie ck2 = new Cookie("visit", "1");
// Add cookies to response
[Link](ck1);
[Link](ck2);
[Link]("<h1><a href='Page2'>Click to visit Page 2</a></h1>");
[Link]("</body></html>");
}
}

18
[Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Page2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
[Link]("<html><head><title>Page2</title></head>");
[Link]("<body bgcolor='yellow'>");
Cookie[] ck = [Link]();
if (ck != null) {
for (int i = 0; i < [Link]; i++) {
if (ck[i].getName().equals("visit")) {
int count = [Link](ck[i].getValue()) + 1;
[Link]("<h1>Visit No : " + count + "</h1>");
// update visit count
ck[i] = new Cookie("visit", [Link](count));
[Link](ck[i]);
} else {
[Link]("<h1>" + ck[i].getName() + " = " + ck[i].getValue() + "</h1>");
}

// Links to next pages


[Link]("<h1><a href='Page3'>Click to visit Page 3</a></h1>");
[Link]("<h1><a href='Page4'>Click to visit Page 4</a></h1>");
[Link]("<h1><a href='Page5'>Click to visit Page 5</a></h1>");
[Link]("</body></html>");
}
}

19
Output:

C) Create a servlet demonstrating the use of session creation and


destruction. Also check whether the user has visited this page first time
or has visited earlier also using sessions.
Solution:
[Link]
<html>
<head><title>Session Demo</title></head>
<form action="Page1" method="get" >
Enter User ID <input type="text" name="txtName"><br>
<input type="reset" ><input type="submit" >
</form>
</html>

20
[Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Page1 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
[Link]("<html><head><title>Servlet Page1</title></head>");
HttpSession hs = [Link](true);
if([Link]())
{
[Link]("<body bgcolor=yellow>");
String name = [Link]("txtName");
[Link]("uname", name);
[Link]("visit", "1");
[Link]("<h1>Welcome First Time</h1>");
}
else
{
[Link]("<h1>Welcome Again</h1>");
int visit = [Link]((String)[Link]("visit"))+1; [Link]("<h1>You Visited
"+visit+"Times</h1>");
[Link]("visit", ""+visit);
}
[Link]("<h1>Your Session ID "+[Link]()+"</h1>");
[Link]("<h1>You Logged in at "+new [Link]([Link]())+"</h1>");
[Link]("<h1><a href=Page2>Click for Page 2 </a></h1>");
[Link]("<h1><a href=Page3>Click for Page 3 </a></h1>"); [Link]("<h1><a
href=Page4>Click for Page 4 </a></h1>");
[Link]("<h1><a href=LogoutServlet>Click to Terminate Session </a></h1>");
[Link]("</body>");
[Link]("</html>");
}
}

21
[Link]

import [Link]; import [Link];


import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Page2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8"); PrintWriter out =
[Link]();
[Link]("<html><head><title>Servlet Page2</title></head>");
HttpSession hs = [Link](false);
[Link]("<h1>Welcome Again on Page No. 2</h1>");
int visit = [Link]((String)[Link]("visit"))+1;
[Link]("<h1>You Visited "+visit+"Times</h1>");
[Link]("visit", ""+visit);
[Link]("<h1>Your Session ID "+[Link]()+"</h1>");
[Link]("<h1>You Logged in at "+new
[Link]([Link]())+"</h1>");
[Link]("<h1><a href=Page1>Click for Page 1 </a></h1>");
[Link]("<h1><a href=Page3>Click for Page 3 </a></h1>");
[Link]("<h1><a href=Page4>Click for Page 4 </a></h1>");
[Link]("<h1><a href=LogoutServlet>Click for Terminate Session
</a></h1>");
[Link]("</body>");
[Link]("</html>");
}
}

22
[Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Page3 extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
[Link]("<html><head><title>Servlet Page2</title></head>");
HttpSession hs = [Link](false);
[Link]("<h1>Welcome Again on Page No. 2</h1>");
int visit = [Link]((String)[Link]("visit"))+1;
[Link]("<h1>You Visited "+visit+"Times</h1>");
[Link]("visit", ""+visit);
[Link]("<h1>Your Session ID "+[Link]()+"</h1>");
[Link]("<h1>You Logged in at "+new
[Link]([Link]())+"</h1>");
[Link]("<h1><a href=Page1>Click for Page 1 </a></h1>");
[Link]("<h1><a href=Page3>Click for Page 3 </a></h1>");
[Link]("<h1><a href=Page4>Click for Page 4 </a></h1>");
[Link]("<h1><a href=LogoutServlet>Click for Terminate Session
</a></h1>");
[Link]("</body>");
[Link]("</html>");
}
}
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Page4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
[Link]("<html><head><title>Servlet Page2</title></head>");
HttpSession hs = [Link](false);
[Link]("<h1>Welcome Again on Page No. 2</h1>");
int visit = [Link]((String)[Link]("visit"))+1;
[Link]("<h1>You Visited "+visit+"Times</h1>");
[Link]("visit", ""+visit);
[Link]("<h1>Your Session ID "+[Link]()+"</h1>");
[Link]("<h1>You Logged in at "+new
[Link]([Link]())+"</h1>");
[Link]("<h1><a href=Page1>Click for Page 1 </a></h1>");
[Link]("<h1><a href=Page3>Click for Page 3 </a></h1>");
[Link]("<h1><a href=Page4>Click for Page 4 </a></h1>");
[Link]("<h1><a href=LogoutServlet>Click for Terminate Session
</a></h1>");
[Link]("</body>");
[Link]("</html>");
}
}
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
[Link]("<html><head><title>Servlet LogoutServlet</title></head>");
[Link]("<body>");
[Link] hs = [Link]();
if(hs != null) [Link]();
[Link]("<h1>You are Logged out now </h1>");
[Link]("</body>"); [Link]("</html>");
}
}
Output:
Practical No.03
Name: Sub:Advanced Java Technologies
Roll No:

Aim:Implement the Servlet IO and File applications.

a) Create a Servlet application to upload and download a file.

Solution:
To Upload File:

[Link]

<html>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-
data">
Select File to Upload:<input type="file" name="file" id="file">
Destination <input type="text" value="/tmp" name="destination">
<br>
<input type="submit" value="Upload file" name="upload" id="upload">
</form>
</body>
</html>

[Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
String path=[Link]("destination");
Part filePart=(Part) [Link]("file");
String filename=[Link]();
[Link]("<br><br><hr> file name: "+filename);
OutputStream os=null;
InputStream is=null;
try {
os=new FileOutputStream(new File(path+[Link]+filename));
is=[Link]();
int read=0;
while ((read = [Link]()) != -1) {
[Link](read);
}
[Link]("<br>file uploaded sucessfully...!!!");
}
catch(FileNotFoundException e){[Link](e);}
}
}

Output:
File Sucessfully Uploaded.

To Download File:

Folder Structure:

[Link]
<html>
<head>
<title>File Download Page</title>
</head>
<body>
<h1>File Download Application</h1>
Click To Download: <a
href="DownloadServlet?filename=[Link]">Sample Chapter</a>
<br/><br/>
Click To Download : <a
href="DownloadServlet?filename=[Link]">Languages</a>
</body>
</html>

[Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class DownloadServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("APPLICATION/OCTET-STREAM");
String filename = [Link]("filename");
ServletContext context = getServletContext();
InputStream is = [Link]("/" + filename);
//ServletOutputStream out = [Link](); // any of
the two works
PrintWriter out=[Link]();
[Link]("Content-Disposition","attachment; filename=\""
+ filename + "\"");
int i;
while ((i=[Link]()) != -1) {
[Link](i);
}
[Link]();
[Link]();
}
}
Output:

b) Develop Simple Servlet Question Answer Application using Database.


Solution:
1)set DB.
Create DB Name:quizdb
Table:quiz
Now,open MYSQL Command line client

Queries:
insert into quiz values('001','What is the capital of
France?','Paris','Lyon','Marseille','Nice','Paris');
insert into quiz values('002','What is the capital of
Japan?','Osaka','Tokyo','Kyoto','Hiroshima','Tokyo');
insert into quiz values('003','What is the capital of
Australia?','Sydney','Melbourne','Canberra','Perth','Canberra');
insert into quiz values('004','What is the capital of
Canada?','Toronto','Vancouver','Ottawa','Montreal','Ottawa');
insert into quiz values('005','What is the capital of Brazil?','Rio de
Janeiro','São Paulo','Brasília','Salvador','Brasília');
[Link]

<html>
<head>
<title>Quiz Application</title></head>
<body>
<h1>Welcome to Quiz Servlet </h1>
<h1><a href="QuizServlet" style="color:palevioletred" >CLICK TO START
QUIZ</a></h1>
</body>
</html>

[Link]

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class QuizServlet extends HttpServlet {

private static final String DB_URL =


"jdbc:mysql://localhost:3306/quizdb?useSSL=false";
private static final String DB_USER = "root"; // change if needed
private static final String DB_PASS = "root"; // change if needed

@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();

[Link]("<form action='ShowResult' method='get'>");


try {
// Use the updated driver class name
[Link]("[Link]");
Connection con = [Link](DB_URL, DB_USER,
DB_PASS);
Statement stmt = [Link]();
ResultSet res = [Link]("SELECT * FROM quiz");
[Link]("<table border='1'>");
int qno = 0;
while ([Link]()) {
qno++;
[Link]("<tr><td colspan='2'><b>" + [Link](2) +
"</b></td></tr>");
[Link]("<tr><td><input type='radio' name='q" + qno + "' value='"
+ [Link](3) + "'></td><td>" + [Link](3) + "</td></tr>");
[Link]("<tr><td><input type='radio' name='q" + qno + "' value='"
+ [Link](4) + "'></td><td>" + [Link](4) + "</td></tr>");
[Link]("<tr><td><input type='radio' name='q" + qno + "' value='"
+ [Link](5) + "'></td><td>" + [Link](5) + "</td></tr>");
[Link]("<tr><td><input type='radio' name='q" + qno + "' value='"
+ [Link](6) + "'></td><td>" + [Link](6) + "</td></tr>");
}
[Link]("</table>");
[Link]("<input type='reset'>");
[Link]("<input type='submit' value='SUBMIT'>");
[Link]("</form>");

//Close connections
[Link]();
[Link]();
[Link]();

} catch (Exception e) {
[Link]("<p style='color:red;'>Error: " + [Link]() + "</p>");
[Link](out);
}
}
}

Output:
c) Create simple Servlet application to demonstrate Non-Blocking Read
Operation.
Solution:
[Link]

<html>
<head>
<title>Non Blocking IO</title>
<meta charset="UTF-8">
<meta http-equiv="Refresh" content="0; URL=NonBlockingServlet">
</head>
<body>
</body>
</html>
[Link]
import [Link];
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class NonBlockingServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
try (PrintWriter out = [Link]()) {
[Link]("<h1>FileReader</h1>");
String filename="/WEB-INF/[Link]";
ServletContext c=getServletContext();
InputStream in=[Link](filename);
String path="[Link]
[Link]()+"/ReadingNonBloclingServlet";
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection)[Link]();
[Link](2);
[Link](true); [Link]();
if(in!=null)
{
InputStreamReader inr=new InputStreamReader(in); BufferedReader br = new
BufferedReader(inr); String text="";
[Link]("Reading started ");
BufferedWriter bw=new BufferedWriter(new
OutputStreamWriter([Link]()));
while((text=[Link]())!=null){ [Link](text+"<br>");
try{
[Link](1000);
[Link]();
}
catch(InterruptedException ex){}
}[Link]("reading completed ...... ");
[Link](); [Link]();}
}
}
}
[Link]

import [Link]; import


[Link]; import
[Link]; import
[Link];
public class ReadingListener implements ReadListener
{
private ServletInputStream input = null;
private AsyncContext ac = null;
ReadingListener(ServletInputStream in, AsyncContext c) { input =
in;
ac = c;
}
@Override
public void onDataAvailable() throws IOException {
}
public void onAllDataRead() throws IOException {
[Link]();
}
public void onError(final Throwable t) {
[Link]();
[Link]();
}
}
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet (name = "ReadingNonBlockingServlet", urlPatterns =
{"/ReadingNonBlockingServlet"},asyncSupported = true ) public
class ReadingNonBlockingServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html"); AsyncContext
ac = [Link](); ServletInputStream
in=[Link](); [Link](new
ReadingListener(in,ac));
}
}

Output:
Practical No.04

Name:Afifa Jameel Bhatkar Roll No:04


Sub: Advanced Java Technologies.

Aim: Implement the following JSP applications.


a) Develop a simple JSP application to display values obtained from the use
of intrinsic objects of various types.
Solution:
Here,we need to create web application project and inside that create one
jsp file and give name as [Link]
[Link]:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html><head><title>JSP Page</title></head>
<body>
<h1>Use of Intrinsic Objects in JSP</h1>
<h1>Request Object </h1>
Query String <%=[Link]() %><br>
Context Path <%=[Link]() %><br>
Remote Host <%=[Link]() %><br>
<h1>Response Object </h1>
Character Encoding Type <%=[Link]() %><br>
Content Type
<%=[Link]() %><br>
Locale
<%=[Link]() %><br>
<h1>Session Object </h1>
ID <%=[Link]() %><br>
Creation Time <%=new [Link]([Link]()) %><br>
Last Access Time<%=new [Link]([Link]())
%><br>
</body>
</html>
Output:

b) Develop a simple JSP application to pass values from one page to


another with validations. (Name-txt, age-txt, hobbies-checkbox, email-txt,
gender-radio button).
Solution:
[Link]
<html><head><title>User Information Paage</title>
</head>
<body>
<form action="[Link]">
Enter Your Name<input type="text" name="name" ><br>
Enter Your Age<input type="text" name="age" ><br>
Select Hobbies
<input type="checkbox" name="hob" value="Singing">Singing
<input type="checkbox" name="hob" value="Reading">Reading Books
<input type="checkbox" name="hob" value="Football">Playing Football<br>
Enter E-mail<input type="text" name="email" ><br>
Select Gender
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="other">Other<br>
<input type="hidden" name="error" value="">
<input type="submit" value="Submit Form">
</form>
</body>
[Link]

<%@page contentType="text/html" pageEncoding="UTF-8"


import="mypack.*" %>
<html><head><title>JSP Page</title></head>
<body>
<h1>Validation Page</h1>
<jsp:useBean id="obj" scope="request"
class="[Link]" >
<jsp:setProperty name="obj" property="*"/>
</jsp:useBean>
<%if ([Link]())
{ %>
<jsp:forward page="[Link]"/>
<% }
else {%>
<jsp:include page="[Link]"/>
<%}%>
<%=[Link]() %>
</body>
</html>

[Link]
package mypack;
public class CheckerBean {
private String name, age, hob, email, gender, error;
public CheckerBean() {
error = "";
}// --- Setters ---
public void setName(String n) { name = n; }
public void setAge(String a) { age = a; }
public void setHob(String h) { hob = h; }
public void setEmail(String e) { email = e; }
public void setGender(String g) { gender = g; }
public void setError(String e) { error = e; }
// --- Getters ---
public String getName() { return name; }
public String getAge() { return age; }
public String getHob() { return hob; }
public String getEmail() { return email; }
public String getGender() { return gender; }
public String getError() { return error; }
// --- Validation Method ---
public boolean validate() {
boolean res = true;
error = ""; // reset error message each time
// Name validation
if (name == null || [Link]().equals("")) {
error += "<br>Enter your name.";
res = false;
} else if (![Link]("^[A-Za-z ]+$")) {
error += "<br>Name must contain only alphabets.";
res = false;
}
// Age validation
if (age == null || [Link]().equals("")) {
error += "<br>Enter your age.";
res = false;
} else {
try {
int ageVal = [Link](age);
if (ageVal <= 0 || ageVal > 120) {
error += "<br>Enter a valid age between 1 and 120.";
res = false;
}
} catch (NumberFormatException e) {
error += "<br>Age must be a number.";
res = false;
}
}// Hobby validation
if (hob == null || [Link]().equals("")) {
error += "<br>Select at least one hobby.";
res = false;
}// Email validation
if (email == null || [Link]().equals("")) {
error += "<br>Enter your email.";
res = false;
} else if (![Link]("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$")) {
error += "<br>Invalid email format.";
res = false;
}
// Gender validation
if (gender == null || [Link]().equals("")) {
error += "<br>Select your gender.";
res = false;
}return res;
}
}

[Link]
<%@ page contentType="text/html" pageEncoding="UTF-8"
import="mypack.*" %>
<html>
<head>
<title>Success Page</title>
</head>
<body>
<h2>Form Submitted Successfully!</h2>
<jsp:useBean id="obj" scope="request" class="[Link]" />
<p><b>Name:</b> <jsp:getProperty name="obj" property="name" /></p>
<p><b>Age:</b> <jsp:getProperty name="obj" property="age" /></p>
<p><b>Hobbies:</b> <jsp:getProperty name="obj" property="hob" /></p>
<p><b>Email:</b> <jsp:getProperty name="obj" property="email" /></p>
<p><b>Gender:</b> <jsp:getProperty name="obj" property="gender"
/></p><hr>
<p style="color:green;">Thank you for submitting your information!</p>
</body>
</html>

Output:
c) Create a registration and login JSP application to register and
authenticate the user based on username and password using JDBC.
Solution:
[Link]
<html>
<head><title>JSP With JDBC</title></head>
<body>
<h1><a href="[Link]" >New User Register Here</a></h1>
<h1><a href="[Link]" >Click Here to Login</a></h1>
</body>
</html>

[Link]
<html><head><title>New User Registration Page</title></head>
<body>
<form action="[Link]" >
<h1> New User Registration Page</h1>
Enter User Name <input type="text" name="txtName" ><br>
Enter Password <input type="password" name="txtPass1" ><br>
Re-Enter Password<input type="password" name="txtPass2" ><br>
Enter Email<input type="text" name="txtEmail" ><br>
Enter Country Name <input type="text" name="txtCon" ><br>
<input type="reset" ><input type="submit" value="REGISTER" >
</form>
</body>
</html>

[Link]
<%@page contentType="text/html" import="[Link].*"%>
<html><body>
<h1>Registration JSP Page</h1>
<%
String uname=[Link]("txtName");
String pass1 = [Link]("txtPass1");
String pass2 = [Link]("txtPass2");
String email = [Link]("txtEmail");
String ctry = [Link]("txtCon");
if([Link](pass2)){
try{
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/logindb?useSSL=fa
lse","root","root");
PreparedStatement stmt = [Link]("insert into user values
(?,?,?,?)");
[Link](1, uname); [Link](2, pass1);
[Link](3, email); [Link](4, ctry);
int row = [Link]();
if(row==1) { [Link]("Registration Successful"); }
else {
[Link]("Registration FFFFFAAAIIILLLL !!!!");
%>
<jsp:include page="[Link]" ></jsp:include>
<%
}
}catch(Exception e){[Link](e);}
}
else
{
[Link]("<h1>Password Mismatch</h1>");
%>
<jsp:include page="[Link]" ></jsp:include>
<% }
%>
</body>
</html>

[Link]
<html>
<body>
<h1>Login Page</h1>
<form action="[Link]" >
Enter User Name <input type="text" name="txtName" ><br>
Enter Password <input type="password" name="txtPass" ><br>
<input type="reset" ><input type="submit" value="~~~LOGIN~~" >
</form>
</body>
</html>

[Link]:
<%@page contentType="text/html" import="[Link].*"%>
<html><body>
<h1>Registration JSP Page</h1>
<%
String uname=[Link]("txtName");
String pass = [Link]("txtPass");

try{
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/logindb?useSSL=fa
lse","root","root");
PreparedStatement stmt = [Link]("select password from user
where uname=?");
[Link](1, uname);
ResultSet rs = [Link]();
if([Link]()){
if([Link]([Link](1)))
{
[Link]("<h1>~~~ LOGIN SUCCESSFULLL ~~~ </h1>");
}
}
else{
[Link]("<h1>User Name not exist !!!!!</h1>");
%>
<jsp:include page="[Link]" ></jsp:include>
<%
}
}catch(Exception e){[Link](e);}
%>
</body>
</html>

Database:
Practical No.05
Name: Afifa Jameel Bhatkar Roll No: 04
Sub: Advanced Java Technologies.

Aim:Implement the following JSP JSTL and EL Applications.


a) Create an html page with fields, eno, name, age, desg, salary. Now on
submit this data to a JSP page which will update the employee table of
database with matching eno.
Solution:
1) CREATE DATABASE companydb;
2)use companydb;
3)open mysql client:

CREATE TABLE employee (


eno INT PRIMARY KEY,
name VARCHAR(50),
age INT,
desg VARCHAR(50),
salary DECIMAL(10,2)
);
# Insert 2 records:
INSERT INTO employee VALUES
(101, 'Janhavi', 25, 'Developer', 55000),
(102, 'Shivam', 27, 'Designer', 48000);
# Verfiry inserted data:
SELECT * FROM employee;
Now write code to update data:
[Link]
<html>
<body>
<form action="[Link]" >
Enter Employee Number<input type="text" name="txtEno" ><br>
Enter Name<input type="text" name="txtName" ><br>
Enter age<input type="text" name="txtAge" ><br>
Enter Salary<input type="text" name="txtSal" ><br>
<input type="reset" ><input type="submit">
</form>
</body>
</html>

[Link]
<%@page contentType="text/html" import="[Link].*" %>
<html>
<body>
<h1>Employee Record Update</h1>
<%
String eno=[Link]("txtEno");
String name=[Link]("txtName");
String age = [Link]("txtAge");
String sal = [Link]("txtSal");
try{
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/companydb?useSS
L=false","root","root");
PreparedStatement stmt = [Link]("select * from employee
where eno=?");
[Link](1, eno);
ResultSet rs = [Link]();
if([Link]()){
[Link]("<h1> Employee "+name+" Exist </h1>");
PreparedStatement pst1= [Link]("update employee set
salary=? where eno=?");
PreparedStatement pst2= [Link]("update employee set
age=? where eno=?");
[Link](1, sal); [Link](2, eno);
[Link](1, age); [Link](2, eno);
[Link](); [Link]();
}
else{
[Link]("<h1>Employee Record not exist !!!!!</h1>");

}
}catch(Exception e){[Link](e);}
%>
</body>
</html>

Output:

b)Create a JSP page to demonstrate the use of Expression language.


Solution:
[Link]:
<h3>welcome to index page</h3>
<%
[Link]("user","Jack");
%>
<%
Cookie ck=new Cookie("name","Jill");
[Link](ck);
%>
<form action="[Link]">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="Submit"/>
</form>

[Link]
Welcome, ${ [Link] }
Session Value is ${ [Link] }
Cookie Value is Hello, ${[Link]}

[Link]
${5*5+4}
${1.4E4+1.4}
${10 mod 4}
${15 div 3}

[Link]
<h2>Logical Operator</h2>
${true and true}
${true && false}
${true or true}
${true || false}
${not true}
${!false}

[Link]:
<h2>Relational Operator</h2>
${10.0==10}
${10.0 eq 10}
${((20*10)!= 200)}
${3 ne 3}
${3.2>=2}
${3.2 ge 2}
${2<3}
${4 lt 6}
${2 <= 4}
${4 le 2}
<h2>Conditional Operator</h2>
The result of 10>2 is: "${(10>1)?'greater':'lesser'}"
Output:

c) Create a JSP application to demonstrate the use of JSTL.


Solution:
[Link]
<html><body>
<a href="[Link]"> SetDemo</a>
<a href="[Link]"> MaxIF</a>
<a href="[Link]"> ForEachDemo</a>
<a href="[Link]"> OutDemo</a>
</body></html>

Output:
[Link]
<%-- Set page title--%>
<%@taglib prefix="c" uri="[Link] %>
<c:set var="pageTitle" scope="application" value="Dukes Soccer League:
Registration" />
${pageTitle}

Output:

[Link]
<form action ="[Link]">
x=<input type="text" name="x" /><br>
y=<input type="text" name="y" /><br>
<input type="submit" value="Check Max" />
</form>

Output:

[Link]
<%@taglib prefix="c" uri="[Link] %>
<c:set var="x" value="${param.x}"/>
<c:set var="y" value="${param.y}"/>
<c:if test="${x>y}">
<font color="blue"><h2>The Ans is:</h2></font>
<c:out value="${x} is greater than ${y}"/>
</c:if>
Output:

[Link]
<%@taglib prefix="c" uri="[Link] %>
<c:forEach begin="1" end="10" var="i">
The Square of <c:out value=" ${i}=${i*i}"/><br>
</c:forEach>

Output:

[Link]
<%@taglib prefix="c" uri="[Link] %>
<c:set var="name" value="ABC"/>
My name is: <c:out value= "${name}" />

Output:
10

You might also like