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

Advanced Java Practical

The document provides a detailed guide on implementing various Java web applications using JDBC and servlets, including creating a JDBC connection, performing CRUD operations, and understanding servlet lifecycles. It includes code examples for both GenericServlet and HttpServlet, along with instructions for setting up projects in Eclipse and NetBeans. Additionally, it covers session tracking techniques such as URL rewriting and hidden fields, and provides HTML forms for user interaction.

Uploaded by

gjhansi2526
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 views37 pages

Advanced Java Practical

The document provides a detailed guide on implementing various Java web applications using JDBC and servlets, including creating a JDBC connection, performing CRUD operations, and understanding servlet lifecycles. It includes code examples for both GenericServlet and HttpServlet, along with instructions for setting up projects in Eclipse and NetBeans. Additionally, it covers session tracking techniques such as URL rewriting and hidden fields, and provides HTML forms for user interaction.

Uploaded by

gjhansi2526
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

Advanced java practical:

Program1 – Complete JDBC Operations

File Name:

[Link]

package advjava;

import [Link].*;

public class Program1 {

public static void main(String[] args) {

try {
// 1. Load Driver
[Link]("[Link]");
[Link]("Driver Loaded");

// 2. Create Connection
Connection conn = [Link](
"jdbc:oracle:thin:@localhost:1521/orclpdb",
"jdbcuser",
"jdbc123"
);
[Link]("Connected to Database");

Statement st = [Link]();

// 3. Create Table
try {
[Link]("CREATE TABLE program1_data (id NUMBER, name
VARCHAR2(50), age NUMBER)");
[Link]("Table Created");
} catch (Exception e) {
[Link]("Table already exists");
}

// 4. Insert Records
[Link]("INSERT INTO program1_data VALUES (1, 'Jhansi', 22)");
[Link]("INSERT INTO program1_data VALUES (2, 'Navya', 21)");
[Link]("INSERT INTO program1_data VALUES (3, 'Sowjanya', 23)");
[Link]("Records Inserted");

// 5. Read Data (ResultSet)


ResultSet rs = [Link]("SELECT * FROM program1_data");

[Link]("\n--- Data Before Deletion ---");


while ([Link]()) {
[Link](
[Link]("id") + " " +
[Link]("name") + " " +
[Link]("age")
);
}

// 6. Delete One Record


[Link]("DELETE FROM program1_data WHERE id = 2");
[Link]("\nRecord with ID=2 Deleted");

// 7. Read Again
ResultSet rs2 = [Link]("SELECT * FROM program1_data");

[Link]("\n--- Data After Deletion ---");


while ([Link]()) {
[Link](
[Link]("id") + " " +
[Link]("name") + " " +
[Link]("age")
);
}

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

[Link]("\nDone Successfully");

} catch (Exception e) {
[Link]();
}
}
}

Steps:
Create Project
• Open Eclipse
• Click File → New → Java Project
• Project Name: advjava
• Click Finish

2. Create Package
• Right click on src
• New → Package
• Name: advjava

3. Create Class
• Right click on package advjava
• New → Class
• Name: Program1
• Tick public static void main
• Click Finish
4. Paste Code
• Open [Link]
• Replace with your code

5. Add Oracle JDBC Driver (IMPORTANT)


• Right click project → Build Path → Configure Build Path
• Go to Libraries tab
• Click Add External JARs
• Select [Link]
• Click Apply → OK

6. Run the Program


• Right click [Link]
• Click Run As → Java Application

7. Verify in SQL Developer


Run:
SELECT * FROM program1_data;
2(a) – GenericServlet Lifecycle
File Name:
[Link]
package advjava2;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Program11 extends GenericServlet {

// 1. init() – called only once when servlet is loaded


public void init() throws ServletException {
[Link]("Servlet initialized");
}

// 2. service() – called for every request


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

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

[Link]("<h2>GenericServlet Life Cycle Demo</h2>");


[Link]("<p>service() method executed</p>");
}

// 3. destroy() – called before servlet is removed


public void destroy() {
[Link]("Servlet destroyed");
}
}

[Link]

