Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

practical file list question

Uploaded by

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

practical file list question

Uploaded by

Sudha Kore
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

1.

Basic JSP Program: Displaying "Hello World"


Explanation:
 The page directive is used to define the page’s language and content type.
 The h1 tag in the body displays "Hello, World!" on the page.
2. JSP Program: Displaying Current Date and Time
Explanation:
 The import directive imports the java.util.Date class.
 <%= new Date() %> is a scriptlet expression that outputs the current date and
time to the page.
3. Handling Form Data: This program accepts user input (name) through a form and
displays the name back to the user.
Explanation:
 form.jsp: A simple HTML form that sends a POST request to display.jsp with the
user input.
 display.jsp: This page retrieves the input value (name) using
request.getParameter("username") and displays it.
4. JSP Program: Performing Arithmetic Operations: This program accepts two
numbers from the user and performs addition.
Explanation:
 calculator.jsp: Takes two numbers as input from the user.
 result.jsp: Receives the input, converts the string values into integers, and
performs the addition. The result is displayed back to the user.
5. JSP Program: Using Sessions: This program demonstrates how to create a
session and store the username in it.
Explanation:
 login.jsp: Takes the username from the user.
 welcome.jsp: Stores the username in the session and displays it.
 logout.jsp: Invalidates the session (logs the user out).
Key Concepts in JSP:
1. Scriptlets (<% %>): Used for embedding Java code in the JSP.
2. Expressions (<%= %>): Output values directly into the HTML response.
3. Directives (<%@ %>): Used to specify page-related settings like importing Java
classes or setting the content type.
6. JSP Program: Using JavaBeans for Data Encapsulation: This program
demonstrates how to use JavaBeans to encapsulate user data and interact with JSP.
Step 1: Create the JavaBean (UserBean.java)
java
Copy code
public class UserBean {
private String name;
private String email;

// Getter and Setter methods


public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}
}
Step 2: Create the JSP Page to Use JavaBeans (userForm.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:useBean id="user" class="UserBean" scope="request" />
<jsp:setProperty name="user" property="*" />

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Information</title>
</head>
<body>
<h1>User Form</h1>
<form action="displayUser.jsp" method="post">
Name: <input type="text" name="name" /><br/>
Email: <input type="text" name="email" /><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Step 3: Display the Data from JavaBean (displayUser.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:useBean id="user" class="UserBean" scope="request" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Information Display</title>
</head>
<body>
<h1>User Information</h1>
<p>Name: <jsp:getProperty name="user" property="name" /></p>
<p>Email: <jsp:getProperty name="user" property="email" /></p>
</body>
</html>
Explanation:
 JavaBean (UserBean.java): A simple Java class with getter and setter methods
for name and email.
 jsp
: This tag is used to create or reference a JavaBean instance.
 jsp
: This tag sets the properties of the JavaBean based on the form inputs.
 jsp
: This tag retrieves the values from the JavaBean and displays them.
7. JSP Program: Using JSTL (JSP Standard Tag Library)
The JSTL allows us to avoid writing Java code in JSP. This program demonstrates how
to use JSTL for looping and condition checking.
Step 1: Add JSTL Dependency
Make sure to include the JSTL library in your project, which is usually available via
Maven or as a .jar file.
Step 2: Display Numbers from 1 to 10 Using JSTL (numbers.jsp)
jsp
Copy code
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSTL Example</title>
</head>
<body>
<h1>Numbers from 1 to 10</h1>
<ul>
<c:forEach var="i" begin="1" end="10">
<li>${i}</li>
</c:forEach>
</ul>
</body>
</html>
Explanation:
 taglib directive: Imports the JSTL core library.
 c
: This tag iterates from 1 to 10 and displays each number in a list (<li>).
8. JSP Program: Connecting to a Database (JDBC Example)
This program demonstrates how to connect to a MySQL database and retrieve data
using JDBC.
Step 1: Create Database Table
Run the following SQL commands to create a table and insert data:
sql
Copy code
CREATE DATABASE mydatabase;
USE mydatabase;

CREATE TABLE users (


id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
email VARCHAR(50)
);

INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');


INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');
Step 2: JSP Page to Connect and Retrieve Data (retrieveData.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.Connection, java.sql.DriverManager, java.sql.ResultSet,
java.sql.Statement" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Example</title>
</head>
<body>
<h1>Users List</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Step 1: Load JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish a connection


conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root",
"password");

// Step 3: Create a statement and execute the query


stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM users");

// Step 4: Process the result set


while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
%>
<tr>
<td><%= id %></td>
<td><%= name %></td>
<td><%= email %></td>
</tr>
<%
}
} catch (Exception e) {
out.println("Error: " + e.getMessage());
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
</table>
</body>
</html>
Explanation:
 DriverManager: Used to establish a connection to the MySQL database.
 Statement and ResultSet: Used to execute SQL queries and process the result
set.
 rs.next(): Loops through the result set to display each user's information in an
HTML table.
9. JSP Program: Session Tracking with Cookies
This program demonstrates how to track user sessions using cookies.
Step 1: Login Form (login.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="welcome.jsp" method="post">
Username: <input type="text" name="username" />
<input type="submit" value="Login" />
</form>
</body>
</html>
Step 2: Welcome Page (welcome.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String username = request.getParameter("username");

if (username != null) {
Cookie userCookie = new Cookie("username", username);
userCookie.setMaxAge(60*60); // Set cookie to expire in 1 hour
response.addCookie(userCookie);
} else {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
username = cookie.getValue();
}
}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <%= username %>!</h1>
</body>
</html>
Explanation:
 Cookies: response.addCookie() adds the username as a cookie, and
request.getCookies() retrieves it on subsequent requests.
 setMaxAge: This sets the cookie's lifespan (1 hour in this case).
10. JSP Program: Redirecting to Another Page
This example demonstrates how to redirect a user to another page in JSP.
JSP Code (redirect.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String destination = "welcome.jsp";
response.sendRedirect(destination); // Redirects to welcome.jsp
%>
Explanation:
 sendRedirect(): This method sends an HTTP response to redirect the browser
to another URL.

These JSP examples cover common use cases such as form handling, database
connection,
4o
You said:
more real life program example
ChatGPT said:
ChatGPT
Here are more real-life JSP examples that demonstrate various practical
functionalities, including user authentication, file upload, form validation, and displaying
data in a paginated manner.
1. JSP Program: User Authentication System
This program demonstrates a simple user authentication system where a user logs in
with a username and password, and their credentials are validated against a database.
Step 1: Create a Database Table for Users
sql
Copy code
CREATE DATABASE mydatabase;
USE mydatabase;

CREATE TABLE users (


id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE,
password VARCHAR(50)
);

INSERT INTO users (username, password) VALUES ('john', 'password123');


INSERT INTO users (username, password) VALUES ('jane', 'mypassword');
Step 2: Create the Login Form (login.jsp)
jsp
Copy code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>User Login</h1>
<form action="loginAction.jsp" method="post">
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password" /><br/>
<input type="submit" value="Login" />
</form>
</body>
</html>
Step 3: Validate the Login (loginAction.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
boolean isValidUser = false;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root",
"password");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users
WHERE username=? AND password=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();

if (rs.next()) {
isValidUser = true;
}
rs.close();
ps.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}

if (isValidUser) {
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp?error=Invalid credentials");
}
%>
Step 4: Welcome Page After Successful Login (welcome.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String username = (String) session.getAttribute("username");
if (username == null) {
response.sendRedirect("login.jsp");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h1>Welcome, <%= username %>!</h1>
<a href="logout.jsp">Logout</a>
</body>
</html>
Step 5: Logout Page (logout.jsp)
jsp
Copy code
<%
session.invalidate();
response.sendRedirect("login.jsp");
%>
Explanation:
 Database validation: User credentials are validated against the users table in
MySQL.
 Session management: On successful login, the username is stored in the
session. The user is redirected to the welcome page, and session invalidation
occurs during logout.

2. JSP Program: File Upload


This program demonstrates how to upload a file using JSP and store it on the server.
Step 1: Add FileUpload Library (Apache Commons FileUpload)
Make sure to add the commons-fileupload and commons-io libraries to your project.
Step 2: Create the File Upload Form (uploadForm.jsp)
jsp
Copy code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="fileUploadAction.jsp" method="post" enctype="multipart/form-data">
Select file: <input type="file" name="file" /><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
Step 3: Handle the File Upload (fileUploadAction.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*, org.apache.commons.fileupload.*,
org.apache.commons.fileupload.disk.*, org.apache.commons.fileupload.servlet.*" %>
<%@ page import="java.util.*, javax.servlet.*" %>

<%
String uploadPath = application.getRealPath("") + File.separator + "uploads";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}

boolean isMultipart = ServletFileUpload.isMultipartContent(request);


if (isMultipart) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
out.println("File uploaded successfully: " + fileName);
}
}
}
} catch (Exception ex) {
out.println("File upload failed: " + ex.getMessage());
}
}
%>
Explanation:
 Multipart form: The form in uploadForm.jsp is set to enctype="multipart/form-
