Advanced Java
Advanced Java
Below is the complete explanation and code implementation for the requested tasks:
A JavaBean is a reusable class containing properties, getters, setters, and optional methods.
package com.example;
// Constructor
public Student() {}
<!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>
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.*;
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());
}
}
}
DisplayStudents.jsp
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>
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.
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.
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.
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.
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>).
• 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.
• 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.
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.
@Override
public void init(ServletConfig config) throws
ServletException {
super.init(config);
System.out.println("Servlet initialized");
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
res.getWriter().println("Service method called");
}
@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);
}
}
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException {
res.getWriter().println("GET request handled");
}
@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.
We can get the reference to the session object in Java servlets or JSP using the following
methods:
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.
3. setProperty Tag
4. getProperty Tag
The <jsp:getProperty> tag retrieves and displays the value of a property from a
JavaBean.
Syntax: