0% found this document useful (0 votes)
19 views53 pages

Java

The document provides a series of Java RMI (Remote Method Invocation) examples, including passing objects, implementing a distributed calculator, a chat application, file sharing, secure communication using SSL, and load balancing. Each section contains code snippets for server and client implementations, demonstrating how to create and use remote objects and services. Additionally, it covers servlet creation, handling HTTP requests, using ServletConfig and ServletContext, and managing sessions.

Uploaded by

deskcode7
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)
19 views53 pages

Java

The document provides a series of Java RMI (Remote Method Invocation) examples, including passing objects, implementing a distributed calculator, a chat application, file sharing, secure communication using SSL, and load balancing. Each section contains code snippets for server and client implementations, demonstrating how to create and use remote objects and services. Additionally, it covers servlet creation, handling HTTP requests, using ServletConfig and ServletContext, and managing sessions.

Uploaded by

deskcode7
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

26.

Passing Objects in RMI

1. [Link] (Serializable Object)


import [Link];
public class Student implements Serializable {
private String name;
private int roll;
public Student(String name, int roll) {
[Link] = name;
[Link] = roll;
}
public String getName() {
return name;
}
public int getRoll() {
return roll;
}
}

2. [Link] (Remote Interface)


import [Link];
import [Link];
public interface StudentService extends Remote {
String displayStudent(Student student) throws RemoteException;
}

3. [Link] (Remote Object Implementation)


import [Link];
import [Link];
public class StudentServiceImpl extends UnicastRemoteObject implements
StudentService {
protected StudentServiceImpl() throws RemoteException {
super();
}
public String displayStudent(Student student) throws RemoteException {
return "Student Name: " + [Link]() + ", Roll No: " +
[Link]();
}
}

4. [Link]
import [Link];

public class Server {


public static void main(String[] args) {
try {
StudentService service = new StudentServiceImpl();
[Link]("rmi://localhost:5000/student", service);
[Link]("Server is running...");
} catch (Exception e) {
[Link]();
}
}
}

5. [Link]
import [Link];

public class Client {


public static void main(String[] args) {
try {
StudentService service = (StudentService)
[Link]("rmi://localhost:5000/student");
Student student = new Student("Alice", 101);
String response = [Link](student);
[Link]("Response from server: " + response);
} catch (Exception e) {
[Link]();
}
}
}
Output:

Response from server: Student Name: Alice, Roll No: 101

27. Distributed Calculator using RMI

[Link] – Remote Interface


import [Link].*;

public interface Calculator extends Remote {


int add(int a, int b) throws RemoteException;
int subtract(int a, int b) throws RemoteException;
int multiply(int a, int b) throws RemoteException;
double divide(int a, int b) throws RemoteException;
}
[Link]
import [Link];
import [Link];

public class CalculatorImpl extends UnicastRemoteObject implements Calculator


{
protected CalculatorImpl() throws RemoteException {
super();
}

public int add(int a, int b) { return a + b; }


public int subtract(int a, int b) { return a - b; }
public int multiply(int a, int b) { return a * b; }
public double divide(int a, int b) { return (double)a / b; }
}

[Link]
import [Link];

public class Server {


public static void main(String[] args) {
try {
Calculator calc = new CalculatorImpl();
[Link]("rmi://localhost:1099/CalculatorService", calc);
[Link]("Calculator RMI Server is running...");
} catch (Exception e) {
[Link]();
}
}
}

[Link]
import [Link];

public class Client {


public static void main(String[] args) {
try {
Calculator calc = (Calculator)
[Link]("rmi://localhost:1099/CalculatorService");
[Link]("Add: " + [Link](10, 5));
[Link]("Subtract: " + [Link](10, 5));
[Link]("Multiply: " + [Link](10, 5));
[Link]("Divide: " + [Link](10, 5));
} catch (Exception e) {
[Link]();
}
}
}

Output

Calculator RMI Server is running...

Add: 15
Subtract: 5
Multiply: 50
Divide: 2.0

28. RMI-based Chat Application

[Link] – Remote Interface


import [Link].*;

public interface ChatInterface extends Remote {


void sendMessage(String msg) throws RemoteException;
String receiveMessage() throws RemoteException;
}
[Link] – Remote Object
import [Link];
import [Link];

