From e118dcf88d504536e2d11f86a3e8ea6a06c0b85e Mon Sep 17 00:00:00 2001 From: Vivek Pramanik <39510579+icodervivek@users.noreply.github.com> Date: Fri, 31 Jan 2025 07:14:43 +0530 Subject: [PATCH] updated the files --- AssignmentOneJava.html | 365 +++++++++++++++++++++++++++++++++++++++++ exercise.css | 4 + test.css | 99 +++++++++++ 3 files changed, 468 insertions(+) create mode 100644 test.css diff --git a/AssignmentOneJava.html b/AssignmentOneJava.html index 7e8ddc3..bb7bc3a 100644 --- a/AssignmentOneJava.html +++ b/AssignmentOneJava.html @@ -103,6 +103,11 @@

25. Write a program to demonstrate interfaces. 26. Write a program to demonstrate packages. 27. Write a program to demonstrate multithreading. + 28. Write a program to demonstrate JDBC Connectivity. + 29. Design a login page using JSP and Servlet. + 30. Design a page using Servlet and JSP to retrieve and display any 5 user ID and password at the server page which is used in database. + 31. Write a program to demonstrate cookies and generate log file using JSP and Servlet. + @@ -861,6 +866,366 @@

27. Write a program to demonstrate multithreading.
+
28. Write a program to demonstrate JDBC Connectivity.
+
+
+          import java.sql.*;
+
+  public class OracleJDBCExample {
+            
+      public static void main(String[] args) {
+            try {
+                // Load the Oracle Type 2 driver (OCI driver)
+                // The Oracle OCI driver uses the Oracle Client libraries to connect to the Oracle DB
+                Class.forName("oracle.jdbc.OracleDriver");
+                System.out.println("Driver Loaded Successfully!");
+            
+                // Establish a connection using Type 2 driver (OCI)
+                // You must have the Oracle client (OCI) installed and configured
+                Connection conn = DriverManager.getConnection(
+                "jdbc:oracle:oci8:@localhost:1521:orcl", // JDBC URL for OCI driver
+                "username",  // Replace with your Oracle username
+                "password"   // Replace with your Oracle password
+                );
+                System.out.println("Connection Established Successfully!");
+            
+                // Create a statement
+                Statement stmt = conn.createStatement();
+            
+                // Execute a query
+                String query = "SELECT id, Name FROM students"; // SQL query to retrieve student data
+                ResultSet rs = stmt.executeQuery(query);
+            
+                // Process the result set
+                while (rs.next()) {
+                    System.out.println("ID = " + rs.getInt("id") + ", Name = " + rs.getString("Name"));
+                }
+            
+                // Close resources
+                rs.close();
+                stmt.close();
+                conn.close();
+                    System.out.println("Connection Closed Successfully!");
+                } catch (Exception e) {
+                    System.out.println("Something went wrong: " + e.getMessage());
+                }
+          }
+    }
+            
+            
+            
+
+ + +
29. Design a login page using JSP and Servlet.
+

Part 1: JSP (Login Page) login.jsp

+
+
+<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
+  <%@ page import="java.io.*, javax.servlet.*, javax.servlet.http.*" %>
+  <html>
+  <head>
+      <title>Login Page</title>
+  </head>
+  <body>
+      <h2>Login Form</h2>
+      <form action="LoginServlet" method="post">
+          <label for="username">Username:</label><br>
+          <input type="text" id="username" name="username" required><br><br>
+  
+          <label for="password">Password:</label><br>
+          <input type="password" id="password" name="password" required><br><br>
+  
+          <button type="submit">Login</button>
+      </form>
+  </body>
+  </html>
+  
+
+            
+
+

Part 2: Servlet (Backend Logic) LoginServlet.java

