0% found this document useful (0 votes)
43 views43 pages

Practice Set 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views43 pages

Practice Set 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

1. What is meaning of Synchronous request and Asynchronous request?

Mention the working of

AJAX Write the ways using that we can deploy an application. Write the steps.

2. How can we use pseudo-classes and pseudo-elements in CSS? Provide

examples. What is the meaning of HTTP Status Code. Explain codes 200,

500,400, 403 & 404. Explain jQuery with a suitable example.

3. What is JDBC? Write the steps to fetch data from a

database. What is the purpose of <Java Server Pages

(JSP):setProperty >? What is a bean ? use setter and setter

method in a bean program.

4. With the help of Java script code block which checks the contents entered in a text box of a
form. If the test entered is in the lower case, convert to upper case using the builtin function.

5. Explain the use of JSP/ Servlet in web application. Write down the directory structure of the
application using a servlet.

6. How can we handle the exceptions in Java Server Pages (JSP)? Explain with a suitable

example. How is HTML 4.0 different from HTML 5.0.

7. Why do we use action tags in JSP? Explain with a suitable

example. What is the use of JDBC drivers? Explain different types

of JDBC drivers. How can we create a dedicated error page in Java

Server Pages (JSP)? What are the different types of Javascript

errors?

8. Compare iteration and recursion using Javascript.

9. Why do we use client side scripting? Also explain the importance of server side scripting.

10. Write a Servlet which includes the content of another Servlet (ie data of other servlet is
coming to your servlet).

11. Write a Servlet which forwards request to another servlet

12. Write a Servlet which receives initialization values from web.xml

13. Construct an HTML code using various text

formatting tags List some features of jQuery.

14. Discover the benefits of using JavaScript

15. Outline the various http methods used to send an html form’s data to server in
details.Explain with the help of a program.

16. What is the utility of Spring boot in web programming? Explain its working
17. Write an Servlet / Java Server Pages (JSP) program to calculate Perimeter and area using post
& get method

18. Write a Servlet code snippet using PreparedStatement to insert data into a table in a MySQL/
Oracle database.

19. What is the use of Spring and Spring Boot in web application. Explain with a suitable example

20. Write a Servlet/ Java Server Pages (JSP) program to validate user login. User data is
available in database

21. Write a Servlet/ Java Server Pages (JSP) program to maintain session using session object,
Hidden Form Field and URL Rewriting

22. Explain the use of SPAN in HTML with an example?

23. What is the utility of Spring in web programming?

Explain Create a table inside a table

24. Create an HTML form in which accept marks of 5 subjects and submit marks to a servlet.
Calculate the division of the students based upon following criterion

25. Marks >= 60 First Division


Marks <60 && >= 45 Second
Division Marks <45 && > 33
Third Division
Marks < 33 Fail

26. State with an example the various way to add JavaScript and CSS to HTML.

27. Write a Servlet/ Java Server Pages (JSP) program showing Page Navigation using Send
redirect & RequestDispatcher

28. Develop an application using AJAX and Java Server Pages (JSP) that contains html page that
accept email and check and display a message email is present in the database or not.
Create an user and store data in database

29. How do we use custom tag in Java Server Pages (JSP)? Formulate steps to create a custom tag.

30. Elaborate Document Object Model (DOM) with different JavaScript objects. Write a
program to show system information and navigation information

31. What is the meaning of implicit objects of Java Server Pages (JSP). Show the uses with a
suitable program.

32. Write a JSP/Servlet program to generate the exponential of a user entered value.
33.

34. Write a Java Server Pages (JSP) program to maintain session using session object.

35. Write a JSP/Servlet program using preparedStatement in entering data in MySQL/ Oracle table.
Also display the result

36. Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2, pwd3 and
pwd4 respectively. Write a servlet/ JSP for doing the following. Create a Cookie and add these
four user
37. id’s and passwords to this Cookie. 2. Read the user id and passwords entered in the Login
form and authenticate with the values available in the cookies.

38. Design a table with the following fields: name, password, email-id, and phone
number. Write a program using Servlets or JavaServer Pages (JSP) to connect to the
database, retrieve data from the table, and display it. Additionally, implement
functionality to insert user details into the table when a new user registers by clicking
the submit button on the registration page.

39. Create a webpage that includes various form elements such as Text area, select, text box,
checkboxes, and radio buttons. Implement functionality using JavaScript to display the data
entered by the user.

40. Design a shopping cart for an apparel store with session tracking API.

41. Write a program of Servlet/ JSP in which pass three input using form element and find the
greatest on in main.jsp page. If the greatest number is even then send control to Even.jsp
otherwise odd.jsp

42. Write a program of Servlet/ JSP in which pass three input using form element Name, Age and
Marks. Use cookie / session objects to maintain session and send data to third page and print
all.

43. Explain MVC architecture in web application. Explain with a suitable example.
SOLUTIONS
1. **What is the meaning of Synchronous request and Asynchronous request? Mention the working of
AJAX Write the ways using that we can deploy an application. Write the steps.**

- Synchronous Request: In a synchronous request, the client waits for the server to process the request
and return a response before continuing with other operations. This can lead to blocking behavior,
where the user interface freezes until the request completes.
- Asynchronous Request: In an asynchronous request, the client initiates a request to the server and
continues its execution without waiting for the response. When the server completes processing the
request, it sends the response back, typically triggering a callback function to handle the response.
- AJAX (Asynchronous JavaScript and XML) allows web pages to be updated asynchronously by
exchanging small amounts of data with the server behind the scenes. It works by using a combination of
XMLHttpRequest object in JavaScript and asynchronous callback functions.
- Deployment of an application can be done in various ways:
- Traditional deployment on physical servers or virtual machines.
- Containerization using technologies like Docker, where applications are packaged along with their
dependencies for easy deployment and scalability.
- Cloud deployment on platforms like AWS, Azure, or Google Cloud, offering scalability, reliability, and
various managed services.
- Steps for deployment typically involve:
- Preparing the application for deployment, including configuring any necessary settings and ensuring
dependencies are met.
- Choosing the deployment environment, whether it's physical servers, virtual machines, containers,
or a cloud platform.
- Configuring the deployment environment, such as setting up networking, security, and scaling
options.
- Deploying the application, which may involve uploading files, configuring services, and starting the
application.
- Testing the deployed application to ensure it works as expected in the production environment.

2. **How can we use pseudo-classes and pseudo-elements in CSS? Provide examples. What is the
meaning of HTTP Status Code. Explain codes 200, 500,400, 403 & 404. Explain jQuery with a suitable
example.**

- Pseudo-classes and pseudo-elements in CSS allow styling based on certain criteria or elements that
aren't directly represented in the HTML markup.
- Pseudo-classes select elements based on their state or position, such as `:hover`, `:active`, `:first-
child`, etc.
- Pseudo-elements select parts of an element's content, like `::before`, `::after`, `::first-line`, etc.
```css
/* Example of using pseudo-classes */
a:hover {
color: red;
}
/* Example of using pseudo-elements */
p::first-line {
font-weight: bold;
}
```
- HTTP Status Codes indicate the outcome of an HTTP request.
- 200: OK - Request succeeded and the response body contains the requested data.
- 500: Internal Server Error - Indicates a server-side error occurred while processing the request.
- 400: Bad Request - The server cannot or will not process the request due to a client error.
- 403: Forbidden - The server understood the request but refuses to authorize it.
- 404: Not Found - The requested resource could not be found on the server.
- jQuery is a JavaScript library that simplifies HTML document traversing, event handling, animating,
and AJAX interactions for rapid web development.
```html
<!-- Example of jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
<button>Click me to hide paragraphs</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
```