public class ChatImpl extends UnicastRemoteObject implements ChatInterface {


private String message = "No new messages";

protected ChatImpl() throws RemoteException {


super();
}

public void sendMessage(String msg) throws RemoteException {


[Link] = msg;
}

public String receiveMessage() throws RemoteException {


return message;
}
}
[Link]
import [Link];

public class Server {


public static void main(String[] args) {
try {
ChatInterface chat = new ChatImpl();
[Link]("rmi://localhost:1099/ChatService", chat);
[Link]("Chat Server is running...");
} catch (Exception e) {
[Link]();
}
}
}
[Link] – Sending a Message
import [Link];

public class Client1 {


public static void main(String[] args) {
try {
ChatInterface chat = (ChatInterface)
[Link]("rmi://localhost:1099/ChatService");
[Link]("Hello from Client 1!");
[Link]("Message sent from Client 1.");
} catch (Exception e) {
[Link]();
}
}
}
[Link] – Receiving the Message
import [Link];

public class Client2 {


public static void main(String[] args) {
try {
ChatInterface chat = (ChatInterface)
[Link]("rmi://localhost:1099/ChatService");
String msg = [Link]();
[Link]("Client 2 received: " + msg);
} catch (Exception e) {
[Link]();
}
}
}

Output

Client1
Message sent from Client 1.
Client2
Client 2 received: Hello from Client 1!

29. File Sharing System using RMI

[Link] – Remote Interface


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

public interface FileService extends Remote {


byte[] downloadFile(String fileName) throws RemoteException;
}
[Link] – Remote Object
import [Link];
import [Link];
import [Link].*;

public class FileServiceImpl extends UnicastRemoteObject implements


FileService {
protected FileServiceImpl() throws RemoteException {
super();
}

public byte[] downloadFile(String fileName) throws RemoteException {


try {
File file = new File(fileName);
byte[] fileData = new byte[(int) [Link]()];
FileInputStream fis = new FileInputStream(file);
[Link](fileData);
[Link]();
return fileData;
} catch (IOException e) {
[Link]();
return null;
}
}
}
[Link]
import [Link];

public class Server {


public static void main(String[] args) {
try {
FileService fs = new FileServiceImpl();
[Link]("rmi://localhost:1099/FileService", fs);
[Link]("File Server is running...");
} catch (Exception e) {
[Link]();
}
}
}
[Link]
import [Link];
import [Link].*;