<web-app>
<!-- 11(a) GenericServlet -->
<servlet>
<servlet-name>Program11</servlet-name>
<servlet-class>advjava2.Program11</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Program11</servlet-name>
<url-pattern>/Program11</url-pattern>
</servlet-mapping>
</web-app>

[Link]:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h2>Click to call GenericServlet</h2>


<form action="Program11" method="get">
<input type="submit" value="Call Servlet">
</form>
</body>
</html>

steps (including JAR + setup)

1. Create Dynamic Web Project


• Open Eclipse
• File → New → Dynamic Web Project
• Project Name: advjava2
• Target Runtime → Select Apache Tomcat
• Click Finish

2. Project Structure
Inside project:
advjava2
├── src/main/java
│ └── advjava2 (package)
│ └── [Link]
├── src/main/webapp
│ ├── [Link]
│ └── WEB-INF
│ └── [Link]

3. Create Package + Servlet


• Right click → src/main/java
• New → Package → advjava2
• Right click package → New → Class → Program11
• Paste your servlet code

4. Create HTML File


• Right click src/main/webapp
• New → HTML File → [Link]
• Paste your HTML code

5. Configure [Link]
• Go to:
src/main/webapp/WEB-INF/[Link]
• Paste your mapping
Your JAR setup status
From your screenshot:
• [Link] is already present ✔️
• Which file to run?
• Always run:
• [Link]
6. Run Project
• Right click project
• Run As → Run on Server (Tomcat)

Sql:
(no db)

2(b) – HttpServlet Lifecycle


File Name:
Program2B:
package advjava3;

import [Link];

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

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

public class Program11B extends HttpServlet {

Connection conn;
PreparedStatement ps;

// init() – Establish Oracle DB connection


public void init() throws ServletException {
try {
[Link]("[Link]");
conn = [Link](
"jdbc:oracle:thin:@//localhost:1521/orclpdb",
"jdbcuser",
"jdbc123"
);
[Link]("Oracle DB connection established in init()");
} catch (Exception e) {
[Link]();
}
}

// doPost() – Insert student record into students1 table


protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

String sid = [Link]("sid");


String sname = [Link]("sname");
String sage = [Link]("sage");

try {
ps = [Link](
"INSERT INTO students1 (SID, SNAME, SAGE) VALUES (?, ?, ?)"
);
[Link](1, [Link](sid));
[Link](2, sname);
[Link](3, [Link](sage));

int rows = [Link]();

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

if (rows > 0) {
[Link]("<h3>Student record inserted successfully!</h3>");
} else {
[Link]("<h3>Failed to insert record.</h3>");
}

} catch (SQLException e) {
[Link]();
}
}

// destroy() – Close DB resources


public void destroy() {
try {
if (ps != null) [Link]();
if (conn != null) [Link]();
[Link]("Oracle DB connection closed in destroy()");
} catch (Exception e) {
[Link]();
}
}
}

[Link]:
<?xml version="1.0" encoding="UTF-8"?>

<web-app>
<!-- 11(b) HttpServlet -->
<servlet>
<servlet-name>Program11B</servlet-name>
<servlet-class>advjava3.Program11B</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Program11B</servlet-name>
<url-pattern>/Program11B</url-pattern>
</servlet-mapping>
</web-app>

[Link]:
<!DOCTYPE html>
<html>
<head>
<title>Insert Student Record</title>
</head>
<body>
<h2>Insert Student Record</h2>
<form action="Program11B" method="post">
SID: <input type="text" name="sid"><br><br>
Name: <input type="text" name="sname"><br><br>
Age: <input type="text" name="sage"><br><br>
<input type="submit" value="Insert">
</form>
</body>
</html>

Sql:
SELECT* FROM students1;

3(a). Servlet Session Tracking (URL Rewriting + Hidden Field)

1. Create Project
• Open NetBeans
• File → New Project
• Java Web → Web Application
• Project Name: SessionDemo
• Server: Select Apache Tomcat
• Click Finish

2. Create Package
• Right click Source Packages
• New → Java Package
• Name: advjava
File name:
[Link]
package advjava;

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

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