data" to enable file uploading.
 File handling: The commons-fileupload library handles the file upload. The file is
stored in a directory on the server.

3. JSP Program: Form Validation with JavaScript and JSP


This program demonstrates how to validate a form on the client side using JavaScript
and on the server side using JSP.
Step 1: Form with Client-Side Validation (registration.jsp)
jsp
Copy code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Registration</title>
<script>
function validateForm() {
var username = document.forms["registrationForm"]["username"].value;
var email = document.forms["registrationForm"]["email"].value;
if (username == "" || email == "") {
alert("Username and Email must be filled out");
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Registration Form</h1>
<form name="registrationForm" action="registerAction.jsp" method="post"
onsubmit="return validateForm()">
Username: <input type="text" name="username" /><br/>
Email: <input type="text" name="email" /><br/>
<input type="submit" value="Register" />
</form>
</body>
</html>
Step 2: Server-Side Validation (registerAction.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String username = request.getParameter("username");
String email = request.getParameter("email");

if (username == null || username.isEmpty() || email == null || email.isEmpty()) {


out.println("Both fields are required!");
} else {
out.println("Registration successful!<br>");
out.println("Username: " + username + "<br>");
out.println("Email: " + email);
}
%>
Explanation:
 Client-side validation: JavaScript ensures that both the username and email
fields are filled before submission.
 Server-side validation: JSP checks if the fields are empty on the server side as
an extra layer of validation.

4. JSP Program: Display Data with Pagination


This program demonstrates how to display data from a database with pagination using
JSP.
Step 1: Create the Database Table
sql
Copy code
CREATE TABLE products (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
price DECIMAL(10, 2)
);

INSERT INTO products (name, price) VALUES ('Product 1', 10.00);


INSERT INTO products (name, price) VALUES ('Product 2', 15.00);
-- Add more products...
Step 2: Display Products with Pagination (products.jsp)
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*, java.util.*" %>
<%
int page = 1;
int recordsPerPage = 5;
if (request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));

int start = (page - 1) * recordsPerPage;

List<String> products

You might also like