3. **What is JDBC? Write the steps to fetch data from a database. What is the purpose of <Java Server
Pages (JSP):setProperty >? What is a bean ? use setter and setter method in a bean program.**

- JDBC (Java Database Connectivity) is an API for Java to connect and execute queries with the
database.
- Steps to fetch data from a database using JDBC:
1. Load and register the JDBC driver.
2. Establish a connection to the database.
3. Create a statement object to send SQL queries.
4. Execute the query.
5. Process the result set.
6. Close the connection.
- `<jsp:setProperty>` is a JSP action used to set properties of JavaBeans from request parameters or
other bean properties.
- A JavaBean is a reusable software component modeled after Java classes. It follows specific naming
conventions with getter and setter methods for its properties.
```java
// Example of a JavaBean
public class Person {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}
```

4. **With the help of JavaScript code block which checks the contents entered in a text box of a form. If
the text entered is in lowercase, convert to uppercase using the built-in function.**

```html
<!-- Example HTML form with JavaScript -->
<form>
<input type="text" id="inputText" onblur="convertToUpper()">
</form>
<script>
function convertToUpper() {
var text = document.getElementById("inputText").value;
if (text === text.toLowerCase()) {
document.getElementById("inputText").value = text.toUpperCase();
}
}
</script>
```

5. **Explain the use of JSP/Servlet in a web application. Write down the directory structure of the
application using a servlet.**

- JSP (JavaServer Pages) and Servlets are Java technologies used for developing web applications.
- JSP is used for creating dynamic web pages with embedded Java code.
- Servlets are Java classes that extend the capabilities of servers and respond to HTTP requests.
- Directory structure of a web application using a servlet:
```
/WEB-INF
/classes
- Servlet.class
/lib
- servlet-api.jar
/web.xml
/index.jsp
```

6. **How can we handle exceptions in Java Server Pages (JSP)? Explain with a suitable example. How is
HTML 4.0 different from HTML 5.0.**

- Exceptions in JSP can be handled using the `errorPage` directive or using a try-catch block.
```jsp
<%@ page errorPage="error.jsp" %>
<% try { %>
<!-- Code that may throw an exception -->
<% } catch(Exception e) { %>
<!-- Error handling code -->
<% } %>
```
- HTML 5 introduced several new elements and APIs, including `<canvas>`, `<video>`, `<audio>`,
`<article>`, etc. It also has better support for multimedia and offline applications compared to HTML 4.0.

7. **Why do we use action tags in JSP? Explain with a suitable example. What is the use of JDBC drivers?
Explain different types of JDBC drivers. How can we create a dedicated error page in Java Server Pages
(JSP)? What are the different types of JavaScript errors?**

- Action tags in JSP are used to perform specific actions, such as including another resource, forwarding
requests, handling exceptions, etc.
```jsp
<!-- Example of using action tags -->
<jsp:include page="header.jsp" />
<jsp:forward page="error.jsp" />
```
- JDBC drivers are software components that enable Java applications to interact with databases. There
are four types of JDBC drivers:
1. Type 1: JDBC-ODBC bridge driver (bridge to ODBC)
2. Type 2: Native-API driver (partially Java driver)
3. Type 3: Network Protocol driver (pure Java driver, translates JDBC calls into a DBMS-independent
network protocol)
4. Type 4: Thin driver (fully Java driver, communicates directly with the database server)
- To create a dedicated error page in JSP, you can use the `<error-page>` element in the `web.xml`
deployment descriptor.
```xml
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
```
- Different types of JavaScript errors include:
1. Syntax errors: Errors due to incorrect syntax in JavaScript code.
2. Reference errors: Errors when trying to access a variable or function that does not exist.
3. Type errors: Errors when performing operations on data types that are not supported.
4. Range errors: Errors when trying to manipulate objects with values outside a permissible range.
5. URI errors: Errors when working with URIs, such as incorrect encoding or decoding.

8. **Compare iteration and recursion using JavaScript.**

- Iteration involves repeatedly executing a set of instructions until a specific condition is met, using
constructs like `for` and `while` loops.
- Recursion involves a function calling itself directly or indirectly to solve a problem. Recursion is
generally slower and consumes more memory compared to iteration but can sometimes lead to more
elegant and concise code.
```javascript
// Example of iteration
function factorialIterative(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Example of recursion
function factorialRecursive(n) {
if (n === 0) {
return 1;
}
return n * factorialRecursive(n - 1);
}
```

9. **Why do we use client-side scripting? Also explain the importance of server-side scripting.**

- Client-side scripting is used to enhance the user experience by enabling dynamic interactions within
web pages without requiring round trips to the server. It allows for interactive features like form
validation, animations, and dynamic content updates without reloading the entire page.
- Server-side scripting is important for handling dynamic content generation, data processing, and
business logic execution on the server. It ensures security by keeping sensitive operations and data on
the server, away from the client-side environment where it can be manipulated.
10. **Write a Servlet which includes the content of another Servlet (i.e., data of the other servlet is
coming to your servlet).**

To include the content of another servlet, you can use the `include` method of the `RequestDispatcher`
interface in your servlet.

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class IncludeServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Include the content of AnotherServlet


RequestDispatcher dispatcher = request.getRequestDispatcher("AnotherServlet");
dispatcher.include(request, response);

out.close();
}
}
```

11. **Write a Servlet which forwards a request to another servlet.**

To forward a request to another servlet, you can use the `forward` method of the `RequestDispatcher`
interface.

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ForwardServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Forward the request to AnotherServlet
RequestDispatcher dispatcher = request.getRequestDispatcher("AnotherServlet");
dispatcher.forward(request, response);
}
}
```

12. **Write a Servlet which receives initialization values from web.xml.**

