0% found this document useful (0 votes)
3 views

Advanced Java

The document provides a comprehensive guide on implementing a student management system using Java technologies, including JavaBeans, HTML forms, servlets, and JSP. It covers the creation of a Student JavaBean, login and student management HTML pages, SQL procedures for updating and deleting student records, and the servlet lifecycle. Additionally, it explains HTTP request and response formats, JSP lifecycle, and the use of cookies and sessions in web applications.

Uploaded by

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

Advanced Java

The document provides a comprehensive guide on implementing a student management system using Java technologies, including JavaBeans, HTML forms, servlets, and JSP. It covers the creation of a Student JavaBean, login and student management HTML pages, SQL procedures for updating and deleting student records, and the servlet lifecycle. Additionally, it explains HTTP request and response formats, JSP lifecycle, and the use of cookies and sessions in web applications.

Uploaded by

Sampriti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Full Solution for the Questions:

Below is the complete explanation and code implementation for the requested tasks:

1. JavaBean Class for Student

A JavaBean is a reusable class containing properties, getters, setters, and optional methods.

package com.example;

public class Student {


private int roll;
private String name;
private int marks;

// Constructor
public Student() {}

public Student(int roll, String name, int marks) {


this.roll = roll;
this.name = name;
this.marks = marks;
}

// Getters and Setters


public int getRoll() {
return roll;
}

public void setRoll(int roll) {


this.roll = roll;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getMarks() {


return marks;
}

public void setMarks(int marks) {


this.marks = marks;
}
}

2. HTML Page for Login and Student Input

Login Page (login.html)

<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="LoginServlet" method="post">
Username: <input type="text" name="username"
required><br>
Password: <input type="password" name="password"
required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Student Management Page (student.html)

<!DOCTYPE html>
<html>
<head>
<title>Student Management</title>
</head>
<body>
<h2>Update or Delete Student</h2>
<form action="StudentServlet" method="post">
Roll No: <input type="text" name="roll" required><br>
Name: <input type="text" name="name"><br>
Marks: <input type="text" name="marks"><br>
<button type="submit" name="action"
value="update">Update</button>
<button type="submit" name="action"
value="delete">Delete</button>
</form>
</body>
</html>

3. Callable Statements for Procedures


SQL Table and Procedures

-- Create Student Table


CREATE TABLE Student (
roll INT PRIMARY KEY,
name VARCHAR(100),
marks INT
);

-- Stored Procedure for Update


DELIMITER //
CREATE PROCEDURE UpdateStudent(IN roll INT, IN newMarks INT)
BEGIN
UPDATE Student SET marks = newMarks WHERE roll = roll;
END;
//

-- Stored Procedure for Delete


DELIMITER //
CREATE PROCEDURE DeleteStudent(IN roll INT)
BEGIN
DELETE FROM Student WHERE roll = roll;
END;
//

4. Servlet for Login Handling (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 {
String username = request.getParameter("username");
String password = request.getParameter("password");

if ("admin".equals(username) &&
"password123".equals(password)) {
response.sendRedirect("student.html");
} else {
response.getWriter().println("<h3>Invalid
Username or Password</h3>");
}
}
}
5. Servlet for Update/Delete Operations (StudentServlet.java)
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class StudentServlet extends HttpServlet {


protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
int roll =
Integer.parseInt(request.getParameter("roll"));
String action = request.getParameter("action");

try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/
yourDB", "root", "password");

if ("update".equals(action)) {
int marks =
Integer.parseInt(request.getParameter("marks"));
CallableStatement stmt =
con.prepareCall("{CALL UpdateStudent(?, ?)}");
stmt.setInt(1, roll);
stmt.setInt(2, marks);
stmt.execute();
response.getWriter().println("Student updated
successfully.");
} else if ("delete".equals(action)) {
CallableStatement stmt =
con.prepareCall("{CALL DeleteStudent(?)}");
stmt.setInt(1, roll);
stmt.execute();
response.getWriter().println("Student deleted
successfully.");
}

con.close();
} catch (Exception e) {
response.getWriter().println("Error: " +
e.getMessage());
}
}
}

6. JSP to Display Students in Tabular Format

DisplayStudents.jsp

<%@ page import="java.sql.*" %>


<!DOCTYPE html>
<html>
<head>
<title>Student Records</title>
</head>
<body>
<h2>Student Records</h2>
<table border="1">
<tr>
<th>Roll</th>
<th>Name</th>
<th>Marks</th>
</tr>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/
yourDB", "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM
Student");

while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("roll") +
"</td>");
out.println("<td>" + rs.getString("name") +
"</td>");
out.println("<td>" + rs.getInt("marks") +
"</td>");
out.println("</tr>");
}