public class Client {


public static void main(String[] args) {
try {
FileService fs = (FileService)
[Link]("rmi://localhost:1099/FileService");
byte[] fileData = [Link]("[Link]");

FileOutputStream fos = new FileOutputStream("client_download.txt");


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

[Link]("File downloaded as client_download.txt");


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

Output

Server Console
File Server is running...
Client Console
File downloaded as client_download.txt

30. Secure Communication in RMI using SSL

🔐 Prerequisites:
1. Generate keystore: keytool -genkeypair -alias serverkey -keyalg RSA -
keystore [Link] -storepass password

1. [Link] – Remote Interface


import [Link];
import [Link];

public interface SecureService extends Remote {


String secureHello(String name) throws RemoteException;
}
2. [Link]
import [Link];
import [Link];

public class SecureServiceImpl extends UnicastRemoteObject implements


SecureService {
protected SecureServiceImpl() throws RemoteException {
super();
}

public String secureHello(String name) throws RemoteException {


return "Secure Hello, " + name;
}
}
3. [Link]
import [Link];
import [Link];
import [Link];
import [Link];

public class SSLServer {


public static void main(String[] args) {
try {
[Link]("[Link]", "[Link]");
[Link]("[Link]", "password");

SecureService service = new SecureServiceImpl();

[Link](1099,
new SslRMIClientSocketFactory(),
new SslRMIServerSocketFactory());

[Link]("rmi://localhost:1099/SecureService", service);
[Link]("Secure RMI Server is running...");
} catch (Exception e) {
[Link]();
}
}
}
4. [Link]
import [Link];
import [Link];

public class SSLClient {


public static void main(String[] args) {
try {
[Link]("[Link]", "[Link]");
[Link]("[Link]", "password");
SecureService service = (SecureService)
[Link]("rmi://localhost:1099/SecureService");
String response = [Link]("Alice");
[Link]("Response: " + response);
} catch (Exception e) {
[Link]();
}
}
}
Output

Server Console
Secure RMI Server is running...
Client Console
Response: Secure Hello, Alice

31. Implementing Load Balancing with RMI

1. [Link] – Remote Interface


import [Link].*;

public interface LoadService extends Remote {


int getLoad() throws RemoteException;
String processRequest(String clientName) throws RemoteException;
}

2. [Link] – Remote Object


import [Link];
import [Link];

public class LoadServiceImpl extends UnicastRemoteObject implements


LoadService {
private int load;
protected LoadServiceImpl(int initialLoad) throws RemoteException {
super();
[Link] = initialLoad;
}

public int getLoad() throws RemoteException {


return load;
}

public String processRequest(String clientName) throws RemoteException {


load++;
return "Processed by Server with current load " + load + " for " +
clientName;
}
}

3. [Link]
import [Link];

public class Server1 {


public static void main(String[] args) {
try {
LoadService service = new LoadServiceImpl(2);
[Link]("rmi://localhost:1099/Server1", service);
[Link]("Server1 is running...");
} catch (Exception e) {
[Link]();
}
}
}
4. [Link]
import [Link];

public class Server2 {


public static void main(String[] args) {
try {
LoadService service = new LoadServiceImpl(5);
[Link]("rmi://localhost:1100/Server2", service);
[Link]("Server2 is running...");
} catch (Exception e) {
[Link]();
}
}
}

5. [Link]
import [Link];

public class Client {


public static void main(String[] args) {
try {
LoadService server1 = (LoadService)
[Link]("rmi://localhost:1099/Server1");
LoadService server2 = (LoadService)
[Link]("rmi://localhost:1100/Server2");

LoadService selected = ([Link]() < [Link]()) ?


server1 : server2;

String response = [Link]("Client A");


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

Output

Server1 Console
Server1 is running...
Server2 Console
Server2 is running...
Client Console
Processed by Server with current load 3 for Client A

32. Introduction to Servlets - Creating a Simple Servlet

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

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<h1>Hello from Servlet</h1>");
}
}

2. [Link] (Web Deployment Descriptor)


<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

Output
Open in browser:
[Link]
Output:

Hello from Servlet

33. Handling HTTP Requests and Responses in Servlets

1. [Link]
java
CopyEdit
import [Link].*;
import [Link].*;
import [Link].*;

public class RequestResponseServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

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

[Link]("<h2>Hello, " + name + "!</h2>");


}
}

2. [Link] (placed in WebContent folder)


html
CopyEdit
<!DOCTYPE html>
<html>
<head><title>Request Form</title></head>
<body>
<form method="post" action="handle">
Enter your name: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
</body>
</html>

3. [Link]
<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>handler</servlet-name>
<servlet-class>RequestResponseServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>handler</servlet-name>
<url-pattern>/handle</url-pattern>
</servlet-mapping>
</web-app>

Output :
User enters: John
After form submission:

Hello, John!
34. Using ServletConfig and ServletContext

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

public class ConfigContextServlet extends HttpServlet {

public void init(ServletConfig config) throws ServletException {


[Link](config);
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


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

// ServletConfig parameter
ServletConfig config = getServletConfig();
String adminEmail = [Link]("adminEmail");

// ServletContext parameter
ServletContext context = getServletContext();
String companyName = [Link]("company");

[Link]("<h2>Admin Email: " + adminEmail + "</h2>");


[Link]("<h2>Company Name: " + companyName + "</h2>");
}
}
2. [Link]
<web-app xmlns="[Link] version="3.0">

<context-param>
<param-name>company</param-name>
<param-value>OpenAI Solutions</param-value>
</context-param>

<servlet>
<servlet-name>configContext</servlet-name>
<servlet-class>ConfigContextServlet</servlet-class>
<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@[Link]</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>configContext</servlet-name>
<url-pattern>/config</url-pattern>
</servlet-mapping>

</web-app>

Output
Access: [Link]

Admin Email: admin@[Link]


Company Name: OpenAI Solutions

35. Managing Sessions in Servlets

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

public class SessionServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

// Retrieve session object


HttpSession session = [Link](true);
String name = (String) [Link]("username");

if (name == null) {
name = "Guest";
}

[Link]("<h2>Welcome, " + name + "!</h2>");

// Set session attribute


[Link]("username", "JohnDoe");
}
}

