0% found this document useful (0 votes)
17 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)
17 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
You are on page 1/ 53

26.

Passing Objects in RMI

1. Student.java (Serializable Object)


import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int roll;
public Student(String name, int roll) {
this.name = name;
this.roll = roll;
}
public String getName() {
return name;
}
public int getRoll() {
return roll;
}
}

2. StudentService.java (Remote Interface)


import java.rmi.Remote;
import java.rmi.RemoteException;
public interface StudentService extends Remote {
String displayStudent(Student student) throws RemoteException;
}

3. StudentServiceImpl.java (Remote Object Implementation)


import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
public class StudentServiceImpl extends UnicastRemoteObject implements
StudentService {
protected StudentServiceImpl() throws RemoteException {
super();
}
public String displayStudent(Student student) throws RemoteException {
return "Student Name: " + student.getName() + ", Roll No: " +
student.getRoll();
}
}

4. Server.java
import java.rmi.Naming;

public class Server {


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

5. Client.java
import java.rmi.Naming;

public class Client {


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

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

27. Distributed Calculator using RMI

Calculator.java – Remote Interface


import java.rmi.*;

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;
}
CalculatorImpl.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

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; }
}

Server.java
import java.rmi.Naming;

public class Server {


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

Client.java
import java.rmi.Naming;

public class Client {


public static void main(String[] args) {
try {
Calculator calc = (Calculator)
Naming.lookup("rmi://localhost:1099/CalculatorService");
System.out.println("Add: " + calc.add(10, 5));
System.out.println("Subtract: " + calc.subtract(10, 5));
System.out.println("Multiply: " + calc.multiply(10, 5));
System.out.println("Divide: " + calc.divide(10, 5));
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output

Calculator RMI Server is running...

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

28. RMI-based Chat Application

ChatInterface.java – Remote Interface


import java.rmi.*;

public interface ChatInterface extends Remote {


void sendMessage(String msg) throws RemoteException;
String receiveMessage() throws RemoteException;
}
ChatImpl.java – Remote Object
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

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 {


this.message = msg;
}

public String receiveMessage() throws RemoteException {


return message;
}
}
Server.java
import java.rmi.Naming;

public class Server {


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

public class Client1 {


public static void main(String[] args) {
try {
ChatInterface chat = (ChatInterface)
Naming.lookup("rmi://localhost:1099/ChatService");
chat.sendMessage("Hello from Client 1!");
System.out.println("Message sent from Client 1.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client2.java – Receiving the Message
import java.rmi.Naming;

public class Client2 {


public static void main(String[] args) {
try {
ChatInterface chat = (ChatInterface)
Naming.lookup("rmi://localhost:1099/ChatService");
String msg = chat.receiveMessage();
System.out.println("Client 2 received: " + msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output

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

29. File Sharing System using RMI

FileService.java – Remote Interface


import java.rmi.*;
import java.io.*;

public interface FileService extends Remote {


byte[] downloadFile(String fileName) throws RemoteException;
}
FileServiceImpl.java – Remote Object
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.io.*;

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) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(fileData);
fis.close();
return fileData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
Server.java
import java.rmi.Naming;

public class Server {


public static void main(String[] args) {
try {
FileService fs = new FileServiceImpl();
Naming.rebind("rmi://localhost:1099/FileService", fs);
System.out.println("File Server is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client.java
import java.rmi.Naming;
import java.io.*;

public class Client {


public static void main(String[] args) {
try {
FileService fs = (FileService)
Naming.lookup("rmi://localhost:1099/FileService");
byte[] fileData = fs.downloadFile("server.txt");

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


fos.write(fileData);
fos.close();

System.out.println("File downloaded as client_download.txt");


} catch (Exception e) {
e.printStackTrace();
}
}
}

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 server.keystore -storepass password

1. SecureService.java – Remote Interface


import java.rmi.Remote;
import java.rmi.RemoteException;

public interface SecureService extends Remote {


String secureHello(String name) throws RemoteException;
}
2. SecureServiceImpl.java
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

public class SecureServiceImpl extends UnicastRemoteObject implements


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

public String secureHello(String name) throws RemoteException {


return "Secure Hello, " + name;
}
}
3. SSLServer.java
import java.rmi.Naming;
import java.rmi.server.RMISocketFactory;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;

public class SSLServer {


public static void main(String[] args) {
try {
System.setProperty("javax.net.ssl.keyStore", "server.keystore");
System.setProperty("javax.net.ssl.keyStorePassword", "password");

SecureService service = new SecureServiceImpl();

java.rmi.registry.LocateRegistry.createRegistry(1099,
new SslRMIClientSocketFactory(),
new SslRMIServerSocketFactory());

Naming.rebind("rmi://localhost:1099/SecureService", service);
System.out.println("Secure RMI Server is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. SSLClient.java
import javax.rmi.ssl.SslRMIClientSocketFactory;
import java.rmi.Naming;

public class SSLClient {


public static void main(String[] args) {
try {
System.setProperty("javax.net.ssl.trustStore", "server.keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "password");
SecureService service = (SecureService)
Naming.lookup("rmi://localhost:1099/SecureService");
String response = service.secureHello("Alice");
System.out.println("Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output

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

31. Implementing Load Balancing with RMI

1. LoadService.java – Remote Interface


import java.rmi.*;

public interface LoadService extends Remote {


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

2. LoadServiceImpl.java – Remote Object


import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

public class LoadServiceImpl extends UnicastRemoteObject implements


LoadService {
private int load;
protected LoadServiceImpl(int initialLoad) throws RemoteException {
super();
this.load = 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. Server1.java
import java.rmi.Naming;

public class Server1 {


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

public class Server2 {


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

5. Client.java
import java.rmi.Naming;

public class Client {


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

LoadService selected = (server1.getLoad() < server2.getLoad()) ?


server1 : server2;

String response = selected.processRequest("Client A");


System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
}
}

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. HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


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

2. web.xml (Web Deployment Descriptor)


<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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:
http://localhost:8080/YourProjectName/hello
Output:

Hello from Servlet

33. Handling HTTP Requests and Responses in Servlets

1. RequestResponseServlet.java
java
CopyEdit
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestResponseServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String name = request.getParameter("username");

out.println("<h2>Hello, " + name + "!</h2>");


}
}

2. form.html (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. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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. ConfigContextServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ConfigContextServlet extends HttpServlet {

public void init(ServletConfig config) throws ServletException {


super.init(config);
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// ServletConfig parameter
ServletConfig config = getServletConfig();
String adminEmail = config.getInitParameter("adminEmail");

// ServletContext parameter
ServletContext context = getServletContext();
String companyName = context.getInitParameter("company");

out.println("<h2>Admin Email: " + adminEmail + "</h2>");


out.println("<h2>Company Name: " + companyName + "</h2>");
}
}
2. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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>[email protected]</param-value>
</init-param>
</servlet>

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

</web-app>

Output
Access: http://localhost:8080/YourApp/config

Admin Email: [email protected]


Company Name: OpenAI Solutions

35. Managing Sessions in Servlets

1. SessionServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Retrieve session object


HttpSession session = request.getSession(true);
String name = (String) session.getAttribute("username");

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

out.println("<h2>Welcome, " + name + "!</h2>");

// Set session attribute


session.setAttribute("username", "JohnDoe");
}
}

2. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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: http://localhost:8080/YourApp/session
First request (no session):

Welcome, Guest!

After session is created:

Welcome, JohnDoe!

36. Implementing Servlet Chaining

1. FirstServlet.java (Initial servlet in the chain)


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


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

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


RequestDispatcher dispatcher = request.getRequestDispatcher("/second");
dispatcher.forward(request, response);
}
}

2. SecondServlet.java (Next servlet in the chain)


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Retrieve the attribute from the request


String message = (String) request.getAttribute("message");
out.println("<h2>" + message + " and Second Servlet processing
request.</h2>");
}
}

3. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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: http://localhost:8080/YourApp/first

Hello from First Servlet and Second Servlet processing request.

37. Using Cookies for Session Tracking

1. CookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CookieServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Check if the "username" cookie exists


Cookie[] cookies = request.getCookies();
String userName = "Guest";

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

out.println("<h2>Welcome, " + userName + "!</h2>");

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


Cookie cookie = new Cookie("username", "JohnDoe");
cookie.setMaxAge(60 * 60); // 1 hour
response.addCookie(cookie);
}
}

2. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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: http://localhost:8080/YourApp/cookie
First visit (no cookie):

Welcome, Guest!

Subsequent visits (cookie stored):

Welcome, JohnDoe!

38. Connecting Servlets with Databases


1. DatabaseConnection.java – Helper Class to Establish DB Connection
import java.sql.*;

public class DatabaseConnection {


public static Connection getConnection() {
try {
// Load the database driver (MySQL in this case)
Class.forName("com.mysql.cj.jdbc.Driver");

// Return connection object


return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/yourDatabase", "root", "password");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
2. UserServlet.java – Servlet to Fetch Data from Database
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class UserServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
Connection conn = DatabaseConnection.getConnection();
String query = "SELECT username, email FROM users";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);

out.println("<table border='1'>");
out.println("<tr><th>Username</th><th>Email</th></tr>");

while (rs.next()) {
out.println("<tr><td>" + rs.getString("username") + "</td>");
out.println("<td>" + rs.getString("email") + "</td></tr>");
}
out.println("</table>");

conn.close();
} catch (SQLException e) {
e.printStackTrace();
out.println("<h3>Error: " + e.getMessage() + "</h3>");
}
}
}

3. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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: http://localhost:8080/YourApp/user
Assuming the users table in the database has data:

| Username | Email |
|----------|-----------------|
| john | [email protected]|
| alice | [email protected]|

39. Uploading Files using Servlets

1. Add Required Dependencies (in web.xml)


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. FileUploadServlet.java – Servlet for File Upload


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.FileItem;

public class FileUploadServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Check if the request is a file upload


boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
out.println("<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
java.util.List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
// Process the uploaded file
String fileName = item.getName();
String filePath = "uploads/" + fileName;

// Save the file on the server


File uploadedFile = new File(filePath);
item.write(uploadedFile);

out.println("<h3>File uploaded successfully: " + fileName +


"</h3>");
}
}
} catch (Exception e) {
out.println("<h3>Error uploading file: " + e.getMessage() + "</h3>");
}
}
}

3. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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. upload.html – 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: http://localhost:8080/YourApp/upload.html
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. LoginServlet.java – Servlet for Handling Login


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Retrieve user input from the login form


String username = request.getParameter("username");
String password = request.getParameter("password");

// Simple validation (hardcoded credentials)


if ("admin".equals(username) && "password123".equals(password)) {
out.println("<h2>Login Successful!</h2>");
} else {
out.println("<h2>Invalid username or password. Please try
again.</h2>");
}
}
}
2. login.html – 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. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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: http://localhost:8080/YourApp/login.html
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. LoggingFilter.java – A Filter for Logging Request Information


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

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;
System.out.println("Request received for: " + httpRequest.getRequestURI());

// Continue the request-response chain


chain.doFilter(request, response);
}

public void destroy() {


// Cleanup resources (optional)
}
}

2. web.xml – Configuring the Filter in web.xml


<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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 http://localhost:8080/YourApp/login, the filter logs the
request information.
Example log:

Request received for: /YourApp/login

42. Introduction to JSP - Creating a Simple JSP Page

1. hello.jsp – 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. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
<servlet>
<servlet-name>helloJSP</servlet-name>
<servlet-class>javax.servlet.jsp.JspServlet</servlet-class>
<init-param>
<param-name>jsp-file</param-name>
<param-value>/hello.jsp</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 http://localhost:8080/YourApp/hello.

Hello, World!
This is a simple JSP page.

43. JSP Implicit Objects and Their Uses

1. implicit.jsp – JSP Using Implicit Objects


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

<h2>Request Information:</h2>
<p>Request Method: <%= request.getMethod() %></p>
<p>Request URI: <%= request.getRequestURI() %></p>

<h2>Session Information:</h2>
<%
HttpSession session = request.getSession(true);
String sessionID = session.getId();
%>
<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 http://localhost:8080/YourApp/implicit.
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 13:45:02 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="java.util.*" %>

<!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 http://localhost:8080/YourApp/directive_declaration.
The page will display:

Using JSP Directives and Declarations

Greeting Message:
Hello, welcome to JSP!

Current Date and Time:


Tue May 01 13:50:00 GMT 2025

45. Handling Forms in JSP

1. form.jsp – 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. greet.jsp – 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 = request.getParameter("name");
if (name != null && !name.trim().isEmpty()) {
out.println("<h2>Hello, " + name + "!</h2>");
} else {
out.println("<h2>Name not provided!</h2>");
}
%>
</body>
</html>

3. web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
<servlet>
<servlet-name>greetServlet</servlet-name>
<servlet-class>javax.servlet.jsp.JspServlet</servlet-class>
<init-param>
<param-name>jsp-file</param-name>
<param-value>/greet.jsp</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: http://localhost:8080/YourApp/form.jsp.
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. DatabaseConnection.java – Helper Class to Connect to the Database


import java.sql.*;

public class DatabaseConnection {


public static Connection getConnection() {
try {
// Load database driver (MySQL in this case)
Class.forName("com.mysql.cj.jdbc.Driver");

// Return connection object


return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/yourDatabase", "root", "password");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

2. displayData.jsp – JSP Page to Retrieve and Display Data


<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head><title>Data from Database</title></head>
<body>
<h1>Database Records</h1>

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

out.println("<table border='1'>");
out.println("<tr><th>Username</th><th>Email</th></tr>");
while (rs.next()) {
out.println("<tr><td>" + rs.getString("username") + "</td>");
out.println("<td>" + rs.getString("email") + "</td></tr>");
}
out.println("</table>");

// Close the connection


conn.close();
} else {
out.println("<h3>Failed to connect to the database</h3>");
}
%>
</body>
</html>

Output
Access the JSP page at http://localhost:8080/YourApp/displayData.
If the users table contains data like:
| username | email |
|----------|--------------------|
| john | [email protected] |
| alice | [email protected] |

The page will display:

Database Records

| Username | Email |
|----------|--------------------|
| john | [email protected] |
| alice | [email protected] |

47. Implementing JSP Custom Tags

1. GreetingTag.java – Java Class for the Custom Tag


import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

public class GreetingTag extends SimpleTagSupport {


private String name;

public void setName(String name) {


this.name = name;
}

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

2. taglib.tld – Tag Library Descriptor (TLD) File


<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee" 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. web.xml – Register the TLD File


<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
<servlet>
<servlet-name>JSPServlet</servlet-name>
<servlet-class>javax.servlet.jsp.JspServlet</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/greeting-tag.tld</taglib-location>
</taglib>
</web-app>

4. customTagPage.jsp – 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 http://localhost:8080/YourApp/customTagPage.
The page will display:

Custom Tag Example

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

1. setAttributes.jsp – Setting Request and Session Attributes


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

<%
// Set request and session attributes
request.setAttribute("username", "John");
session.setAttribute("userRole", "Admin");
%>

<p>Request Attribute: <%= request.getAttribute("username") %></p>


<p>Session Attribute: <%= session.getAttribute("userRole") %></p>
</body>
</html>

2. displayAttributes.jsp – 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 setAttributes.jsp page at
http://localhost:8080/YourApp/setAttributes.jsp.
After visiting the setAttributes.jsp, access the displayAttributes.jsp page at
http://localhost:8080/YourApp/displayAttributes.jsp.
The page will display:

Using JSP Expression Language (EL)

Request Attribute: John


Session Attribute: Admin

49. Implementing User Authentication using JSP

1. login.jsp – 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. authenticate.jsp – Validating Credentials and Redirecting


<%@ page import="java.io.*, java.sql.*, javax.servlet.*, javax.servlet.http.*" %>
<%@ page contentType="text/html; charset=ISO-8859-1" %>
<!DOCTYPE html>
<html>
<head><title>Authentication</title></head>
<body>
<h1>Authentication</h1>

<%
String username = request.getParameter("username");
String password = request.getParameter("password");

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


if ("admin".equals(username) && "password123".equals(password)) {
// Successful login, create session
HttpSession session = request.getSession();
session.setAttribute("user", username);
out.println("<p>Welcome, " + username + "!</p>");
out.println("<p><a href='dashboard.jsp'>Go to Dashboard</a></p>");
} else {
// Failed login
out.println("<p>Invalid username or password. Please try again.</p>");
out.println("<p><a href='login.jsp'>Back to Login</a></p>");
}
%>
</body>
</html>
3. dashboard.jsp – 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 = request.getSession(false);
if (session != null && session.getAttribute("user") != null) {
String username = (String) session.getAttribute("user");
out.println("<p>Welcome to your dashboard, " + username + "!</p>");
out.println("<p><a href='logout.jsp'>Logout</a></p>");
} else {
out.println("<p>You are not logged in. <a
href='login.jsp'>Login</a></p>");
}
%>
</body>
</html>

4. logout.jsp – 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 = request.getSession(false);
if (session != null) {
session.invalidate(); // Destroy the session
out.println("<p>You have successfully logged out.</p>");
}
out.println("<p><a href='login.jsp'>Back to Login</a></p>");
%>
</body>
</html>

Output
1. Access login.jsp at http://localhost:8080/YourApp/login.jsp 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 dashboard.jsp, 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: User.java – A Simple JavaBean (Model)


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

public User(String username, String password) {


this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}

public void setUsername(String username) {


this.username = username;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}
}

2. Controller: LoginController.java – Handling User Authentication


(Controller)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class LoginController extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("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 = request.getSession();
session.setAttribute("user", user);

// Redirect to dashboard
response.sendRedirect("dashboard.jsp");
} else {
// Redirect to login page with error
response.sendRedirect("login.jsp?error=true");
}
}
}

3. View: login.jsp – 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;">
<%= request.getParameter("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: dashboard.jsp – User Dashboard (View)


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

<%
User user = (User) session.getAttribute("user");
if (user != null) {
%>
<p>Welcome, <%= user.getUsername() %>!</p>
<a href="logout.jsp">Logout</a>
<% } else { %>
<p>You are not logged in. <a href="login.jsp">Login</a></p>
<% } %>
</body>
</html>

5. View: logout.jsp – Logout Functionality (View)


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

<%
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate(); // Invalidate session on logout
out.println("<p>You have logged out successfully.</p>");
}
%>

<p><a href="login.jsp">Back to Login</a></p>


</body>
</html>

6. web.xml – Configuring the Controller Servlet


<web-app xmlns="http://java.sun.com/xml/ns/javaee" 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>login.jsp</welcome-file>
</welcome-file-list>
</web-app>

Output
1. Login Page: Access login.jsp at http://localhost:8080/YourApp/login.jsp.
o Enter the username admin and password password123 to log in.

2. Successful Login: Redirect to dashboard.jsp, displaying:

Welcome, admin!

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

Invalid credentials, please try again.

4. Logout: Access logout.jsp to log out, invalidating the session and


redirecting back to login.jsp.

You might also like