You can retrieve initialization parameters configured in the `web.xml` file using the `getInitParameter`
method of the `ServletConfig` object.

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InitParamServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
ServletConfig config = getServletConfig();
String paramValue = config.getInitParameter("paramName");
PrintWriter out = response.getWriter();
out.println("Initialization Parameter Value: " + paramValue);
}
}
```

13. **Construct an HTML code using various text formatting tags. List some features of jQuery.**

```html
<!DOCTYPE html>
<html>
<head>
<title>Text Formatting Example</title>
</head>
<body>
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<em>This is emphasized text.</em>
<strong>This is strong text.</strong>
<sub>This is subscript text.</sub>
<sup>This is superscript text.</sup>
<u>This is underlined text.</u>
<br>
<blockquote>This is a blockquote.</blockquote>
</body>
</html>
```

Features of jQuery:
- DOM manipulation: jQuery simplifies HTML document traversing, event handling, and animating.
- AJAX support: jQuery provides easy-to-use methods for making asynchronous HTTP requests.
- Effects and animations: jQuery offers a wide range of built-in animations and effects.
- Plugins: jQuery has a vast ecosystem of plugins for extending its functionality.
- Cross-browser compatibility: jQuery handles browser inconsistencies, providing consistent behavior
across different browsers.

Sure, let's continue with the next set of answers:

14. **Discover the benefits of using JavaScript.**

Some benefits of using JavaScript include:


- Interactivity: JavaScript enables dynamic interactions on web pages, enhancing user experience.
- Client-side validation: JavaScript can validate user inputs on the client-side before submitting data to
the server, improving data quality and reducing server load.
- Asynchronous programming: JavaScript supports asynchronous operations, allowing non-blocking
execution and better responsiveness in web applications.
- Rich user interfaces: JavaScript frameworks and libraries like React, Angular, and Vue.js enable the
creation of complex and interactive user interfaces.
- Cross-platform compatibility: JavaScript runs on various platforms and browsers, making it a versatile
choice for web development.
- Community support: JavaScript has a large and active community, offering extensive documentation,
tutorials, and libraries to support developers.

15. **Outline the various HTTP methods used to send an HTML form’s data to the server in detail.
Explain with the help of a program.**

HTML forms can use several HTTP methods to send data to the server, including:
- GET: Sends form data in the URL query string. Suitable for retrieving data from the server.
- POST: Sends form data in the request body. Suitable for sending large amounts of data and sensitive
information.
- PUT: Sends data to update an existing resource on the server.
- DELETE: Sends a request to delete a resource on the server.
- PATCH: Sends a partial update to an existing resource.

Example HTML form using the POST method:


```html
<!DOCTYPE html>
<html>
<head>
<title>Form Submission</title>
</head>
<body>
<form action="process_form.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
```

16. **What is the utility of Spring Boot in web programming? Explain its working.**

Spring Boot simplifies the process of building and deploying web applications by providing a
convention-over-configuration approach and eliminating boilerplate code. Some utilities and benefits of
Spring Boot include:
- Auto-configuration: Spring Boot automatically configures the application based on dependencies and
sensible defaults, reducing manual configuration.
- Embedded servers: Spring Boot includes embedded servers like Tomcat, Jetty, or Undertow, making
it easy to deploy applications as standalone executables.
- Production-ready features: Spring Boot offers built-in support for metrics, health checks, logging, and
monitoring, making applications production-ready out of the box.
- Simplified dependency management: Spring Boot manages dependencies and versions, ensuring
compatibility and reducing dependency conflicts.
- Externalized configuration: Spring Boot allows configuration properties to be externalized, supporting
different environments and reducing the need for recompilation.

The working of Spring Boot involves:


- Creating a Spring Boot application using Spring Initializr or Maven/Gradle.
- Adding dependencies for web, data access, security, etc., as required.
- Writing application code using Spring's annotations and conventions.
- Running the application, which automatically starts the embedded server and deploys the
application.

17. **Write a Servlet / Java Server Pages (JSP) program to calculate Perimeter and area using post & get
method.**

Here's an example of a Servlet program to calculate the perimeter and area of a rectangle using both
POST and GET methods:

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RectangleServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve parameters from the request
int length = Integer.parseInt(request.getParameter("length"));
int width = Integer.parseInt(request.getParameter("width"));

// Calculate perimeter and area


int perimeter = 2 * (length + width);
int area = length * width;

// Set response content type


response.setContentType("text/html");

// Write the results to the response


PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Rectangle Details</h2>");
out.println("Length: " + length + "<br>");
out.println("Width: " + width + "<br>");
out.println("Perimeter: " + perimeter + "<br>");
out.println("Area: " + area + "<br>");
out.println("</body></html>");
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// For GET method, redirect to POST method
response.sendRedirect("rectangle.html");
}
}
```

For the JSP version, you can create a form in `rectangle.jsp` to collect the length and width inputs and
submit them to this servlet.

18. **Write a Servlet code snippet using PreparedStatement to insert data into a table in a
MySQL/Oracle database.**

Here's an example of a Servlet code snippet using PreparedStatement to insert data into a MySQL
database:

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class InsertDataServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve form parameters
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String email = request.getParameter("email");

// Database connection details


String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String password = "password";

try {
// Load MySQL JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Establish connection
Connection con = DriverManager.getConnection(url, username, password);
// Prepare SQL statement
String sql = "INSERT INTO users (name, age, email) VALUES (?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(sql);
// Set parameters
pstmt.setString(1, name);
pstmt.setInt(2, age);
pstmt.setString(3, email);
// Execute query
int rowsAffected = pstmt.executeUpdate();
// Close resources
pstmt.close();
con.close();

// Send response
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Data inserted successfully!</h2>");
out.println("</body></html>");
} catch (Exception e) {
// Handle exceptions
e.printStackTrace();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error inserting
data");
}
}
}
```
19. **What is the use of Spring and Spring Boot in web application? Explain with a suitable example.**

- Spring is a powerful and widely used framework for building enterprise-level Java applications. It
provides comprehensive infrastructure support and various modules for dependency injection, aspect-
oriented programming, data access, transaction management, etc.
- Spring Boot is an extension of the Spring framework that simplifies the setup and configuration of
Spring-based applications. It offers auto-configuration, embedded servers, and opinionated defaults,
allowing developers to quickly create production-ready applications with minimal setup.

Example:
Let's consider building a simple web application for managing tasks using Spring Boot.

- First, we can use Spring Initializr to generate a new Spring Boot project with dependencies for Web
and Thymeleaf (a templating engine).
- We define a Task model class to represent a task with attributes like id, name, description, etc.
- We create a TaskController class to handle HTTP requests and map them to appropriate methods for
tasks management (e.g., listing tasks, adding a new task, updating, or deleting a task).
- We implement CRUD (Create, Read, Update, Delete) operations for tasks using Spring Data JPA for
database access.
- We use Thymeleaf templates to render HTML views for displaying tasks and forms for adding or
editing tasks.

20. **Write a Servlet/ Java Server Pages (JSP) program to validate user login. User data is available in the
database.**

Here's an example of a Servlet program to validate user login using user data stored in a database:

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class LoginServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve form parameters
String username = request.getParameter("username");
String password = request.getParameter("password");

// Database connection details


String url = "jdbc:mysql://localhost:3306/mydatabase";
String dbUsername = "username";
String dbPassword = "password";

try {
// Load MySQL JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Establish connection
Connection con = DriverManager.getConnection(url, dbUsername, dbPassword);
// Prepare SQL statement
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
// Execute query
ResultSet rs = pstmt.executeQuery();
// Check if user exists
if (rs.next()) {
// User authenticated, redirect to success page
response.sendRedirect("success.jsp");
} else {
// User not found, redirect to error page
response.sendRedirect("error.jsp");
}
// Close resources
rs.close();
pstmt.close();
con.close();
} catch (Exception e) {
// Handle exceptions
e.printStackTrace();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error validating
login");
}
}
}
```

21. **Write a Servlet/ Java Server Pages (JSP) program to maintain session using session object, Hidden
Form Field, and URL Rewriting.**

Here's an example demonstrating how to maintain session using Servlets with session object, Hidden
Form Field, and URL Rewriting:

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get session object
HttpSession session = request.getSession();
// Set session attribute
session.setAttribute("username", "John");