2. [Link]
<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>session</servlet-name>
<servlet-class>SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>session</servlet-name>
<url-pattern>/session</url-pattern>
</servlet-mapping>
</web-app>

✅ Output
Access: [Link]
First request (no session):

Welcome, Guest!

After session is created:

Welcome, JohnDoe!

36. Implementing Servlet Chaining

1. [Link] (Initial servlet in the chain)


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

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Add attribute to the request
[Link]("message", "Hello from First Servlet");

// Forward the request to the next servlet in the chain


RequestDispatcher dispatcher = [Link]("/second");
[Link](request, response);
}
}

2. [Link] (Next servlet in the chain)


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

public class SecondServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

// Retrieve the attribute from the request


String message = (String) [Link]("message");
[Link]("<h2>" + message + " and Second Servlet processing
request.</h2>");
}
}

3. [Link]
<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>firstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>secondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>firstServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>secondServlet</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
</web-app>

Output
Access: [Link]

Hello from First Servlet and Second Servlet processing request.

37. Using Cookies for Session Tracking

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

public class CookieServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

// Check if the "username" cookie exists


Cookie[] cookies = [Link]();
String userName = "Guest";

if (cookies != null) {
for (Cookie cookie : cookies) {
if ([Link]().equals("username")) {
userName = [Link]();
break;
}
}
}

[Link]("<h2>Welcome, " + userName + "!</h2>");

// Create a new cookie and send it to the client


Cookie cookie = new Cookie("username", "JohnDoe");
[Link](60 * 60); // 1 hour
[Link](cookie);
}
}

2. [Link]
<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>cookieServlet</servlet-name>
<servlet-class>CookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cookieServlet</servlet-name>
<url-pattern>/cookie</url-pattern>
</servlet-mapping>
</web-app>

Output
Access: [Link]
First visit (no cookie):

Welcome, Guest!

Subsequent visits (cookie stored):

Welcome, JohnDoe!

38. Connecting Servlets with Databases


1. [Link] – Helper Class to Establish DB Connection
import [Link].*;

public class DatabaseConnection {


public static Connection getConnection() {
try {
// Load the database driver (MySQL in this case)
[Link]("[Link]");

// Return connection object


return [Link](
"jdbc:mysql://localhost:3306/yourDatabase", "root", "password");
} catch (Exception e) {
[Link]();
return null;
}
}
}
2. [Link] – Servlet to Fetch Data from Database
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class UserServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

try {
Connection conn = [Link]();
String query = "SELECT username, email FROM users";
Statement stmt = [Link]();
ResultSet rs = [Link](query);

[Link]("<table border='1'>");
[Link]("<tr><th>Username</th><th>Email</th></tr>");

while ([Link]()) {
[Link]("<tr><td>" + [Link]("username") + "</td>");
[Link]("<td>" + [Link]("email") + "</td></tr>");
}
[Link]("</table>");

[Link]();
} catch (SQLException e) {
[Link]();
[Link]("<h3>Error: " + [Link]() + "</h3>");
}
}
}

3. [Link]
<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>userServlet</servlet-name>
<servlet-class>UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>userServlet</servlet-name>
<url-pattern>/user</url-pattern>
</servlet-mapping>
</web-app>
Output
Access: [Link]
Assuming the users table in the database has data:

| Username | Email |
|----------|-----------------|
| john | john@[Link]|
| alice | alice@[Link]|

39. Uploading Files using Servlets

1. Add Required Dependencies (in [Link])


You need to include the Apache Commons FileUpload library to handle file
uploads.
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>

2. [Link] – Servlet for File Upload


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

public class FileUploadServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

// Check if the request is a file upload


