Advance Java Imp
Advance Java Imp
5. What are cookies? Explain the use of cookies in session tracking with
example.
Cookies are small pieces of data stored on the client-side by the web browser.
They are used to remember user preferences, session information, and track
user behavior across sessions.
In session tracking, cookies can store a unique session ID that the server can
use to identify the user's session.
Example:
Cookie userCookie = new Cookie("sessionId", "12345");
userCookie.setMaxAge(60*60); // 1 hour
response.addCookie(userCookie);
In this example, a cookie named "sessionId" is created and sent to the client,
allowing the server to track the user's session.
// Client
Socket socket = new Socket("localhost", 8080); // Connects to the server
16. What is session tracking? What are the different ways of session
tracking in servlets?
Session tracking is a mechanism that allows the server to maintain state and
track user interactions across multiple requests. Different ways of session
tracking in servlets include:
1. Cookies: Storing session IDs in cookies on the client-side.
2. URL Rewriting: Appending session IDs to URLs when cookies are not
supported.
3. Hidden Form Fields: Including session IDs as hidden fields in HTML
forms.
4. HttpSession: Using the HttpSession interface to store user-specific
data on the server.
waiter.start();
incrementer.start();
}
}
In this example, the waitForCount method waits until the count reaches a
specified target, while the increment method notifies any waiting threads
when the count is incremented.
Q3. Programs.
1. Write a Java program to display odd numbers between 1 to 100, with
each number displayed after 2 seconds (multithreading).
Ans:-
public class OddNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 100; i += 2) {
System.out.println(i);
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2. Write a servlet application to display "Hello Java" message on the
browser.
Ans:-
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().println("<h1>Hello Java</h1>");
}
}
3. Write a JSP script to display the factorial of a given number.
Ans:-
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<html>
<body>
<form method="post">
Enter a number: <input type="text" name="number">
<input type="submit" value="Calculate Factorial">
</form>
<%
String numberStr = request.getParameter("number");
if (numberStr != null) {
int number = Integer.parseInt(numberStr);
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
out.println("<h2>Factorial of " + number + " is " + factorial + "</h2>");
}
%>
</body>
</html>
4. Write a Java program to display the date of the server machine on the
client's machine.
Ans:-
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/date")
public class DateServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy
HH:mm:ss");
Date date = new Date();
out.println("<h1>Server Date and Time: " + formatter.format(date) +
"</h1>");
}
}
5. Write a JDBC program to insert a record into the student table (Assume
the student table is already created with columns rno, name, percentage).
Ans:-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@WebServlet("/add")
public class AdditionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1 style='color:blue;'>Sum: " + sum + "</h1>");
}
}
13. Write a JDBC program to display the details of employees (eno,
ename, department, sal) whose department is ‘Computer Application’.
Ans:-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
@WebServlet("/employeeDetails")
public class EmployeeDetailsServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<table
border='1'><tr><th>ENO</th><th>Name</th><th>Salary</th><th>Designatio
n</th></tr>");
@WebServlet("/displayName")
public class DisplayNameServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String name = request.getParameter("name");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello, " + name + "!</h1>");
}
}
22. Write a Java program to delete the salary column from the Emp table
(Assume the Emp table with attributes ENo, EName, and salary is already
created).
Ans:-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
2. Connection Interface
The Connection interface in JDBC represents a connection to a specific
database. It provides methods for creating statements, managing
transactions, and closing the connection. Key methods include:
• createStatement(): Creates a Statement object for sending SQL
statements to the database.
• prepareStatement(String sql): Creates a PreparedStatement object for
sending precompiled SQL statements to the database.
• setAutoCommit(boolean autoCommit): Sets the auto-commit mode
for the connection.
• close(): Closes the connection and releases any resources associated
with it.
3. Thread Priorities
Thread priority is a way to indicate the relative importance of a thread
compared to others. In Java, thread priorities range from 1 (lowest) to 10
(highest), with the default priority being 5. You can set the thread priority using
the setPriority(int newPriority) method of the Thread class. Higher priority
threads are more likely to be executed before lower priority threads, but the
actual scheduling is determined by the thread scheduler and may vary across
different platforms.
4. Runnable Interface
The Runnable interface is a functional interface in Java that represents a task
that can be executed by a thread. It contains a single method, run(), which
contains the code that defines the task. Implementing the Runnable interface
allows for more flexible thread management compared to extending the
Thread class, as it enables the separation of the task from the thread itself.
Example:
RunCopy code
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Running in a separate thread.");
}
}
5. Thread Synchronization
Thread synchronization is a mechanism that ensures that two or more
concurrent threads do not simultaneously execute a particular section of
code, which can lead to data inconsistency. In Java, synchronization can be
achieved using the synchronized keyword.
Example:
class Counter {
private int count = 0;
6. Run Method
The run() method is defined in the Runnable interface and contains the code
that is executed when a thread is started. When a thread is created using the
Runnable interface, the run() method must be overridden to define the task
that the thread will perform.
Example:
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running.");
}
}
7. Statement Interface
The Statement interface in JDBC is used to execute SQL queries against a
database. It is suitable for executing simple SQL statements without
parameters. Key methods include:
• executeQuery(String sql): Executes a SQL SELECT statement and
returns a ResultSet object.
• executeUpdate(String sql): Executes a SQL INSERT, UPDATE, or
DELETE statement and returns the number of affected rows.
• close(): Closes the Statement object and releases any resources
associated with it.
8. HttpServlet
HttpServlet is a class in Java that extends the GenericServlet class and is
specifically designed to handle HTTP requests. It provides methods such
as doGet(), doPost(), doPut(), and doDelete() for handling different HTTP
methods. HttpServlet is commonly used in web applications to process client
requests and generate dynamic content.
10. Cookies
Cookies are small pieces of data stored on the client-side by the web browser.
They are used to remember user preferences, session information, and track
user activity across web pages. In Java, cookies can be created and managed
using the javax.servlet.http.Cookie class. Cookies can be set with attributes
such as name, value, expiration time, and path. They are sent from the server
to the client and then sent back to the server with subsequent requests.
Example:
Cookie cookie = new Cookie("username", "JohnDoe");
cookie.setMaxAge(3600); // 1 hour
response.addCookie(cookie);