public class Program13 extends HttpServlet {

Connection conn;
PreparedStatement ps;

// init() – Oracle DB connection


public void init() throws ServletException {
try {
[Link]("[Link]");
conn = [Link](
"jdbc:oracle:thin:@//localhost:1521/orclpdb",
"jdbcuser",
"jdbc123"
);
[Link]("Oracle DB connected (Program13)");
} catch (Exception e) {
[Link]();
}
}

// doGet() – Session tracking + DB insert


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

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

String username = [Link]("username");

// Create session
HttpSession session = [Link]();
String sessionId = [Link]();

// Store in session
[Link]("username", username);

try {
ps = [Link](
"INSERT INTO session_users (username, session_id) VALUES (?, ?)"
);
[Link](1, username);
[Link](2, sessionId);
[Link]();
} catch (Exception e) {
[Link]();
}

[Link]("<html><body>");
[Link]("<h2>Session Tracking with Oracle DB</h2>");
[Link]("<p>Hello, " + username + "</p>");
[Link]("<p>Session ID: " + sessionId + "</p>");
[Link]("<p>Session Created: "
+ new [Link]([Link]()) + "</p>");
[Link]("</body></html>");
}

// destroy() – Close DB resources


public void destroy() {
try {
if (ps != null) [Link]();
if (conn != null) [Link]();
[Link]("Oracle DB connection closed (Program13)");
} catch (Exception e) {
[Link]();
}
}
}

[Link]:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
version="3.1">

<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>Program13</servlet-name>
<servlet-class>advjava.Program13</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Program13</servlet-name>
<url-pattern>/Program13</url-pattern>
</servlet-mapping>

</web-app>

[Link]:
<!DOCTYPE html>
<html>
<head>
<title>Session Tracking Demo</title>
</head>
<body>
<h2>Session Tracking Example</h2>
<form action="Program13" method="get">
Enter your name:
<input type="text" name="username" required>
<input type="submit" value="Submit">
</form>
</body>
</html>

Click run file:


In [Link]
Sql:
Select*from session_users;
3(b).url-rewritten:

File name: Program16


package advjava16;

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

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

public class Program16 extends HttpServlet {

Connection conn;
PreparedStatement ps;

public void init() throws ServletException {


try {
[Link]("[Link]");
conn = [Link](
"jdbc:oracle:thin:@//localhost:1521/orclpdb",
"jdbcuser",
"jdbc123"
);
} catch (Exception e) {
[Link]();
}
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

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

try {
ps = [Link](
"INSERT INTO url_users VALUES (?, ?)"
);
[Link](1, username);
[Link](2, "Data passed using URL Rewriting");
[Link]();
} catch (Exception e) {
[Link]();
}

[Link]("<html><body>");
[Link]("<h2>URL Rewriting with DB</h2>");
[Link]("<p>Hello, " + username + "</p>");

// URL rewriting
[Link]("<a href='Program16?username=" + username + "'>");
[Link]("Continue</a>");

[Link]("</body></html>");
}

public void destroy() {


try {
if (ps != null) [Link]();
if (conn != null) [Link]();
} catch (Exception e) {
[Link]();
}
}
}

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
version="3.1">

<servlet>
<servlet-name>Program16</servlet-name>
<servlet-class>advjava16.Program16</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Program16</servlet-name>
<url-pattern>/Program16</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>

</web-app>
[Link]
<!DOCTYPE html>
<html>
<head>
<title>URL Rewriting Demo</title>
</head>
<body>
<h2>URL Rewriting Example</h2>

<form action="Program16" method="get">


Enter Name:
<input type="text" name="username" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
Run [Link](right click and then run file)
Sql:
Select*from url_users;

3(c).hidden form field:


File name: Program17
package advjava17;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

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