// Using hidden form field


PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<form action='hiddenServlet' method='post'>");
out.println("<input type='hidden' name='username' value='John'>");
out.println("<input type='submit' value='Submit'>");
out.println("</form>");

// Using URL Rewriting


out.println("<a href='urlRewriteServlet?username=John'>Click here</a>");
out.println("</body></html>");
}
}
```

Hidden Form Field Servlet:

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HiddenServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get session attribute from hidden form field
String username = request.getParameter("username");
PrintWriter out = response.getWriter();
out.println("Username from hidden form field: " + username);
}
}
```

URL Rewrite Servlet:

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class UrlRewriteServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get session attribute from URL rewriting
String username = request.getParameter("username");
PrintWriter out = response.getWriter();
out.println("Username from URL rewriting: " + username);
}
}
```

This demonstrates three different methods to maintain session data in a servlet-based web
application.

22. **Explain the use of SPAN in HTML with an example?**

The `<span>` element is an inline container used to group inline elements and apply styles to a specific
part of the text without affecting the layout of the document.

Example:

```html
<!DOCTYPE html>
<html>
<head>
<title>Span Example</title>
<style>
.highlight {
color: red;
}
</style>
</head>
<body>
<p>This is a <span class="highlight">highlighted</span> text.</p>
</body>
</html>
```

In this example, the text "highlighted" inside the `<span>` element will be displayed in red color due to
the `.highlight` CSS class.

23. **What is the utility of Spring in web programming? Explain Create a table inside a table.**

The Spring framework offers various utilities and features that greatly simplify web programming
tasks. Some of its utilities include:

- Dependency Injection (DI) and Inversion of Control (IoC): Spring provides a powerful DI container
that manages the dependencies of application components, making it easier to develop loosely coupled
and highly testable components.
- Aspect-Oriented Programming (AOP): Spring's AOP module allows developers to apply cross-cutting
concerns, such as logging, security, and transaction management, to multiple components in a modular
and reusable way.
- MVC Framework: Spring MVC provides a robust and flexible model-view-controller architecture for
building web applications. It offers features like request mapping, data binding, form validation, and
more.
- Data Access: Spring offers support for JDBC, JPA, Hibernate, and other data access technologies,
making it easier to work with databases and perform data access operations.
- Security: Spring Security provides comprehensive authentication, authorization, and protection
against common security vulnerabilities, helping developers secure their web applications.
- Testing: Spring's testing support simplifies unit testing, integration testing, and mocking of Spring
components, enabling developers to write reliable and maintainable tests.

Example of creating a table inside a table in HTML:

```html
<!DOCTYPE html>
<html>
<head>
<title>Nested Table Example</title>
</head>
<body>
<table border="1">
<tr>
<td>Outer Table Cell 1</td>
<td>Outer Table Cell 2</td>
</tr>
<tr>
<td colspan="2">
<table border="1">
<tr>
<td>Inner Table Cell 1</td>
<td>Inner Table Cell 2</td>
</tr>
<tr>
<td>Inner Table Cell 3</td>
<td>Inner Table Cell 4</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
```

In this example, we have an outer table with two rows. The second row contains a single cell spanning
two columns, which contains another nested table with its own rows and cells.

24. **Create an HTML form that accepts marks of 5 subjects and submits marks to a servlet. Calculate
the division of the students based upon the following criterion:**
- Marks >= 60: First Division
- Marks < 60 && >= 45: Second Division
- Marks < 45 && > 33: Third Division
- Marks <= 33: Fail

Here's an example of an HTML form that collects marks of 5 subjects and submits them to a servlet for
division calculation:

```html
<!DOCTYPE html>
<html>
<head>
<title>Division Calculator</title>
</head>
<body>
<h2>Enter Marks of 5 Subjects</h2>
<form action="DivisionCalculatorServlet" method="post">
Subject 1: <input type="number" name="subject1" required><br>
Subject 2: <input type="number" name="subject2" required><br>
Subject 3: <input type="number" name="subject3" required><br>
Subject 4: <input type="number" name="subject4" required><br>
Subject 5: <input type="number" name="subject5" required><br>
<input type="submit" value="Calculate Division">
</form>
</body>
</html>
```

In this HTML form, the user is prompted to enter marks for 5 subjects. The form is submitted to a
servlet named `DivisionCalculatorServlet` using the POST method.

Here's an example of a servlet (`DivisionCalculatorServlet`) that calculates the division based on the
entered marks:

```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DivisionCalculatorServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve marks from request parameters
int subject1 = Integer.parseInt(request.getParameter("subject1"));
int subject2 = Integer.parseInt(request.getParameter("subject2"));
int subject3 = Integer.parseInt(request.getParameter("subject3"));
int subject4 = Integer.parseInt(request.getParameter("subject4"));
int subject5 = Integer.parseInt(request.getParameter("subject5"));

// Calculate total marks


int totalMarks = subject1 + subject2 + subject3 + subject4 + subject5;

// Calculate division
String division;
if (totalMarks >= 60) {
division = "First Division";
} else if (totalMarks >= 45) {
division = "Second Division";
} else if (totalMarks > 33) {
division = "Third Division";
} else {
division = "Fail";
}

// Set response content type


response.setContentType("text/html");

// Write the result to the response


PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2>Division Calculator Result</h2>");
out.println("Total Marks: " + totalMarks + "<br>");
out.println("Division: " + division + "<br>");
out.println("</body></html>");
}
}
```

This servlet calculates the total marks obtained and determines the division based on the total marks.
The result is then displayed in the response.

25. **State with an example the various ways to add JavaScript and CSS to HTML.**

There are several ways to add JavaScript and CSS to HTML:

1. **Inline**: Directly within HTML elements using the `style` attribute for CSS and the `script` tag for
JavaScript.
```html
<p style="color: red;">This is a paragraph with inline CSS.</p>
<script>
console.log("This is inline JavaScript.");
</script>
```

2. **Internal**: Within the `<head>` or `<body>` section of the HTML document using `<style>` tag for
CSS and `<script>` tag for JavaScript.
```html
<head>
<style>
p{
color: blue;
}
</style>
</head>
<body>
<p>This is a paragraph with internal CSS.</p>
<script>
console.log("This is internal JavaScript.");
</script>
</body>
```

3. **External**: By linking to an external CSS file using the `<link>` tag and to an external JavaScript
file using the `<script>` tag.
```html
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="script.js"></script>
</head>
```

4. **CDN (Content Delivery Network)**: Linking to external libraries or frameworks hosted on a CDN.
```html
<head>
<script src="https://cdn.example.com/jquery.min.js"></script>
</head>
```

5. **Asynchronous Loading**: Adding the `async` attribute to the `<script>` tag to load JavaScript
asynchronously.
```html
<script async src="script.js"></script>
```

6. **Deferred Loading**: Adding the `defer` attribute to the `<script>` tag to defer script execution
until the document has finished parsing.
```html
<script defer src="script.js"></script>
```

26. **Write a Servlet/ Java Server Pages (JSP) program showing Page Navigation using Send redirect &
RequestDispatcher.**

Here's an example demonstrating page navigation using both `sendRedirect` and `RequestDispatcher`
in a Servlet:
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class NavigationServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Page navigation using sendRedirect
response.sendRedirect("page1.jsp");

// Page navigation using RequestDispatcher


RequestDispatcher dispatcher = request.getRequestDispatcher("page2.jsp");
dispatcher.forward(request, response);
}
}
```