boolean isMultipart = [Link](request);
if (!isMultipart) {
[Link]("<h3>Request is not multipart, please try again.</h3>");
return;
}

// Create a factory for disk-based file items


DiskFileItemFactory factory = new DiskFileItemFactory();

// Create a new file upload handler


ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
[Link]<FileItem> items = [Link](request);
for (FileItem item : items) {
if (![Link]()) {
// Process the uploaded file
String fileName = [Link]();
String filePath = "uploads/" + fileName;

// Save the file on the server


File uploadedFile = new File(filePath);
[Link](uploadedFile);

[Link]("<h3>File uploaded successfully: " + fileName +


"</h3>");
}
}
} catch (Exception e) {
[Link]("<h3>Error uploading file: " + [Link]() + "</h3>");
}
}
}

3. [Link]
<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>fileUpload</servlet-name>
<servlet-class>FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUpload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
</web-app>

4. [Link] – HTML Form for File Upload


<!DOCTYPE html>
<html>
<head><title>File Upload</title></head>
<body>
<h1>Upload a File</h1>
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>

Output
Access the upload form: [Link]
Upon file selection and submission, the server will save the uploaded file in
the "uploads" directory.
For successful upload:

File uploaded successfully: [filename]

40. Creating a Login System using Servlets

1. [Link] – Servlet for Handling Login


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

public class LoginServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

// Retrieve user input from the login form


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

// Simple validation (hardcoded credentials)


if ("admin".equals(username) && "password123".equals(password)) {
[Link]("<h2>Login Successful!</h2>");
} else {
[Link]("<h2>Invalid username or password. Please try
again.</h2>");
}
}
}
2. [Link] – HTML Form for Login
<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
<h1>Login Page</h1>
<form method="post" action="login">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>

3. [Link]
<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

Output
Access the login form: [Link]
Valid credentials:
Username: admin, Password: password123
Output:

Login Successful!
Invalid credentials:
Output:

Invalid username or password. Please try again.

41. Implementing Filters in Servlets

1. [Link] – A Filter for Logging Request Information


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

public class LoggingFilter implements Filter {


public void init(FilterConfig filterConfig) throws ServletException {
// Initialization logic (optional)
}

public void doFilter(ServletRequest request, ServletResponse response,


FilterChain chain) throws IOException, ServletException {
// Log incoming request information
HttpServletRequest httpRequest = (HttpServletRequest) request;
[Link]("Request received for: " + [Link]());

// Continue the request-response chain


[Link](request, response);
}

public void destroy() {


// Cleanup resources (optional)
}
}

2. [Link] – Configuring the Filter in [Link]


<web-app xmlns="[Link] version="3.0">
<filter>
<filter-name>loggingFilter</filter-name>
<filter-class>LoggingFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>loggingFilter</filter-name>
<url-pattern>/login</url-pattern>
</filter-mapping>

<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>

Output
When a request is made to [Link] the filter logs the
request information.
Example log:

Request received for: /YourApp/login

42. Introduction to JSP - Creating a Simple JSP Page

1. [Link] – Simple JSP Page


<!DOCTYPE html>
<html>
<head><title>Simple JSP Page</title></head>
<body>
<h1>Hello, World!</h1>
<p>This is a simple JSP page.</p>
</body>
</html>

2. [Link]
<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>helloJSP</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>jsp-file</param-name>
<param-value>/[Link]</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>helloJSP</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

Output
Access the JSP page at [Link]

Hello, World!
This is a simple JSP page.

43. JSP Implicit Objects and Their Uses

1. [Link] – JSP Using Implicit Objects


<%@ page import="[Link].*" %>
<!DOCTYPE html>
<html>
<head><title>JSP Implicit Objects</title></head>
<body>
<h1>Using JSP Implicit Objects</h1>

<h2>Request Information:</h2>
<p>Request Method: <%= [Link]() %></p>
<p>Request URI: <%= [Link]() %></p>

<h2>Session Information:</h2>
<%
HttpSession session = [Link](true);
String sessionID = [Link]();
%>
<p>Session ID: <%= sessionID %></p>

<h2>Current Date and Time:</h2>


<p>Current Date and Time: <%= new Date() %></p>
</body>
</html>