con.close();
} catch (Exception e) {
out.println("<tr><td colspan='3'>Error: " +
e.getMessage() + "</td></tr>");
}
%>
</table>
</body>
</html>

This setup involves:

• JavaBean for encapsulating student data.


• HTML forms for login and student management.
• CallableStatement for executing SQL procedures.
• Servlets for handling login and update/delete operations.
• JSP for displaying student data in tabular format.

Here are expanded answers for each question, suitable for 5 marks:

1. Suppose you have n number of logged-in users, then write the number of
sessions? Cookies.

• Sessions: Each logged-in user has one unique session. If there are n users logged in
simultaneously, the number of sessions will be exactly n. Sessions are server-side
objects used to track user activities.
• Cookies: Cookies are used to store session identifiers on the client side. They help the
server recognize returning users. Each session typically corresponds to one cookie
unless URL rewriting or hidden form fields are used. For n users, there are n cookies
if cookies manage session tracking.

2. HTTP Request Format

An HTTP request consists of three parts:

1 Start line: Includes the HTTP method (e.g., GET, POST), the target resource (URL), and
the protocol version. Example: GET /home.html HTTP/1.1.
2 Headers: Provide metadata about the request, such as Content-Type, Host, and
User-Agent. Example: Host: www.example.com.
3 Body: Contains data sent with the request (applicable for POST/PUT methods). Example:
form submissions or JSON data.

3. HTTP Response Format

An HTTP response includes the following:

1 Status line: Displays the protocol version, status code, and a status message. Example:
HTTP/1.1 200 OK.
2 Headers: Metadata about the response, such as Content-Type: text/html or
Content-Length: 234.
3 Body: Contains the actual content of the response, such as an HTML page, JSON data, or
other files.

4. JSP Life Cycle

1 Translation: The JSP file is converted into a servlet by the web container.
2 Compilation: The servlet code is compiled into a .class file.
3 Initialization: The jspInit() method is called to initialize resources.
4 Execution: The service() method handles incoming requests and generates dynamic
responses.
5 Destruction: The jspDestroy() method releases resources before the JSP is removed
from memory.

5. JSP Tags (Directive, Action, Custom)

1 Directive Tags: <%@ page %>, <%@ include %> define page settings or include files.
2 Declaration Tags: <%! %> declare variables or methods.
3 Scriptlet Tags: <% %> contain Java code embedded in JSP.
4 Expression Tags: <%= %> evaluate expressions and output results.
5 Custom Tags: Defined in tag libraries (e.g., <taglib:customtag>).

6. JSP Implicit Objects (9)

1 request: Represents the HTTP request.


2 response: Represents the HTTP response.
3 out: Writes data to the output stream.
4 session: Manages user sessions.
5 application: Provides application-level data sharing.
6 config: Retrieves servlet configuration.
7 pageContext: Provides access to JSP-related objects.
8 page: Represents the current page.
9 exception: Handles exceptions on error pages.

7. Servlet Life Cycle

1 Initialization: The servlet is instantiated, and init() is called once.


2 Service: For each client request, the service() method is called to process the request
and generate a response.
3 Destruction: The destroy() method is called to release resources when the servlet is
removed.

8. JavaBean (setProperty, getProperty)

• setProperty: Sets values for bean properties dynamically. Example:


<jsp:setProperty name="student" property="name"
value="John" />.
• getProperty: Retrieves bean property values dynamically. Example:
<jsp:getProperty name="student" property="name"
/>. JavaBeans must implement the Serializable interface and provide getter
and setter methods for encapsulated properties.

9. Difference between GET and POST

• GET:
◦ Appends data to the URL, visible to users.
◦ Limited data size.
◦ Used for retrieving resources.
• POST:
◦ Sends data in the request body, hidden from users.
◦ Larger data size allowed.
◦ Used for submitting forms or uploading files.

10. forward() vs include()

• forward():
◦ Transfers control to another resource (e.g., JSP or servlet).
◦ The original resource doesn't generate content.
• include():
◦ Includes the content of another resource in the response.
◦ Both the original and included resources generate content.