In this example, `sendRedirect` is used to redirect the client to `page1.jsp`, while `RequestDispatcher`
is used to forward the request to `page2.jsp`.

Remember that `sendRedirect` sends a new request to the client, while `RequestDispatcher.forward`
performs an internal forward within the server.

27. **Develop an application using AJAX and Java Server Pages (JSP) that contains an HTML page that
accepts an email and checks and displays a message if the email is present in the database or not. Create
a user and store data in the database.**

Here's an example of how you can implement an AJAX-based application using Java Server Pages (JSP)
to check if an email exists in a database:

**HTML Page (`index.html`):**


```html
<!DOCTYPE html>
<html>
<head>
<title>Email Checker</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#checkEmail").click(function(){
var email = $("#email").val();
$.ajax({
type: "POST",
url: "CheckEmail.jsp",
data: {email: email},
success: function(response){
$("#result").html(response);
}
});
});
});
</script>
</head>
<body>
<h2>Email Checker</h2>
<input type="text" id="email" placeholder="Enter email">
<button id="checkEmail">Check</button>
<div id="result"></div>
</body>
</html>
```

**JSP Page (`CheckEmail.jsp`):**


```jsp
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page contentType="text/html;charset=UTF-8" %>
<%!
public boolean isEmailExists(String email) {
// Database connection details
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String password = "password";
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// Establish database connection
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, username, password);
// Check if email exists in the database
String sql = "SELECT * FROM users WHERE email=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, email);
rs = pstmt.executeQuery();
if (rs.next()) {
return true; // Email exists
} else {
return false; // Email does not exist
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
// Close resources
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (con != null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
<% String email = request.getParameter("email");
if (email != null && !email.isEmpty()) {
if (isEmailExists(email)) {
out.println("<p>Email exists in the database.</p>");
} else {
out.println("<p>Email does not exist in the database.</p>");
}
} else {
out.println("<p>Please enter an email.</p>");
}
%>
```

This application allows users to enter an email, and upon clicking the "Check" button, it sends an AJAX
request to the `CheckEmail.jsp` page, which checks if the email exists in the database and displays the
result on the HTML page.

Make sure to replace `"jdbc:mysql://localhost:3306/mydatabase"`, `"username"`, and `"password"`


with your MySQL database details.

Additionally, you need to have a table named `users` in your database with a column named `email` to
store user email addresses.

28. **How do we use custom tags in Java Server Pages (JSP)? Formulate steps to create a custom tag.**

Custom tags in JSP allow developers to create their own tags, encapsulating certain behaviors or
functionalities, and then use them within JSP pages. Here are the steps to create a custom tag:

1. **Define the Tag Handler Class**: Create a Java class that extends
`javax.servlet.jsp.tagext.SimpleTagSupport` or implements `javax.servlet.jsp.tagext.Tag`. This class will
contain the logic of your custom tag.

2. **Override the doTag() Method**: If you're extending `SimpleTagSupport`, override the `doTag()`
method to define the behavior of your tag. If you're implementing `Tag`, you need to implement the
`doStartTag()`, `doEndTag()`, and optionally, `doAfterBody()` methods.

3. **Declare the Tag in a Tag Library Descriptor (TLD)**: Create a TLD file (usually with a `.tld`
extension) where you define the custom tag. This file specifies the tag's name, its handler class,
attributes, and other details.

4. **Add the Tag Library to the Web Application**: Include the TLD file in your web application's
`WEB-INF` directory.

5. **Use the Custom Tag in JSP Pages**: Import the tag library in your JSP page using the `<%@ taglib
%>` directive, and then use the custom tag in your JSP code.

Here's an example illustrating these steps:

**1. Define the Tag Handler Class (`HelloTag.java`):**


```java
package com.example.tags;

import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;

public class HelloTag extends SimpleTagSupport {


public void doTag() throws IOException {
getJspContext().getOut().println("Hello, custom tag!");
}
}
```

**2. Declare the Tag in a TLD File (`hello.tld`):**


```xml
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
jsptaglibrary_2_1.xsd"
version="2.1">

<tlib-version>1.0</tlib-version>
<short-name>hello</short-name>
<uri>/WEB-INF/hello.tld</uri>

<tag>
<name>hello</name>
<tag-class>com.example.tags.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>

</taglib>
```

**3. Add the Tag Library to the Web Application:**


Save `hello.tld` file in the `WEB-INF` directory of your web application.

**4. Use the Custom Tag in JSP Pages:**


In your JSP page, import the tag library and use the custom tag:
```jsp
<%@ taglib prefix="hello" uri="/WEB-INF/hello.tld" %>
<!DOCTYPE html>
<html>
<head>
<title>Custom Tag Example</title>
</head>
<body>
<hello:hello/>
</body>
</html>
```

When you access the JSP page, it will execute the custom tag and display "Hello, custom tag!" in the
output.

This is a basic example; custom tags can have attributes, body content, and more complex behaviors
depending on your requirements.

29. **Elaborate Document Object Model (DOM) with different JavaScript objects. Write a program to
show system information and navigation information.**

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It
represents the structure of a document as a tree of objects, where each node in the tree corresponds to
a part of the document (such as elements, attributes, or text). JavaScript provides various objects to
interact with the DOM and manipulate the document dynamically.

Here's a simple program to demonstrate accessing system information and navigation information
using DOM:

```html
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
<script>
// Function to display system information
function displaySystemInfo() {
var info = "User Agent: " + navigator.userAgent + "<br>";
info += "Platform: " + navigator.platform + "<br>";
info += "Cookies Enabled: " + navigator.cookieEnabled + "<br>";
document.getElementById("system-info").innerHTML = info;
}

// Function to display navigation information


function displayNavigationInfo() {
var info = "Current URL: " + window.location.href + "<br>";
info += "Hostname: " + window.location.hostname + "<br>";
info += "Protocol: " + window.location.protocol + "<br>";
document.getElementById("navigation-info").innerHTML = info;
}
</script>
</head>
<body>
<h2>System Information</h2>
<button onclick="displaySystemInfo()">Show System Info</button>
<div id="system-info"></div>

<h2>Navigation Information</h2>
<button onclick="displayNavigationInfo()">Show Navigation Info</button>
<div id="navigation-info"></div>
</body>
</html>
```

In this program:
- The `navigator` object provides information about the browser and system.
- The `window.location` object provides information about the current URL and navigation.
- Two JavaScript functions, `displaySystemInfo()` and `displayNavigationInfo()`, are defined to access
the respective information and update the HTML elements accordingly.
- When the buttons are clicked, these functions are called, and the relevant information is displayed
on the webpage.

This example demonstrates how to use JavaScript to access system and navigation information using
the DOM.
30. **What is the meaning of implicit objects of Java Server Pages (JSP)? Show their uses with a suitable
program.**

