Java solution
Java solution
2a) What are cookies? Correlate the usage of Cookies in servlets. How de you set out a
cookie in a servlet provide an example code
What are Cookies?
Cookies are small pieces of data stored by a web browser on behalf of a web server. They are used
to remember information about the user between sessions. For example, cookies can store user
preferences, session identifiers, and other data needed for website functionality.
In servlets, cookies are used to store information about a user's interaction with a web application.
They help in maintaining session information and user preferences, providing a seamless user
experience.
Setting a cookie in a servlet involves creating a Cookie object and adding it to the response. Here's a
simple example:
1. Create a Cookie: You create a cookie by instantiating the Cookie class with a name and
value.
2. Set Cookie Attributes: Optionally, you can set attributes like maximum age, path, and
domain.
3. Add the Cookie to the Response: Finally, you add the cookie to the response object, so the
browser can store it.
4. Example Code
5. java
6. Copy code
7. import java.io.IOException;
8. import javax.servlet.ServletException;
9. import javax.servlet.http.Cookie;
10. import javax.servlet.http.HttpServlet;
11. import javax.servlet.http.HttpServletRequest;
12. import javax.servlet.http.HttpServletResponse;
13.
14. public class CookieServlet extends HttpServlet {
15. protected void doGet(HttpServletRequest request,
HttpServletResponse response)
16. throws ServletException, IOException {
17. // Create a cookie with name "user" and value "Nitin"
18. Cookie userCookie = new Cookie("user", "Nitin");
19.
20. // Set the cookie to expire in 1 hour (3600 seconds)
21. userCookie.setMaxAge(3600);
22.
23. // Add the cookie to the response
24. response.addCookie(userCookie);
25.
26. // Send a response message to the client
27. response.getWriter().println("Cookie has been set
successfully!");
28. }
29. }
1. Atomicity: Ensures that all operations within a transaction are completed; if not, the
transaction is aborted and no changes are made.
2. Consistency: Ensures that a transaction brings the database from one valid state to another,
maintaining database rules.
4. Durability: Ensures that once a transaction is committed, it will remain so, even in the event
of a system failure.
1. Disable Auto-Commit:
java
Copy code
conn.setAutoCommit(false);
java
Copy code
conn.commit();
java
Copy code
conn.rollback();
1. Start Transaction:
java
Copy code
conn.setAutoCommit(false);
java
Copy code
stmt.executeUpdate("INSERT INTO users (name) VALUES ('John')");
3. Commit if Successful:
java
Copy code
conn.commit();
4. Rollback if Failure:
java
Copy code
conn.rollback();
Example Code
java
Copy code
try {
conn.setAutoCommit(false); // Start transaction
This example demonstrates starting a transaction, committing on success, and rolling back on
failure.
3 a) What is Session Tracking Illustrate the below Session tracking methods
1.Cookies 2. URL Rewriting 3. Hidden form Fields 4 HTTP Session Explain the
different types of directive tags in JSP provide an Example
Session Tracking
Session Tracking is a way to maintain user state and data across multiple requests in a web
application. This is crucial for web applications to remember user interactions and provide a
continuous experience.
1. Cookies:
o Explanation: Cookies are small pieces of data stored on the client's browser.
o Usage: A unique session ID is stored in a cookie, which is sent with every
request to identify the user.
o Example:
java
Copy code
Cookie userCookie = new Cookie("sessionID", "12345");
response.addCookie(userCookie);
2. URL Rewriting:
o Explanation: The session ID is appended to the URL.
o Usage: The server appends the session ID to every URL.
o Example:
java
Copy code
String url = response.encodeURL("dashboard.jsp");
html
Copy code
<form action="dashboard.jsp" method="post">
<input type="hidden" name="sessionID" value="12345">
<input type="submit" value="Submit">
</form>
4. HTTP Session:
o Explanation: The server creates a session object to store user data.
o Usage: The server manages the session and its data.
o Example:
java
Copy code
HttpSession session = request.getSession();
session.setAttribute("username", "JohnDoe");
Directive tags in JSP provide instructions to the JSP container and affect the overall structure
of the servlet generated from the JSP page.
1. Page Directive:
o Purpose: Defines page-dependent attributes.
o Example:
jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8"
%>
2. Include Directive:
o Purpose: Includes a file during the translation phase.
o Example:
jsp
Copy code
<%@ include file="header.jsp" %>
3. Taglib Directive:
o Purpose: Declares a tag library to be used in the JSP page.
o Example:
jsp
Copy code
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"
%>
<html>
<head>
<title>Example Page</title>
</head>
<body>
<h1>Welcome to the Example Page</h1>
<c:out value="${username}" />
</body>
</html>
In this example:
• Page Directive: Sets the page language to Java and content type to HTML.
• Include Directive: Includes the header.jsp file.
• Taglib Directive: Declares the JSTL core library with the prefix "c".
These methods and directives help manage sessions and structure JSP pages effectively.
3b) Evaluate the different types of statement objects with an Example What
is ResultSet How do you Create, Navigate and Retrieve Data from
Result from Resalt
1. Statement:
o Usage: Used for executing simple SQL queries without parameters.
o Example:
java
Copy code
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
2. PreparedStatement:
o Usage: Used for executing precompiled SQL queries with parameters. It is
safer and faster than Statement.
o Example:
java
Copy code
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM
users WHERE id = ?");
pstmt.setInt(1, 1);
ResultSet rs = pstmt.executeQuery();
3. CallableStatement:
o Usage: Used for executing stored procedures in the database.
o Example:
java
Copy code
CallableStatement cstmt = conn.prepareCall("{call
getUserById(?)}");
cstmt.setInt(1, 1);
ResultSet rs = cstmt.executeQuery();
What is ResultSet?
A ResultSet is an object that holds the data retrieved from a database after executing an SQL
query. It allows you to navigate through the rows of data and read the values.
java
Copy code
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
java
Copy code
while (rs.next()) {
// Process each row
}
java
Copy code
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}