0% found this document useful (0 votes)
6 views7 pages

Java solution

Uploaded by

neha praveen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
6 views7 pages

Java solution

Uploaded by

neha praveen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 7

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.

Usage of Cookies in Servlets

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.

How to Set a Cookie in a Servlet

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

2b) What is transaction in context of Database and JDBC Explain ACID


properties of transaction How do you start a transaction in jdbe Prioritize the
purpose of Commit) and Rollback() methods in JDBC Describe how to manage
transaction uang the Setauto Commit() method.

Transaction in the Context of Database and JDBC

A transaction in a database context is a sequence of one or more SQL operations executed as a


single unit. Transactions ensure that either all operations are successfully completed, or none of
them are applied, maintaining data integrity.

ACID Properties of Transactions

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.

3. Isolation: Ensures that transactions are executed independently of one another.

4. Durability: Ensures that once a transaction is committed, it will remain so, even in the event
of a system failure.

Starting a Transaction in JDBC

1. Disable Auto-Commit:

java
Copy code
conn.setAutoCommit(false);

Purpose of commit() and rollback() Methods

1. commit(): Saves all changes.

java
Copy code
conn.commit();

2. rollback(): Reverts all changes.

java
Copy code
conn.rollback();

Managing Transactions with setAutoCommit()

1. Start Transaction:

java
Copy code
conn.setAutoCommit(false);

2. Execute SQL Statements:

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

// Execute SQL operations


stmt.executeUpdate("INSERT INTO users (name) VALUES ('John')");
stmt.executeUpdate("UPDATE accounts SET balance = balance - 100 WHERE
user_id = 1");

conn.commit(); // Commit if successful


} catch (SQLException e) {
conn.rollback(); // Rollback if failure
} finally {
conn.setAutoCommit(true); // Reset auto-commit
}

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.

Session Tracking Methods

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");

3. Hidden Form Fields:


o Explanation: Hidden fields in HTML forms carry session information.
o Usage: Session data is included in form fields, submitted with each request.
o Example:

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");

JSP Directive Tags

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"
%>

Example of JSP Directive Tags


jsp
Copy code
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ include file="header.jsp" %>
<%@ 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

Types of Statement Objects in JDBC

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.

Creating, Navigating, and Retrieving Data from ResultSet


1. Creating a ResultSet:
o A ResultSet is created when you execute a query using a Statement,
PreparedStatement, or CallableStatement.
o Example:

java
Copy code
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

2. Navigating the ResultSet:


o Use the next() method to move the cursor to the next row in the ResultSet.
o Example:

java
Copy code
while (rs.next()) {
// Process each row
}

3. Retrieving Data from ResultSet:


o Use getter methods like getInt(), getString(), etc., to retrieve data from
the current row.
o Example:

java
Copy code
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}

You might also like