In JSP, implicit objects are objects that are automatically available to the developer without being
explicitly declared. These objects provide access to various aspects of the JSP environment, such as
request parameters, session attributes, application context, etc.

Here are some commonly used implicit objects in JSP:

- **request**: Represents the client's request to the server. It provides methods to retrieve
parameters sent by the client, such as form data, query parameters, and cookies.

- **response**: Represents the server's response to the client. It provides methods to set response
headers, cookies, and send content back to the client.

- **session**: Represents the user's session, allowing storage of session attributes that persist across
multiple requests from the same client.

- **application**: Represents the servlet context, providing access to application-wide resources and
attributes.

- **out**: Represents the output stream used to send content to the client's browser.

- **config**: Provides access to the servlet configuration parameters defined in the web.xml file.

- **pageContext**: Provides access to various objects and services related to the current JSP page,
such as request, response, session, etc.

Here's a simple example demonstrating the use of implicit objects in a JSP page:

```jsp
<%@ page language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Implicit Objects Example</title>
</head>
<body>
<h2>Request Parameters:</h2>
<p>Username: <%= request.getParameter("username") %></p>
<p>Password: <%= request.getParameter("password") %></p>

<h2>Session Attributes:</h2>
<p>User ID: <%= session.getAttribute("userId") %></p>
<p>User Name: <%= session.getAttribute("userName") %></p>

<h2>Application Context:</h2>
<p>Context Path: <%= application.getContextPath() %></p>

<h2>Response:</h2>
<% response.setContentType("text/html"); %>
<% response.getWriter().println("Hello from the server!"); %>
</body>
</html>
```

In this example, we're accessing request parameters, session attributes, application context, and
response object using implicit objects like `request`, `session`, `application`, and `response`.

31. **Write a JSP/Servlet program to generate the exponential of a user-entered value.**

Here's a simple JSP/Servlet program that calculates the exponential of a user-entered value:

**index.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Exponential Calculator</title>
</head>
<body>
<h2>Exponential Calculator</h2>
<form action="ExponentialCalculatorServlet" method="post">
Enter a number: <input type="number" name="number" required><br>
Enter the power: <input type="number" name="power" required><br>
<input type="submit" value="Calculate Exponential">
</form>
</body>
</html>
```

**ExponentialCalculatorServlet.java:**
```java
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("/ExponentialCalculatorServlet")
public class ExponentialCalculatorServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
int number = Integer.parseInt(request.getParameter("number"));
int power = Integer.parseInt(request.getParameter("power"));
double result = Math.pow(number, power);

response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h2>Result:</h2>");
response.getWriter().println("Exponential of " + number + " raised to the power of " + power + "
is: " + result);
response.getWriter().println("</body></html>");
}
}
```

In this program:
- The `index.jsp` file presents a form to the user to enter a number and its power.
- The form submits the data to `ExponentialCalculatorServlet`.
- In `ExponentialCalculatorServlet`, the values are retrieved from the request parameters, and the
exponential is calculated using the `Math.pow()` method.
- The result is then sent back to the client's browser as an HTML response.

This program allows users to calculate the exponential of a number with a specified power.

32. **Write a JSP/Servlet program to maintain a session using the session object.**

Below is a simple example demonstrating how to create and maintain a session using JSP/Servlet:

**index.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Session Example</title>
</head>
<body>
<h2>Session Example</h2>
<form action="SessionServlet" method="post">
Enter your name: <input type="text" name="name" required><br>
<input type="submit" value="Start Session">
</form>
</body>
</html>
```

**SessionServlet.java:**
```java
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;
import javax.servlet.http.HttpSession;

@WebServlet("/SessionServlet")
public class SessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name = request.getParameter("name");
HttpSession session = request.getSession();
session.setAttribute("name", name);

response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h2>Session Created</h2>");
response.getWriter().println("Welcome, " + name + "!<br>");
response.getWriter().println("<a href='DisplaySession'>Display Session</a>");
response.getWriter().println("</body></html>");
}
}
```

**DisplaySession.java:**
```java
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;
import javax.servlet.http.HttpSession;

@WebServlet("/DisplaySession")
public class DisplaySession extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
String name = (String) session.getAttribute("name");
response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h2>Session Details</h2>");
response.getWriter().println("Name: " + name + "<br>");
response.getWriter().println("</body></html>");
} else {
response.getWriter().println("Session not found.");
}
}
}
```

In this example:
- `index.jsp` presents a form to the user to enter their name.
- When the form is submitted, the `SessionServlet` creates a session and stores the user's name in the
session.
- It then displays a message confirming the session creation and provides a link to display the session
details.
- `DisplaySession` retrieves the session and displays the stored name.

This demonstrates the basic usage of session management in JSP/Servlet.

34. **Write a Java Server Pages (JSP) program to maintain session using the session object.**

Here's a simple example of a JSP program that demonstrates how to maintain a session using the
session object:

**session_example.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Session Example</title>
</head>
<body>
<h2>Session Example</h2>
<%
// Get the session object
HttpSession session = request.getSession();

// Check if the session already contains a name attribute


String name = (String) session.getAttribute("name");

if (name != null) {
// If the name attribute exists, display a welcome message
%>
<p>Welcome back, <%= name %>!</p>
<%
} else {
// If the name attribute doesn't exist, prompt the user to enter their name
%>
<form action="SetSession" method="post">
Enter your name: <input type="text" name="name" required>
<input type="submit" value="Start Session">
</form>
<%
}
%>
</body>
</html>
```

**SetSession.java (Servlet):**
```java
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;
import javax.servlet.http.HttpSession;

@WebServlet("/SetSession")
public class SetSession extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get the name parameter from the form
String name = request.getParameter("name");

// Create or retrieve the session object


HttpSession session = request.getSession();

// Set the name attribute in the session


session.setAttribute("name", name);

// Redirect the user back to the session_example.jsp page


response.sendRedirect("session_example.jsp");
}
}
```

In this example:
- The `session_example.jsp` page checks if the session already contains a name attribute. If it does, it
displays a welcome message; otherwise, it prompts the user to enter their name.
- When the user submits their name, the `SetSession` servlet sets the name attribute in the session
and redirects the user back to the `session_example.jsp` page.
- The session will persist across multiple requests until it expires or is invalidated.

This demonstrates how to maintain a session using the session object in a JSP program.

35. **Write a JSP/Servlet program using PreparedStatement to enter data into a MySQL/Oracle table
and display the result.**

Below is an example of a JSP/Servlet program that inserts data into a MySQL database table using
PreparedStatement and then displays the inserted data:

**insert_data.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Insert Data</title>
</head>
<body>
<h2>Insert Data into Database</h2>
<form action="InsertDataServlet" method="post">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
<input type="submit" value="Insert Data">
</form>
</body>
</html>
```