+
+
+            import java.io.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+public class LoginServlet extends HttpServlet {
+    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+        // Set response content type
+        response.setContentType("text/html");
+
+        // Get the user input from the login form
+        String username = request.getParameter("username");
+        String password = request.getParameter("password");
+
+        // Logic to validate the credentials (For simplicity, using hardcoded values)
+        PrintWriter out = response.getWriter();
+        if ("admin".equals(username) && "password123".equals(password)) {
+            // If valid, redirect to a welcome page
+            out.println("

Welcome, " + username + "!

"); + out.println("

You have logged in successfully.

"); + } else { + // If invalid, send an error message + out.println("

Invalid login credentials.

"); + out.println("

Try again

"); + } + } +} +
+ +
+
+ + +
30. Design a page using Servlet and JSP to retrieve and display any 5 user ID and password at the server page which is used in database.
+

Using Servlet

+
+
+    import java.io.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.sql.*;
+      
+  public class UserServlet extends HttpServlet {
+    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
+    throws ServletException, IOException {
+      response.setContentType("text/html");
+      PrintWriter out = response.getWriter();
+      
+      try {
+            // Connect to the database
+            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", 
+            "root", "password");
+      
+            // Fetch the first 5 users
+            String query = "SELECT id, username, password FROM users LIMIT 5";
+            Statement stmt = conn.createStatement();
+            ResultSet rs = stmt.executeQuery(query);
+      
+            // Start HTML output
+            out.println("<html><body>");
+            out.println("<h2>User Details</h2>");
+            out.println("<table border='1'><tr><th>ID</th><th>Username</th><th>Password</th></tr>");
+
+      
+            // Loop through the result set and display data in a table
+            while (rs.next()) {
+              out.println("<tr>");
+                out.println("<td>" + rs.getInt("id") + "</td>");
+                out.println("<td>" + rs.getString("username") + "</td>");
+                out.println("<td>" + rs.getString("password") + "</td>");
+                out.println("</tr>");
+          }
+          out.println("</table>");
+          out.println("</body></html>");
+      
+            // Close resources
+            rs.close();
+            stmt.close();
+            conn.close();
+          } catch (Exception e) {
+              out.println("Error: " + e.getMessage());
+          }
+        }
+    }
+      
+      
+      
+
+ +

Using JSP

+
+
+    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
+<%@ page import="java.sql.*, java.util.*" %>
+<html>
+<head>
+    <title>User Details</title>
+    <style>
+        table {
+            width: 50%;
+            margin: 50px auto;
+            border-collapse: collapse;
+        }
+        th, td {
+            padding: 8px;
+            text-align: left;
+            border: 1px solid #ddd;
+        }
+        th {
+            background-color: #f2f2f2;
+        }
+    </style>
+</head>
+<body>
+    <h2 style="text-align: center;">User Details</h2>
+    <table>
+    <thead>
+        <tr>
+            <th>ID</th>
+            <th>Username</th>
+            <th>Password</th>
+        </tr>
+    </thead>
+    <tbody>
+            <%
+            // Establish the database connection using the utility class
+            Connection conn = null;
+            Statement stmt = null;
+            ResultSet rs = null;
+            
+            try {
+                conn = DBConnection.getConnection(); // Use the DBConnection class
+                stmt = conn.createStatement();
+                
+                // Query to fetch first 5 users from the database
+                String query = "SELECT id, username, password FROM users LIMIT 5";
+                rs = stmt.executeQuery(query);
+                
+                // Loop through the result set and display user data in the table
+                while (rs.next()) {
+                  out.println("<tr>");
+                  out.println("<td>" + rs.getInt("id") + "</td>");
+                  out.println("<td>" + rs.getString("username") + "</td>");
+                  out.println("<td>" + rs.getString("password") + "</td>");
+                  out.println("</tr>");
+                }
+            } catch (SQLException e) {
+                out.println("<tr><td colspan='3'>Error: " + e.getMessage() + "</td></tr>");
+            } finally {
+                // Close the database resources
+                try {
+                  if (rs != null) rs.close();
+                  if (stmt != null) stmt.close();
+                  if (conn != null) conn.close();
+                } catch (SQLException e) {
+                  out.println("<tr><td colspan='3'>Error closing resources: " + 
+                  e.getMessage() + "</td></tr>");
+                }
+            }
+            %>
+        </tbody>
+    </table>
+</body>
+</html>
+      
+      
+      
+
+ + +
31. Write a program to demonstrate cookies and generate log file using JSP and Servlet.
+

Servlet: CookieServlet.java +

+
+
+          import java.io.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.util.*;
+import java.text.*;
+
+public class CookieServlet extends HttpServlet {
+    
+    private static final String LOG_FILE_PATH = "C:/logs/application.log"; 
+    // Change this path based on your system
+
+    @Override
+    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
+    throws ServletException, IOException {
+        response.setContentType("text/html");
+        PrintWriter out = response.getWriter();
+        
+        // Create a new cookie
+        String userId = UUID.randomUUID().toString(); // Generate a unique user ID
+        Cookie userCookie = new Cookie("userID", userId);
+        userCookie.setMaxAge(60 * 60); // Set cookie expiration to 1 hour
+        response.addCookie(userCookie);
+
+        // Log the request information
+        logRequestToFile(request);
+
+        out.println("<html>");
+        out.println("<body>");
+        out.println("<h2>Cookie Created Successfully!</h2>");
+        out.println("<p>Your unique user ID (Cookie): " + userId + "</p>");
+        out.println("<p><a href='log.jsp'>Click here to view the log file</a></p>");
+        out.println("</body>");
+        out.println("</html>");
+    }
+
+    // Method to log request information into a log file
+    private void logRequestToFile(HttpServletRequest request) {
+        try {
+          PrintWriter logWriter = new PrintWriter(new FileWriter(LOG_FILE_PATH, true)); // Append mode
+          String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
+          String logMessage = timestamp + " - Access from IP: " + request.getRemoteAddr() 
+          + " with User-Agent: " + request.getHeader("User-Agent");
+          logWriter.println(logMessage);
+          logWriter.close();
+        } catch (IOException e) {
+          System.out.println("Error logging request: " + e.getMessage());
+        }
+    }
+}
+          
+        
+
+ +

JSP: log.jsp +

+
+
+              <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
+<%@ page import="java.io.*, java.util.*" %>
+<html>
+<head>
+    <title>Log File and Cookie Information</title>
+</head>
+<body>
+    <h2>Cookie Information</h2>
+    <p>
+        <%
+            Cookie[] cookies = request.getCookies();
+            if (cookies != null) {
+                for (Cookie cookie : cookies) {
+                    if ("userID".equals(cookie.getName())) {
+                        out.println("Your User ID (Cookie): " + cookie.getValue());
+                    }
+                }
+            } else {
+                out.println("No cookies found.");
+            }
+        %>
+    </p>
+
+    <h2>Log File Contents</h2>
+    <pre>
+        <%
+            String logFilePath = "C:/logs/application.log"; 
+            // Make sure the path is correct for your environment
+            File logFile = new File(logFilePath);
+            if (logFile.exists()) {
+                BufferedReader reader = new BufferedReader(new FileReader(logFile));
+                String line;
+                while ((line = reader.readLine()) != null) {
+                    out.println(line);
+                }
+                reader.close();
+            } else {
+                out.println("Log file does not exist.");
+            }
+        %>
+    </pre>
+</body>
+</html>
+              
+            
+
+ +