Output
Access the JSP page at [Link]
The page will display:

Using JSP Implicit Objects

Request Information:
Request Method: GET
Request URI: /YourApp/implicit

Session Information:
Session ID: 12345678ABCD1234

Current Date and Time:


Current Date and Time: Tue May 01 [Link] GMT 2025

44. Using JSP Directives and Declarations

1. directive_declaration.jsp – Using Directives and Declarations


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ import="[Link].*" %>

<!DOCTYPE html>
<html>
<head><title>JSP Directives and Declarations</title></head>
<body>
<h1>Using JSP Directives and Declarations</h1>

<%
// Declare a method in the declaration section
public String getGreetingMessage() {
return "Hello, welcome to JSP!";
}
%>

<h2>Greeting Message:</h2>
<p><%= getGreetingMessage() %></p>

<h2>Current Date and Time:</h2>


<p><%= new Date() %></p>
</body>
</html>
Output
Access the JSP page at [Link]
The page will display:

Using JSP Directives and Declarations

Greeting Message:
Hello, welcome to JSP!

Current Date and Time:


Tue May 01 [Link] GMT 2025

45. Handling Forms in JSP

1. [Link] – HTML Form for User Input


<!DOCTYPE html>
<html>
<head><title>Form Handling in JSP</title></head>
<body>
<h1>Enter Your Name</h1>
<form action="greet" method="post">
<label for="name">Name: </label>
<input type="text" name="name" id="name" required />
<input type="submit" value="Submit" />
</form>
</body>
</html>

2. [Link] – JSP Page to Display Greeting


<%@ page contentType="text/html; charset=ISO-8859-1" %>
<!DOCTYPE html>
<html>
<head><title>Greeting Page</title></head>
<body>
<h1>Greeting</h1>

<%
String name = [Link]("name");
if (name != null && ![Link]().isEmpty()) {
[Link]("<h2>Hello, " + name + "!</h2>");
} else {
[Link]("<h2>Name not provided!</h2>");
}
%>
</body>
</html>

3. [Link]
<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>greetServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>jsp-file</param-name>
<param-value>/[Link]</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>greetServlet</servlet-name>
<url-pattern>/greet</url-pattern>
</servlet-mapping>
</web-app>

Output
Access the form: [Link]
If you submit the form with the name "John":

Hello, John!

If no name is provided:

Name not provided!

46. JSP with Database Connectivity

1. [Link] – Helper Class to Connect to the Database


import [Link].*;

public class DatabaseConnection {


public static Connection getConnection() {
try {
// Load database driver (MySQL in this case)
[Link]("[Link]");

// Return connection object


return [Link](
"jdbc:mysql://localhost:3306/yourDatabase", "root", "password");
} catch (Exception e) {
[Link]();
return null;
}
}
}

2. [Link] – JSP Page to Retrieve and Display Data


<%@ page import="[Link].*" %>
<%@ page import="[Link].*" %>
<!DOCTYPE html>
<html>
<head><title>Data from Database</title></head>
<body>
<h1>Database Records</h1>

<%
// Get a connection to the database
Connection conn = [Link]();
if (conn != null) {
// SQL query to fetch data from 'users' table
String query = "SELECT username, email FROM users";
Statement stmt = [Link]();
ResultSet rs = [Link](query);

[Link]("<table border='1'>");
[Link]("<tr><th>Username</th><th>Email</th></tr>");
while ([Link]()) {
[Link]("<tr><td>" + [Link]("username") + "</td>");
[Link]("<td>" + [Link]("email") + "</td></tr>");
}
[Link]("</table>");

// Close the connection


[Link]();
} else {
[Link]("<h3>Failed to connect to the database</h3>");
}
%>
</body>
</html>

Output
Access the JSP page at [Link]
If the users table contains data like:
| username | email |
|----------|--------------------|
| john | john@[Link] |
| alice | alice@[Link] |

The page will display:

Database Records

| Username | Email |
|----------|--------------------|
| john | john@[Link] |
| alice | alice@[Link] |

47. Implementing JSP Custom Tags

1. [Link] – Java Class for the Custom Tag


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