**InsertDataServlet.java:**
```java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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("/InsertDataServlet")
public class InsertDataServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get parameters from the form
String name = request.getParameter("name");
String email = request.getParameter("email");

// Database connection details


String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String password = "password";

// SQL query to insert data


String sql = "INSERT INTO users (name, email) VALUES (?, ?)";

try (
// Establish database connection
Connection connection = DriverManager.getConnection(url, username, password);
// Create a PreparedStatement with SQL query
PreparedStatement pstmt = connection.prepareStatement(sql);
){
// Set parameters in the PreparedStatement
pstmt.setString(1, name);
pstmt.setString(2, email);

// Execute the query to insert data


int rowsInserted = pstmt.executeUpdate();

// Display success or failure message


if (rowsInserted > 0) {
response.getWriter().println("Data inserted successfully.");
} else {
response.getWriter().println("Failed to insert data.");
}
} catch (SQLException e) {
e.printStackTrace();
response.getWriter().println("Error: " + e.getMessage());
}
}
}
```

In this example:
- The `insert_data.jsp` page contains a form where users can enter their name and email.
- When the form is submitted, the `InsertDataServlet` servlet retrieves the form parameters and
inserts the data into a MySQL database table named `users`.
- PreparedStatement is used to prevent SQL injection attacks by providing parameterized queries.
- The servlet displays a success or failure message based on the result of the insert operation.

Ensure you replace `"jdbc:mysql://localhost:3306/mydatabase"`, `"username"`, and `"password"` with


your MySQL database details.
36. **Assume four users user1, user2, user3, and user4 having the passwords pwd1, pwd2, pwd3, and
pwd4 respectively. Write a servlet/JSP for doing the following:**
1. Create a Cookie and add these four user IDs and passwords to this Cookie.
2. Read the user IDs and passwords entered in the Login form and authenticate with the values
available in the cookies.

Below is an example of how you can implement this functionality using a servlet:

**LoginServlet.java:**
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String userId = request.getParameter("userId");
String password = request.getParameter("password");

// Retrieve the cookie containing user IDs and passwords


Cookie[] cookies = request.getCookies();
String storedPassword = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(userId)) {
storedPassword = cookie.getValue();
break;
}
}
}

// Authenticate the user


if (storedPassword != null && storedPassword.equals(password)) {
response.getWriter().println("Login successful");
} else {
response.getWriter().println("Invalid credentials");
}
}
}
```

**login.html:**
```html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="LoginServlet" method="post">
User ID: <input type="text" name="userId" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
</body>
</html>
```

**Remember to create cookies when the servlet container starts up and assign them to users. For
brevity, that part is not included here.**

This example demonstrates how to read user IDs and passwords entered in a login form and
authenticate with the values available in cookies.

37. **Design a table with the following fields: name, password, email-id, and phone number. Write a
program using Servlets or JavaServer Pages (JSP) to connect to the database, retrieve data from the
table, and display it. Additionally, implement functionality to insert user details into the table when a
new user registers by clicking the submit button on the registration page.**

Below is an example of how you can achieve this using Servlets and JSP:

**registration.html:**
```html
<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<h2>Registration</h2>
<form action="RegistrationServlet" method="post">
Name: <input type="text" name="name" required><br>
Password: <input type="password" name="password" required><br>
Email: <input type="email" name="email" required><br>
Phone Number: <input type="text" name="phone" required><br>
<input type="submit" value="Register">
</form>
</body>
</html>
```

**RegistrationServlet.java:**
```java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");

// Database connection details


String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String dbPassword = "password";

Connection connection = null;


PreparedStatement pstmt = null;

try {
// Establish database connection
connection = DriverManager.getConnection(url, username, dbPassword);

// Prepare SQL statement to insert user details


String sql = "INSERT INTO users (name, password, email, phone) VALUES (?, ?, ?, ?)";
pstmt = connection.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, password);
pstmt.setString(3, email);
pstmt.setString(4, phone);

// Execute the SQL statement to insert user details


pstmt.executeUpdate();

// Display success message


response.getWriter().println("Registration successful");
} catch (SQLException e) {
e.printStackTrace();
response.getWriter().println("Error: " + e.getMessage());
} finally {
// Close the PreparedStatement and Connection
try {
if (pstmt != null) pstmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```

**This code snippet assumes you have a table named `users` with fields `name`, `password`, `email`,
and `phone` in your database.**
This example demonstrates how to register a user by inserting their details into a database table using
Servlets.

Sure, let's continue:

38. **Create a webpage that includes various form elements such as Text area, select, text box,
checkboxes, and radio buttons. Implement functionality using JavaScript to display the data entered by
the user.**

Below is an example of how you can achieve this using HTML and JavaScript:

**index.html:**
```html
<!DOCTYPE html>
<html>
<head>
<title>Form Elements</title>
<script>
function displayFormData() {
// Get form elements
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var gender = document.querySelector('input[name="gender"]:checked').value;
var country = document.getElementById("country").value;
var hobbies = document.querySelectorAll('input[name="hobby"]:checked');
var hobbyList = [];
for (var i = 0; i < hobbies.length; i++) {
hobbyList.push(hobbies[i].value);
}
var message = document.getElementById("message").value;

// Display data
var displayArea = document.getElementById("displayArea");
displayArea.innerHTML = "<h2>Form Data</h2>";
displayArea.innerHTML += "<p>Name: " + name + "</p>";
displayArea.innerHTML += "<p>Email: " + email + "</p>";
displayArea.innerHTML += "<p>Gender: " + gender + "</p>";
displayArea.innerHTML += "<p>Country: " + country + "</p>";
displayArea.innerHTML += "<p>Hobbies: " + hobbyList.join(", ") + "</p>";
displayArea.innerHTML += "<p>Message: " + message + "</p>";
}
</script>
</head>
<body>
<h2>Form Elements</h2>
<form>
Name: <input type="text" id="name"><br>
Email: <input type="email" id="email"><br>
Gender: <input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br>
Country: <select id="country">
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="Canada">Canada</option>
</select><br>
Hobbies: <input type="checkbox" name="hobby" value="Reading"> Reading
<input type="checkbox" name="hobby" value="Traveling"> Traveling
<input type="checkbox" name="hobby" value="Sports"> Sports<br>
Message: <textarea id="message"></textarea><br>
<input type="button" value="Submit" onclick="displayFormData()">
</form>
<div id="displayArea"></div>
</body>
</html>
```

In this example:
- Various form elements such as text box, email, radio buttons, select, checkboxes, and text area are
included in the form.
- JavaScript function `displayFormData()` is defined to retrieve the values entered by the user and
display them in a designated area on the webpage.
- When the user clicks the "Submit" button, the `displayFormData()` function is called, which retrieves
the form data and dynamically updates the display area with the entered data.

This example demonstrates how to implement functionality using JavaScript to display data entered by
the user in a web form.

39. **Design a shopping cart for an apparel store with session tracking API.**

Below is an example of how you can design a basic shopping cart for an apparel store using session
tracking in Java servlets:

**index.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Apparel Store</title>
</head>
<body>
<h2>Welcome to Apparel Store</h2>
<a href="browse.jsp">Browse Items</a><br>
<a href="viewCart.jsp">View Cart</a>
</body>
</html>
```

**browse.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Browse Items</title>
</head>
<body>
<h2>Browse Items</h2>
<form action="AddToCartServlet" method="post">
<input type="hidden" name="item" value="Shirt">
<input type="submit" value="Add Shirt to Cart">
</form>
<form action="AddToCartServlet" method="post">
<input type="hidden" name="item" value="Pants">
<input type="submit" value="Add Pants to Cart">
</form>
</body>
</html>
```

**AddToCartServlet.java:**
```java
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;
import javax.servlet.http.HttpSession;

@WebServlet("/AddToCartServlet")
public class AddToCartServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String item = request.getParameter("item");

// Get or create session


HttpSession session = request.getSession(true);

// Add item to cart


if (session.getAttribute("cart") == null) {
session.setAttribute("cart", new StringBuilder());
}
StringBuilder cart = (StringBuilder) session.getAttribute("cart");
cart.append(item).append(", ");

response.sendRedirect("browse.jsp");
}
}
```

**viewCart.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>View Cart</title>
</head>
<body>
<h2>Shopping Cart</h2>
<%
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("cart") != null) {
StringBuilder cart = (StringBuilder) session.getAttribute("cart");
String[] items = cart.toString().split(", ");
out.println("<ul>");
for (String item : items) {
out.println("<li>" + item + "</li>");
}
out.println("</ul>");
} else {
out.println("Your cart is empty.");
}
%>
</body>
</html>
```