11. forward() vs sendRedirect()

• forward(): Server-side, faster, used for internal resources.


• sendRedirect(): Client-side, slower, can redirect to external URLs.

12. JSP API

The JSP API includes core classes (JspWriter, PageContext, HttpJspPage) and
interfaces (JspPage, Tag). These classes and interfaces provide methods for lifecycle
management, page scripting, and tag handling in JSP.

13. Types of JDBC Drivers

1 Type 1 (JDBC-ODBC Bridge): Connects via ODBC driver.


2 Type 2 (Native-API): Uses native database client libraries.
3 Type 3 (Network Protocol): Converts JDBC calls to database-specific protocol over a
network.
4 Type 4 (Thin Driver): Pure Java driver, directly communicates with the database.
Here’s an explanation of each method in the servlet lifecycle and HTTP handling:

1. public void init(ServletConfig config)

• This method is called only once when the servlet is initialized.


• It is used to perform servlet initialization tasks like loading configuration settings or
initializing resources like database connections.
• The ServletConfig object provides initialization parameters and servlet-specific
configuration.
Example:

@Override
public void init(ServletConfig config) throws
ServletException {
super.init(config);
System.out.println("Servlet initialized");
}

2. public void service(ServletRequest request,


ServletResponse response) throws ServletException,
IOException
• The service() method is called for every client request.
• It determines the HTTP method (e.g., GET or POST) and delegates the request to
doGet() or doPost().
• Override only if custom processing for all request types is needed.
Example:

@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
res.getWriter().println("Service method called");
}

3. public void destroy()

• Called when the servlet is being removed from memory.


• Used to release resources like closing database connections or stopping background
threads.
Example:

@Override
public void destroy() {
System.out.println("Servlet destroyed");
}
4. public void service(HttpServletRequest request,
HttpServletResponse response)
• An overridden version of service() specific to HttpServletRequest and
HttpServletResponse.
• Used when implementing HTTP-specific logic.
Example:

@Override
protected void service(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
if (req.getMethod().equalsIgnoreCase("GET")) {
doGet(req, res);
} else if (req.getMethod().equalsIgnoreCase("POST")) {
doPost(req, res);
}
}

5. public void doGet(HttpServletRequest request,


HttpServletResponse response)
• Handles HTTP GET requests.
• Used for fetching resources or displaying content.
• Data is typically sent as query parameters in the URL.
Example:

@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
res.getWriter().println("GET request handled");
}

6. public void doPost(HttpServletRequest request,


HttpServletResponse response)
• Handles HTTP POST requests.
• Used for creating resources, submitting forms, or handling sensitive data.
• Data is sent in the request body, making it more secure.
Example:

@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
res.getWriter().println("POST request handled");
}

These methods are part of the servlet lifecycle and HTTP request-handling workflow. Use
doGet() and doPost() for specific HTTP methods and init()/destroy() for
setup and cleanup tasks.

1. How do we get the reference of the session object?

We can get the reference to the session object in Java servlets or JSP using the following
methods:

• In Servlet: Use HttpServletRequest's getSession() method.


HttpSession session = request.getSession();
• In JSP: The session object is an implicit object available by default in JSP.
<%
HttpSession session = session;
%>
The session object allows storing and retrieving user-specific data between requests.

2. What is a Cookie?

A cookie is a small piece of data stored on the client-side (browser) by the server. It helps
maintain user state between requests.

• Types: Persistent and Non-persistent cookies.


• Usage: Session tracking, user preferences, and login sessions.
• Example:
Cookie cookie = new Cookie("username", "JohnDoe");
response.addCookie(cookie);
• In JSP:
<%
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
out.println(cookie.getName() + ": " +
cookie.getValue());
}
%>

3. setProperty Tag

The <jsp:setProperty> tag is used to set values in a JavaBean property.


Syntax:

<jsp:setProperty name="beanName" property="propertyName"


value="value" />
Example:

<jsp:setProperty name="user" property="username"


value="JohnDoe" />
It automatically populates bean properties based on request parameters using
property="*".

4. getProperty Tag

The <jsp:getProperty> tag retrieves and displays the value of a property from a
JavaBean.

Syntax:

<jsp:getProperty name="beanName" property="propertyName" />


Example:

<jsp:getProperty name="user" property="username" />


This tag ensures separation of data and presentation.

You might also like