public class Program17 extends HttpServlet {

Connection conn;
PreparedStatement ps;

public void init() throws ServletException {


try {
[Link]("[Link]");
conn = [Link](
"jdbc:oracle:thin:@//localhost:1521/orclpdb",
"jdbcuser",
"jdbc123"
);
} catch (Exception e) {
[Link]();
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

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

String username = [Link]("username");


String password = [Link]("password");
String source = [Link]("source"); // hidden field value

try {
ps = [Link](
"INSERT INTO hidden_form_users (username, password) VALUES (?, ?)"
);
[Link](1, username);
[Link](2, password);
[Link]();
} catch (Exception e) {
[Link]();
}

[Link]("<html><body>");
[Link]("<h2>Hidden Field Submitted Successfully</h2>");
[Link]("<p>Username: " + username + "</p>");
[Link]("<p>Password: " + password + "</p>");
[Link]("<p>Source: " + source + "</p>");
[Link]("</body></html>");
}

public void destroy() {


try {
if (ps != null) [Link]();
if (conn != null) [Link]();
} catch (Exception e) {
[Link]();
}
}
}

[Link]:

<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
version="3.1">

<servlet>
<servlet-name>Program17</servlet-name>
<servlet-class>advjava17.Program17</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Program17</servlet-name>
<url-pattern>/Program17</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>

</web-app>
[Link]:
<!DOCTYPE html>
<html>
<head>
<title>Hidden Form Field Example</title>
</head>
<body>
<h2>Hidden Form Field Example</h2>
<form action="Program17" method="post">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>

<!-- Hidden Field -->


<input type="hidden" name="source" value="hiddenFormDemo">

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


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

Sql:
Select*from hidden_form_users;

13(d) cookies
File name:Program14
package advjava14;

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

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

public class Program14 extends HttpServlet {

Connection conn;
PreparedStatement ps;

// init() – Oracle DB connection


public void init() throws ServletException {
try {
[Link]("[Link]");
conn = [Link](
"jdbc:oracle:thin:@//localhost:1521/orclpdb",
"jdbcuser",
"jdbc123"
);
[Link]("Oracle DB connected (Program14)");
} catch (Exception e) {
[Link]();
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

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

String username = [Link]("username");


String password = [Link]("password");

// CREATE cookies
Cookie c1 = new Cookie("username", username);
Cookie c2 = new Cookie("password", password);

[Link](60 * 60);
[Link](60 * 60);

[Link](c1);
[Link](c2);

// STORE cookies into DB


try {
ps = [Link](
"INSERT INTO cookie_users (username, cookie_value) VALUES (?, ?)"
);

[Link](1, username);
[Link](2, password);
[Link]();

} catch (Exception e) {
[Link]();
}

// READ cookies
[Link]("<html><body>");
[Link]("<h2>Cookies Stored Successfully</h2>");

Cookie[] cookies = [Link]();


if (cookies != null) {
for (Cookie c : cookies) {
[Link]("<p>" + [Link]() + " : " + [Link]() + "</p>");
}
}

[Link]("</body></html>");
}

// destroy() – close DB resources


public void destroy() {
try {
if (ps != null) [Link]();
if (conn != null) [Link]();
[Link]("Oracle DB closed (Program14)");
} catch (Exception e) {
[Link]();
}
}
}

[Link]:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
version="3.1">
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>Program14</servlet-name>
<servlet-class>advjava14.Program14</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Program14</servlet-name>
<url-pattern>/Program14</url-pattern>
</servlet-mapping>

</web-app>

[Link]
<!DOCTYPE html>
<html>
<head>
<title>Cookies with DB</title>
</head>
<body>

<h2>Cookies Demonstration</h2>

<form action="Program14" method="post">


Username:
<input type="text" name="username" required><br><br>

Password:
<input type="password" name="password" required><br><br>

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


</form>

</body>
</html>

Sql:
Select*from cookie_users;

[Link] life cycle:


File name:[Link]
<%@ page import="[Link].*" %>
<%@ page import="[Link].*" %>
<%@ page import="[Link].*" %>

<%!
// Declaration Tag - Variables for JDBC
Connection conn;
PreparedStatement ps;

// init method to simulate JSP initialization


public void jspInit() {
try {
[Link]("[Link]");
conn = [Link](
"jdbc:oracle:thin:@//localhost:1521/orclpdb",
"jdbcuser",
"jdbc123"
);
[Link]("JSP Init: Connection Established");
} catch(Exception e) {
[Link]();
}
}
// destroy method to simulate JSP cleanup
public void jspDestroy() {
try {
if(ps != null) [Link]();
if(conn != null) [Link]();
[Link]("JSP Destroy: Connection Closed");
} catch(Exception e) {
[Link]();
}
}

// method to insert user into DB


public String insertUser(String username, String password) {
try {
ps = [Link]("INSERT INTO users(username, password)
VALUES(?, ?)");
[Link](1, username);
[Link](2, password);
[Link]();
return "User saved successfully!";
} catch(Exception e) {
[Link]();
return "Error saving user.";
}
}
%>

<%
// Scriptlet Tag - simulate jsp service
jspInit(); // simulate init
String message = "";
String username = [Link]("username");
String password = [Link]("password");

if(username != null && password != null){


message = insertUser(username, password);
}
%>

<html>
<head>
<title>JSP Lifecycle Demo</title>
</head>
<body>
<h2>JSP Lifecycle & DB Insert Demo</h2>

<form method="post">
Username: <input type="text" name="username" required /><br><br>
Password: <input type="password" name="password" required /><br><br>
<input type="submit" value="Submit" />
</form>

<%
// Expression Tag
%>
<p><%= message %></p>

<%
// simulate destroy
jspDestroy();
%>

</body>
</html>

Sql: select*from users;

[Link] tags:

[Link] tags:([Link])
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="[Link] prefix="c" %>

<!DOCTYPE html>
<html>
<head>
<title>JSTL Core Tags Complete Demo</title>
</head>
<body>

<h2>JSTL Core Tags Demonstration</h2>


<!-- ================= GENERAL PURPOSE TAGS ================= -->
<h3>1. General Purpose Tags</h3>

<!-- c:set -->


<c:set var="name" value="Jhansi" />
<c:set var="age" value="22" />

<p>Name: ${name}</p>
<p>Age: ${age}</p>

<!-- c:remove -->


<c:remove var="name" />
<p>After Removing Name: ${name}</p>

<hr>

<!-- ================= CONDITIONAL TAGS ================= -->


<h3>2. Conditional Tags</h3>

<!-- c:if -->


<c:if test="${age >= 18}">
<p>You are eligible to vote.</p>
</c:if>

<!-- c:choose -->


<c:choose>
<c:when test="${age < 18}">
Minor
</c:when>
<c:when test="${age >= 18 && age <= 60}">
Adult
</c:when>
<c:otherwise>
Senior Citizen
</c:otherwise>
</c:choose>

<hr>

<!-- ================= ITERATION TAGS ================= -->


<h3>3. Iteration Tags</h3>

<!-- c:forEach -->


<c:forEach var="i" begin="1" end="3">
<p>Number: ${i}</p>
</c:forEach>

<!-- c:forTokens -->


<c:forTokens items="Java,Python,SQL" delims="," var="lang">
<p>Language: ${lang}</p>
</c:forTokens>

<hr>

<!-- ================= NETWORKING / URL TAGS ================= -->


<h3>4. Networking / URL Tags</h3>

<!-- c:url -->


<c:url value="[Link]" var="myUrl" />
<a href="${myUrl}">Reload This Page</a>

<br><br>

<!-- c:redirect (commented to avoid auto redirect) -->


<%--
<c:redirect url="[Link] />
--%>

<p>c:redirect example is written in comment to avoid automatic redirection.</p>

</body>
</html>

[Link] tags(jstl_sql.jsp):
<%@ page contentType="text/html;charset=UTF-8" %>

<%@ taglib uri="[Link] prefix="sql" %>


<%@ taglib uri="[Link] prefix="c" %>

<html>
<head>
<title>JSTL SQL Tags Demonstration</title>
</head>
<body>

<h2>JSTL SQL Tags Demonstration</h2>

<!-- 1. sql:setDataSource -->


<h3>1. sql:setDataSource</h3>

<sql:setDataSource
var="db"
driver="[Link]"
url="jdbc:oracle:thin:@localhost:1521/orclpdb"
user="jdbcuser"
password="jdbc123"/>

<p>Database connection established successfully.</p>

<hr>

<!-- 2. User Input -->


<h3>2. sql:update & sql:param</h3>

<form method="post">
Record ID: <input type="number" name="rid" required><br><br>
Record Name: <input type="text" name="rname" required><br><br>
<input type="submit" value="Insert Record">
</form>

<c:if test="${not empty [Link] and not empty [Link]}">

<sql:update var="count" dataSource="${db}">


INSERT INTO jsp_sql_data VALUES (?, ?)
<sql:param value="${[Link]}" />
<sql:param value="${[Link]}" />
</sql:update>

<p style="color:green;">
${count} Record Inserted Successfully!
</p>
</c:if>

<hr>

<!-- 3. sql:query -->


<h3>3. sql:query</h3>

<sql:query var="result" dataSource="${db}">


SELECT * FROM jsp_sql_data
</sql:query>

<p>Query executed successfully. Data can be verified in SQL Developer.</p>

</body>
</html>
Sql: select*from jsp_sql_data;

(c)fmt tags(jstl_format.jsp)

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

<%@ taglib uri="[Link] prefix="c" %>


<%@ taglib uri="[Link] prefix="fmt" %>

<html>
<head>
<title>JSTL Formatting Tags Demonstration</title>
</head>
<body>

<h2>JSTL Formatting Tags Demonstration</h2>

<!-- ==================== 1. fmt:setLocale ==================== -->


<h3>1. fmt:setLocale</h3>

<fmt:setLocale value="en_IN"/>
<p>Locale set to India.</p>

<hr>

<!-- ==================== 2. fmt:formatNumber ==================== -->


<h3>2. fmt:formatNumber</h3>

<c:set var="amount" value="1234567.89"/>

Currency Format (Rupees):


<fmt:formatNumber value="${amount}" type="currency"/><br><br>

Number Format (Grouping):


<fmt:formatNumber value="${amount}" type="number" groupingUsed="true"/>

<hr>

<!-- ==================== 3. fmt:parseNumber ==================== -->


<h3>3. fmt:parseNumber</h3>

<fmt:parseNumber var="parsedNumber" value="4567.89" type="number"/>


Parsed Number: ${parsedNumber}

<hr>

<!-- ==================== 4. fmt:formatDate ==================== -->


<h3>4. fmt:formatDate</h3>

<c:set var="today" value="<%= new [Link]() %>" />

Formatted Date:
<fmt:formatDate value="${today}" type="both" dateStyle="full"
timeStyle="short"/>

<hr>

<!-- ==================== 5. fmt:parseDate ==================== -->


<h3>5. fmt:parseDate</h3>

<fmt:parseDate var="parsedDate" value="03-03-2026" pattern="dd-MM-yyyy"/>


Parsed Date: ${parsedDate}

<hr>

<!-- ==================== 6. fmt:setBundle & fmt:message


==================== -->
<h3>6. fmt:setBundle & fmt:message</h3>

<p>
These tags are used for internationalization (i18n) using properties files.
</p>

</body>
</html>

[Link](jstl_xml.jsp)
<%@ page contentType="text/html;charset=UTF-8" %>

<%@ taglib uri="[Link] prefix="c" %>


<%@ taglib uri="[Link] prefix="x" %>

<html>
<head>
<title>JSTL XML Tags Demonstration</title>
</head>
<body>

<h2>JSTL XML Tags Demonstration</h2>

<!-- Sample XML Data -->


<c:set var="xmlData">
<employees>
<employee>
<id>1</id>
<name>Leeknow</name>
<department>Development</department>
</employee>
<employee>
<id>2</id>
<name>Jisung</name>
<department>Testing</department>
</employee>
</employees>
</c:set>

<!-- ==================== 1. x:parse ==================== -->


<h3>1. x:parse</h3>
<x:parse xml="${xmlData}" var="doc"/>
XML Data Parsed Successfully.

<hr>

<!-- ==================== 2. x:out ==================== -->


<h3>2. x:out</h3>

First Employee Name:


<x:out select="$doc/employees/employee[1]/name"/>

<hr>

<!-- ==================== 3. x:if ==================== -->


<h3>3. x:if</h3>

<x:if select="$doc/employees/employee[1]/department='Development'">
First employee works in Development department.
</x:if>

<hr>

<!-- ==================== 4. x:set ==================== -->


<h3>4. x:set</h3>

<x:set var="empName" select="$doc/employees/employee[2]/name"/>


Second Employee Name: ${empName}

<hr>

<!-- ==================== 5. x:choose ==================== -->


<h3>5. x:choose</h3>

<x:choose>
<x:when select="$doc/employees/employee[2]/department='Testing'">
Second employee is from Testing department.
</x:when>
<x:otherwise>
Department not found.
</x:otherwise>
</x:choose>

</body>
</html>

[Link]([Link])
package customtags;

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

public class GreetTag extends SimpleTagSupport {

private String name;

public void setName(String name) {


[Link] = name;
}

@Override
public void doTag() throws JspException, IOException {
getJspContext().getOut().write(
"Hello, " + name + "! Welcome to Custom Tags Demo."
);
}
}

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1"
xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<tlib-version>1.0</tlib-version>
<short-name>custom</short-name>
<uri>/WEB-INF/[Link]</uri>

<tag>
<name>greet</name>
<tag-class>[Link]</tag-class>
<body-content>empty</body-content>

<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>

</taglib>

jstl_custom.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="/WEB-INF/[Link]" prefix="my" %>

<html>
<head>
<title>Custom Tag Demonstration</title>
</head>
<body>

<h2>Custom Tag Demonstration</h2>

<h3>1. Using Custom Tag</h3>

<my:greet name="Jhansi" />

</body>
</html>
Run(jsp)

[Link] tag elements:


Filename:[Link]

<%-- Page Directive --%>


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

<%-- Page Directive --%>


<%@ page import="[Link]" %>

<%-- Page Directive --%>


<%@ page import="[Link].*" %>

<%-- Declaration Tag --%>


<%!
String welcomeMessage = "Welcome to JSP Tag Elements Demo!";

public int calculateSquare(int n) {


return n * n;
}
%>

<html>
<head>
<title>JSP Tag Elements Demo</title>
<style>
body {
font-family: Arial, sans-serif;
font-size: 13px;
margin: 20px;
}
.box {
width: 380px;
}
.label {
font-weight: bold;
}
</style>
</head>
<body>

<div class="box">

<!-- Expression Tag -->


<span class="label">[Expression Tag]</span><br>
Date: <%= new Date() %><br>
Welcome Message: <%= welcomeMessage %><br><br>
<form method="post">
Name: <input type="text" name="username" required />
<input type="submit" value="Submit" />
</form>

<%-- Scriptlet Tag --%>


<%
String username = [Link]("username");
String message = "";
int nameLength = 0;

if(username != null && ![Link]().isEmpty()){

nameLength = [Link]();

try{
[Link]("[Link]");

Connection conn = [Link](


"jdbc:oracle:thin:@localhost:1521/orclpdb",
"jdbcuser",
"jdbc123"
);

PreparedStatement ps = [Link](
"INSERT INTO tag_demo_users(username, created_date) VALUES(?,
SYSDATE)"
);

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

message = "Stored successfully.";

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

} catch(Exception e){
message = "Error: " + [Link]();
}
%>
<br>

<!-- Expression Tag -->


<span class="label">[Scriptlet + Expression Tag]</span><br>
Hello: <%= username %><br>
Length: <%= nameLength %><br>

<br>

<!-- Expression Tag -->


<span class="label">[Declaration Method via Expression]</span><br>
Square of 5: <%= calculateSquare(5) %><br>

<br>

<!-- Expression Tag -->


<span class="label">[Database Status]</span><br>
Status: <%= message %><br><br>

<!-- Action Tag -->


<span class="label">[Action Tag]</span><br>
<jsp:include page="[Link]" />

<%
} // End of Scriptlet Tag
%>

</div>

</body>
</html>

[Link]
<html>
<body>
<p>Footer included using Action Tag (jsp:include)</p>
</body>
</html>
Run(program16)
Sql: select*from tag_demo_users;

You might also like