This example demonstrates a simple shopping cart implementation for an apparel store using session
tracking in Java servlets. Users can browse items, add them to the cart, and view the cart contents.

40. **Write a program of Servlet/JSP in which pass three input using form element and find the greatest
one in main.jsp page. If the greatest number is even then send control to Even.jsp otherwise Odd.jsp.**

Below is an example of how you can achieve this using Servlets and JSP:

**index.html:**
```html
<!DOCTYPE html>
<html>
<head>
<title>Find Greatest Number</title>
</head>
<body>
<h2>Find Greatest Number</h2>
<form action="GreatestNumberServlet" method="post">
Enter first number: <input type="text" name="num1" required><br>
Enter second number: <input type="text" name="num2" required><br>
Enter third number: <input type="text" name="num3" required><br>
<input type="submit" value="Find Greatest Number">
</form>
</body>
</html>
```

**GreatestNumberServlet.java:**
```java
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("/GreatestNumberServlet")
public class GreatestNumberServlet 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 num3 = Integer.parseInt(request.getParameter("num3"));

int greatest = Math.max(num1, Math.max(num2, num3));


request.setAttribute("greatest", greatest);

if (greatest % 2 == 0) {
request.getRequestDispatcher("Even.jsp").forward(request, response);
} else {
request.getRequestDispatcher("Odd.jsp").forward(request, response);
}
}
}
```

**Even.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Even Number</title>
</head>
<body>
<h2>Even Number</h2>
<p>The greatest number is <%= request.getAttribute("greatest") %> and it is even.</p>
</body>
</html>
```

**Odd.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Odd Number</title>
</head>
<body>
<h2>Odd Number</h2>
<p>The greatest number is <%= request.getAttribute("greatest") %> and it is odd.</p>
</body>
</html>
```

In this example:
- The user enters three numbers in the form.
- When the form is submitted, the `GreatestNumberServlet` servlet calculates the greatest number
among the three.
- If the greatest number is even, the control is forwarded to `Even.jsp`; otherwise, it is forwarded to
`Odd.jsp`.

This example demonstrates how to find the greatest number among three inputs and forward the
control to different JSP pages based on certain conditions.
41. **Write a program of Servlet/JSP in which pass three input using form element Name, Age, and
Marks. Use cookie/session objects to maintain session and send data to the third page and print all.**

Below is an example of how you can achieve this using Servlets and JSP:

**index.html:**
```html
<!DOCTYPE html>
<html>
<head>
<title>Form Inputs</title>
</head>
<body>
<h2>Enter Details</h2>
<form action="SaveDetailsServlet" method="post">
Name: <input type="text" name="name" required><br>
Age: <input type="text" name="age" required><br>
Marks: <input type="text" name="marks" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
```

**SaveDetailsServlet.java:**
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/SaveDetailsServlet")
public class SaveDetailsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name = request.getParameter("name");
String age = request.getParameter("age");
String marks = request.getParameter("marks");

// Using session to store data


HttpSession session = request.getSession();
session.setAttribute("name", name);
session.setAttribute("age", age);
session.setAttribute("marks", marks);

// Using cookies to store data


Cookie nameCookie = new Cookie("name", name);
Cookie ageCookie = new Cookie("age", age);
Cookie marksCookie = new Cookie("marks", marks);
response.addCookie(nameCookie);
response.addCookie(ageCookie);
response.addCookie(marksCookie);

response.sendRedirect("display.jsp");
}
}
```

**display.jsp:**
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Display Details</title>
</head>
<body>
<h2>Details</h2>
<%
String name = (String) session.getAttribute("name");
String age = (String) session.getAttribute("age");
String marks = (String) session.getAttribute("marks");

out.println("Name: " + name + "<br>");


out.println("Age: " + age + "<br>");
out.println("Marks: " + marks + "<br>");
%>
</body>
</html>
```

In this example:
- The user enters their name, age, and marks in the form.
- When the form is submitted, the `SaveDetailsServlet` servlet stores the data in both session and
cookies.
- The control is then forwarded to `display.jsp`, where the stored data is retrieved from session and
displayed.

This example demonstrates how to use session and cookies to maintain user data across multiple
pages in a Servlet/JSP application.

42. **Explain MVC architecture in web application. Explain with a suitable example.**

MVC (Model-View-Controller) is a software architectural pattern used for designing web applications. It
separates an application into three interconnected components: Model, View, and Controller. Each of
these components has a specific role in managing different aspects of the application.

- **Model:** The Model represents the application's data and business logic. It encapsulates the data
and behavior of the application and provides an interface to access and manipulate the data. In MVC,
the Model notifies the View of any changes in the data, allowing the View to update itself accordingly.

- **View:** The View represents the presentation layer of the application. It is responsible for
rendering the user interface and displaying the data to the user. Views are typically implemented using
HTML, CSS, and JavaScript. In MVC, the View receives data from the Model and presents it to the user in
an appropriate format.

- **Controller:** The Controller acts as an intermediary between the Model and the View. It receives
user input from the View, processes it, and interacts with the Model to perform any necessary actions.
The Controller updates the Model based on the user input and selects an appropriate View to display the
results. In MVC, the Controller handles user requests, processes business logic, and determines the
appropriate response.

**Example:**

Let's consider a simple example of a web application for managing a list of tasks:

- **Model:** The Model component manages the data related to tasks, such as task names,
descriptions, and statuses. It provides methods to add, edit, delete, and retrieve tasks from a database.

- **View:** The View component consists of HTML templates that define the layout and appearance
of the user interface. It includes pages for displaying a list of tasks, creating/editing tasks, and viewing
task details. The View receives task data from the Model and renders it dynamically using template
variables.

- **Controller:** The Controller component handles HTTP requests from the user's browser. It
contains logic for processing user actions, such as adding/editing/deleting tasks. When a user submits a
form to create or edit a task, the Controller receives the form data, validates it, and interacts with the
Model to update the task data accordingly. It then selects an appropriate View to display the updated
task list or task details.

In this example, the MVC architecture separates concerns by dividing the application into distinct
components, making it easier to manage and maintain the codebase. The Model encapsulates the data
and business logic, the View handles the presentation layer, and the Controller orchestrates the flow of
data and user interactions.

You might also like