public class GreetingTag extends SimpleTagSupport {


private String name;

public void setName(String name) {


[Link] = name;
}

@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
if (name != null && ![Link]()) {
[Link]("Hello, " + name + "!");
} else {
[Link]("Hello, Guest!");
}
}
}

2. [Link] – Tag Library Descriptor (TLD) File


<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="[Link] version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>greeting</short-name>
<uri>/WEB-INF/tlds/greeting-tag</uri>
<tag>
<name>greeting</name>
<tag-class>GreetingTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
</tag>
</taglib>

3. [Link] – Register the TLD File


<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>JSPServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>JSPServlet</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>

<taglib>
<taglib-uri>/WEB-INF/tlds/greeting-tag</taglib-uri>
<taglib-location>/WEB-INF/tlds/[Link]</taglib-location>
</taglib>
</web-app>

4. [Link] – JSP Page Using the Custom Tag


<%@ taglib uri="/WEB-INF/tlds/greeting-tag" prefix="gt" %>
<!DOCTYPE html>
<html>
<head><title>Custom Tag Example</title></head>
<body>
<h1>Custom Tag Example</h1>

<!-- Using the custom greeting tag -->


<gt:greeting name="John"/>
<gt:greeting name="Alice"/>
<gt:greeting />
</body>
</html>

Output
Access the JSP page at [Link]
The page will display:

Custom Tag Example

Hello, John!
Hello, Alice!
Hello, Guest!
48. Using JSP Expression Language (EL)

1. [Link] – Setting Request and Session Attributes


<%@ page contentType="text/html; charset=ISO-8859-1" %>
<%@ page import="[Link].*" %>
<!DOCTYPE html>
<html>
<head><title>Set Attributes</title></head>
<body>
<h1>Setting Request and Session Attributes</h1>

<%
// Set request and session attributes
[Link]("username", "John");
[Link]("userRole", "Admin");
%>

<p>Request Attribute: <%= [Link]("username") %></p>


<p>Session Attribute: <%= [Link]("userRole") %></p>
</body>
</html>

2. [Link] – Displaying Attributes Using EL


<%@ page contentType="text/html; charset=ISO-8859-1" %>
<!DOCTYPE html>
<html>
<head><title>Display Attributes</title></head>
<body>
<h1>Using JSP Expression Language (EL)</h1>

<p>Request Attribute: ${username}</p>


<p>Session Attribute: ${userRole}</p>
</body>
</html>

Output
Access the [Link] page at
[Link]
After visiting the [Link], access the [Link] page at
[Link]
The page will display:

Using JSP Expression Language (EL)

Request Attribute: John


Session Attribute: Admin

49. Implementing User Authentication using JSP

1. [Link] – Login Form


<!DOCTYPE html>
<html>
<head><title>User Login</title></head>
<body>
<h1>Login</h1>
<form action="authenticate" method="post">
<label for="username">Username: </label>
<input type="text" name="username" id="username"
required/><br><br>

<label for="password">Password: </label>


<input type="password" name="password" id="password"
required/><br><br>

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


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

2. [Link] – Validating Credentials and Redirecting


<%@ page import="[Link].*, [Link].*, [Link].*, [Link].*" %>
<%@ page contentType="text/html; charset=ISO-8859-1" %>
<!DOCTYPE html>
<html>
<head><title>Authentication</title></head>
<body>
<h1>Authentication</h1>

<%
String username = [Link]("username");
String password = [Link]("password");

// Simple validation (replace with DB validation in real applications)


if ("admin".equals(username) && "password123".equals(password)) {
// Successful login, create session
HttpSession session = [Link]();
[Link]("user", username);
[Link]("<p>Welcome, " + username + "!</p>");
[Link]("<p><a href='[Link]'>Go to Dashboard</a></p>");
} else {
// Failed login
[Link]("<p>Invalid username or password. Please try again.</p>");
[Link]("<p><a href='[Link]'>Back to Login</a></p>");
}
%>
</body>
</html>
3. [Link] – User Dashboard (Only Accessible After Login)
<%@ page contentType="text/html; charset=ISO-8859-1" %>
<%@ page session="true" %>
<!DOCTYPE html>
<html>
<head><title>Dashboard</title></head>
<body>
<h1>Dashboard</h1>

<%
HttpSession session = [Link](false);
if (session != null && [Link]("user") != null) {
String username = (String) [Link]("user");
[Link]("<p>Welcome to your dashboard, " + username + "!</p>");
[Link]("<p><a href='[Link]'>Logout</a></p>");
} else {
[Link]("<p>You are not logged in. <a
href='[Link]'>Login</a></p>");
}
%>
</body>
</html>

4. [Link] – Logging Out the User


<%@ page contentType="text/html; charset=ISO-8859-1" %>
<%@ page session="true" %>
<!DOCTYPE html>
<html>
<head><title>Logout</title></head>
<body>
<h1>Logout</h1>
<%
HttpSession session = [Link](false);
if (session != null) {
[Link](); // Destroy the session
[Link]("<p>You have successfully logged out.</p>");
}
[Link]("<p><a href='[Link]'>Back to Login</a></p>");
%>
</body>
</html>

Output
1. Access [Link] at [Link] to enter the
username and password.
2. Use the username admin and password password123 to log in.
3. If credentials are correct, it will redirect to [Link], displaying the
message:

Welcome to your dashboard, admin!

4. If the credentials are incorrect, it will display an error message:

Invalid username or password. Please try again.

50. Implementing MVC Architecture in JSP

1. Model: [Link] – A Simple JavaBean (Model)


public class User {
private String username;
private String password;

public User(String username, String password) {


[Link] = username;
[Link] = password;
}
public String getUsername() {
return username;
}

public void setUsername(String username) {


[Link] = username;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


[Link] = password;
}
}

2. Controller: [Link] – Handling User Authentication


(Controller)
import [Link].*;
import [Link].*;
import [Link].*;

public class LoginController extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String username = [Link]("username");
String password = [Link]("password");

// Simple authentication (replace with database logic)


if ("admin".equals(username) && "password123".equals(password)) {
// Create user model
User user = new User(username, password);

// Set user in session


HttpSession session = [Link]();
[Link]("user", user);

// Redirect to dashboard
[Link]("[Link]");
} else {
// Redirect to login page with error
[Link]("[Link]?error=true");
}
}
}

3. View: [Link] – User Login Form (View)


<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
<h1>Login</h1>

<%-- Display error message if login fails --%>


<p style="color: red;">
<%= [Link]("error") != null ? "Invalid credentials, please try
again." : "" %>
</p>

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


<label for="username">Username: </label>
<input type="text" name="username" id="username" required
/><br><br>
<label for="password">Password: </label>
<input type="password" name="password" id="password" required
/><br><br>

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


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

4. View: [Link] – User Dashboard (View)


<%@ page session="true" %>
<!DOCTYPE html>
<html>
<head><title>Dashboard</title></head>
<body>
<h1>Dashboard</h1>

<%
User user = (User) [Link]("user");
if (user != null) {
%>
<p>Welcome, <%= [Link]() %>!</p>
<a href="[Link]">Logout</a>
<% } else { %>
<p>You are not logged in. <a href="[Link]">Login</a></p>
<% } %>
</body>
</html>

5. View: [Link] – Logout Functionality (View)


<%@ page session="true" %>
<!DOCTYPE html>
<html>
<head><title>Logout</title></head>
<body>
<h1>Logout</h1>

<%
HttpSession session = [Link](false);
if (session != null) {
[Link](); // Invalidate session on logout
[Link]("<p>You have logged out successfully.</p>");
}
%>

<p><a href="[Link]">Back to Login</a></p>


</body>
</html>

6. [Link] – Configuring the Controller Servlet


<web-app xmlns="[Link] version="3.0">
<servlet>
<servlet-name>LoginController</servlet-name>
<servlet-class>LoginController</servlet-class>
</servlet>

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

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

Output
1. Login Page: Access [Link] at [Link]
o Enter the username admin and password password123 to log in.

2. Successful Login: Redirect to [Link], displaying:

Welcome, admin!

[Logout]
3. Failed Login: If credentials are incorrect, redirect to [Link] with an error
message:

Invalid credentials, please try again.

4. Logout: Access [Link] to log out, invalidating the session and


redirecting back to [Link].

You might also like