Untitled Document
Untitled Document
/WEB-INF
/lib
/classes
/META-INF
index.jsp
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
@WebServlet("/DatabaseServlet")
public class DatabaseServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
Connection connection = null;
PrintWriter out = response.getWriter();
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to the database
String url = "jdbc:mysql://localhost:3306/your_database";
String username = "your_username";
String password = "your_password";
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
out.println("Error: " + e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Configure web.xml:
● In the /WEB-INF directory, create or modify web.xml to map the servlet:
<web-app>
<servlet>
<servlet-name>DatabaseServlet</servlet-name>
<servlet-class>your.package.name.DatabaseServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseServlet</servlet-name>
<url-pattern>/DatabaseServlet</url-pattern>
</servlet-mapping>
</web-app>
Deploy to Tomcat:
● Package your application into a WAR file and deploy it to Tomcat's
webapps directory.
Access the Servlet:
● Open a web browser and go to
http://localhost:8080/your-web-app-context/DatabaseServlet to
test the database connectivity.
● Remember to replace placeholders like your_database, your_username,
your_password, and your.package.name with your actual database
information and package name.
Unit 1
1.Create a registration form to collect the student information like Name, Roll
number, gender, branch, subject options using the form elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
form {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
label {
display: block;
margin-bottom: 8px;
}
input,
select {
width: 100%;
padding: 10px;
margin-bottom: 15px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background-color: #4caf50;
color: #fff;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<form action="#" method="post">
<h2>Student Registration Form</h2>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="male" required>
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female" required>
<label for="female">Female</label>
<label for="branch">Branch:</label>
<select id="branch" name="branch" required>
<option value="CSE">Computer Science and Engineering</option>
<option value="ECE">Electronics and Communication Engineering</option>
<option value="ME">Mechanical Engineering</option>
<!-- Add more options as needed -->
</select>
<label for="subject">Subject:</label>
<select id="subject" name="subject" required>
<option value="math">Mathematics</option>
<option value="physics">Physics</option>
<option value="chemistry">Chemistry</option>
<!-- Add more options as needed -->
</select>
<button type="submit">Submit</button>
</form>
</body>
</html>
2. Create a web page by adding different margins,
borders, and padding properties to different
paragraphs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styling Paragraphs</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 20px;
border: 5px solid #333;
}
p{
margin-bottom: 20px;
padding: 15px;
border: 2px solid #ddd;
border-radius: 8px;
}
.special-paragraph {
margin-top: 40px;
margin-bottom: 10px;
padding: 20px;
border: 3px dashed #4caf50;
}
.highlighted-paragraph {
margin-top: 10px;
margin-bottom: 30px;
padding: 15px;
border: 2px solid #ff9800;
background-color: #ffeeba;
}
</style>
</head>
<body>
<h1>Styled Paragraphs Example</h1>
In this example:
font-size:
Sets the size of the font. It can be specified in various units such as pixels, ems, rems,
or percentages.
p{
font-size: 16px;
}
font-weight:
Defines the thickness of the font. Common values are normal, bold, or numeric values
like 400 or 700.
h1 {
font-weight: bold;
}
font-style:
Specifies the style of the font, such as normal, italic, or oblique.
em {
font-style: italic;
}
color:
Sets the color of the text. It can be specified using color names, hexadecimal codes,
RGB values, or HSL values.
a{
color: #3366cc;
}
Border Properties:
border-width, border-style, border-color:
These properties can be used individually or combined to set the width, style, and
color of the border.
div {
border-width: 2px;
border-style: solid;
border-color: #999;
}
Alternatively, you can use the shorthand property border:
div {
border: 2px solid #999;
}
border-radius:
Defines the radius of the border corners, creating rounded corners.
img {
border-radius: 5px;
}
border-collapse:
Specifies whether table borders should be collapsed into a single border or separated.
table {
border-collapse: collapse;
}
Border-spacing:
Sets the spacing between adjacent cells in a table.
table {
border-spacing: 5px;
}
outline:
Creates a line outside an element to make it stand out. It is often used in addition to
borders.
input:focus {
outline: 2px solid #4caf50;
}
Unit 2
How can regular expressions be used for text pattern matching in java
script with an example
Regular expressions (regex or regexp) are powerful tools for pattern matching and
manipulation of text in JavaScript. In JavaScript, you can use the RegExp object or use
regular expression literals directly. Here's a simple example demonstrating how regular
expressions can be used for text pattern matching in JavaScript:
<p id="result"></p>
<script>
function validateEmail() {
// Get the input value
var email = document.getElementById('emailInput').value;
The HTML file includes an input field for entering an email address, a button to trigger
the validation, and a paragraph for displaying the result.
The JavaScript function validateEmail is triggered when the button is clicked. It retrieves
the input value and uses a regular expression to validate the email format.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Toggle Element Visibility</title>
<style>
#imageContainer {
text-align: center;
margin: 20px;
}
#toggleButton {
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Toggle Element Visibility Example</h1>
<div id="imageContainer">
<img id="toggleImage" src="https://via.placeholder.com/300" alt="Sample Image"
style="display: block;">
</div>
<script>
function toggleVisibility() {
var image = document.getElementById('toggleImage');
In this example:
The page includes an image with the id toggleImage and a button with the id
toggleButton.
The initial display of the image is set to block using inline CSS.
The toggleVisibility JavaScript function is triggered when the button is clicked.
Inside the function, it checks the current display property of the image.
If the image is visible, it sets the display property to none to hide it.
If the image is hidden, it sets the display property to block to show it.
Explain various looping statements in Javascript with examples
JavaScript provides several looping statements that allow you to execute a block of
code repeatedly. Here are the main looping statements in JavaScript along with
examples:
1. for Loop:
The for loop is used when the number of iterations is known beforehand.
// Example: Print numbers from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(i);
}
2. while Loop:
The while loop is used when the number of iterations is not known beforehand, and the
loop continues as long as the specified condition is true.
// Example: Print numbers from 1 to 5 using while loop
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
3. do...while Loop:
Similar to the while loop, but the block of code is executed at least once before the
condition is checked.
// Example: Print numbers from 1 to 5 using do...while loop
let j = 1;
do {
console.log(j);
j++;
} while (j <= 5);
4. for...in Loop:
Used for iterating over the properties of an object.
// Example: Iterate over object properties
const person = { name: 'John', age: 30, job: 'developer' };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
5. for...of Loop:
Introduced in ES6, used for iterating over iterable objects such as arrays, strings, maps,
sets, etc.
// Example: Iterate over array elements
const colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
6. forEach Method:
Array method for iterating over array elements (introduced in ES5).
// Example: Using forEach to iterate over array elements
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function (number) {
console.log(number);
});
7. map Method:
Array method that creates a new array with the results of calling a provided function on
every element in the array.
// Example: Using map to create a new array
const doubledNumbers = numbers.map(function (number) {
return number * 2;
});
console.log(doubledNumbers);
8. filter Method:
Array method that creates a new array with elements that satisfy the provided function.
// Example: Using filter to create a new array with even numbers
const evenNumbers = numbers.filter(function (number) {
return number % 2 === 0;
});
console.log(evenNumbers);
These looping statements provide different ways to iterate over data structures and
execute code repeatedly based on various conditions. The choice of which loop to use
depends on the specific requirements of your code.
Illustrate how position concept works in Java Script, explain with code.
In JavaScript, the position concept is often associated with the manipulation of the
position of elements within the Document Object Model (DOM). The position property is
used in CSS to control the positioning of an element relative to its normal position.
JavaScript can be used to dynamically manipulate this property and change the position
of elements on the web page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Position Concept in JavaScript</title>
<style>
#movingBox {
width: 100px;
height: 100px;
background-color: #3498db;
position: absolute; /* Set the initial position to absolute */
top: 50px;
left: 50px;
}
button {
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Move the Box!</h1>
<div id="movingBox"></div>
<script>
function moveBox() {
// Get the reference to the moving box element
var box = document.getElementById('movingBox');
// Calculate new random position
var newLeft = Math.floor(Math.random() * window.innerWidth);
var newTop = Math.floor(Math.random() * window.innerHeight);
In this example:
The #movingBox div has an initial position set using CSS. It is initially positioned at top:
50px and left: 50px.
The button triggers the moveBox function when clicked.
The moveBox function calculates new random coordinates and updates the left and top
style properties of the #movingBox div.
The position property is set to absolute, allowing us to position the element based on its
containing block.
Unit 3
Describe internal DTD and External DTD with syntax.
DTD (Document Type Definition) is a set of rules that define the structure and legal
elements and attributes of an XML document. DTDs can be either internal or external,
and they help ensure that XML documents adhere to a specific structure.
Internal DTD:
An internal DTD is included within the XML document itself, typically within the
DOCTYPE declaration at the beginning of the XML file. Here is the syntax for an internal
DTD:
<?xml version="1.0"?>
<!DOCTYPE rootElement [
<!-- Internal DTD Declarations -->
<!ELEMENT rootElement (childElement1, childElement2, ...)>
<!ELEMENT childElement1 (#PCDATA | subElement1 | subElement2 | ...)>
<!ELEMENT childElement2 (#PCDATA | subElement3 | subElement4 | ...)>
In this example:
<!DOCTYPE rootElement [...]> declares the document type and includes the internal DTD
within square brackets.
<!ELEMENT> declarations define the elements and their allowed content.
<!ATTLIST> declarations define attributes for elements.
External DTD:
An external DTD is stored in a separate file and referenced from the XML document.
This approach allows for greater modularity and reusability. Here is the syntax for an
external DTD:
<!ATTLIST childElement1
attribute1 CDATA #REQUIRED
attribute2 (value1 | value2 | value3) "default">
In this example:
<!DOCTYPE rootElement SYSTEM "example.dtd"> references the external DTD file using
the SYSTEM keyword.
Both internal and external DTDs provide a way to formally describe the structure and
constraints of XML documents. The choice between them depends on factors such as
document modularity, reuse, and manageability. External DTDs are often preferred for
larger projects where maintaining a separate file for document structure is more
practical.
What is the use of XQUERY and Illustrate FLOWR expression to write
Queries in XML?
XQuery (XML Query):
XQuery is a query language designed for querying and extracting information from XML
documents. It is a standardized query language for XML databases and is supported by
various XML databases and processing engines. XQuery provides a powerful and
flexible way to query XML data, similar to how SQL is used to query relational
databases.
Let's illustrate the FLOWR expression with an example. Consider the following XML data
representing a list of books:
<library>
<book>
<title>XQuery for Beginners</title>
<author>John Doe</author>
<price>29.99</price>
</book>
<book>
<title>Advanced XML Processing</title>
<author>Jane Smith</author>
<price>39.99</price>
</book>
<!-- More book elements... -->
</library>
xample XQuery using FLOWR expression:
Suppose we want to retrieve the titles of books written by authors whose names start
with 'J' and are priced below $35. We can use a FLOWR expression for this:
In this example:
for $book in /library/book iterates over each <book> element in the XML document.
where starts-with($book/author, 'J') and $book/price < 35.00 filters the books based on
the conditions specified.
order by $book/price ascending sorts the results by the book price in ascending order.
return $book/title specifies that the query should return the title of each matching book.
The result of this query will be a sequence of book titles meeting the specified criteria.
<!DOCTYPE books [
<!ELEMENT books (book+)>
<!ELEMENT book (title, author, year, price)>
<!ATTLIST book category CDATA #REQUIRED>
<!ELEMENT title (#PCDATA)>
<!ATTLIST title lang CDATA #REQUIRED>
<!ELEMENT author (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>
Explanation:
<!ELEMENT books (book+)>: Defines that the <books> element should contain one or
more <book> elements.
<!ELEMENT book (title, author, year, price)>: Defines the structure of the <book> element,
which must contain a <title>, <author>, <year>, and <price> in that order.
<!ATTLIST book category CDATA #REQUIRED>: Specifies that the <book> element must
have a category attribute of type CDATA (character data) and is required.
<!ELEMENT title (#PCDATA)>: Defines that the <title> element can contain parsed
character data (#PCDATA).
<!ATTLIST title lang CDATA #REQUIRED>: Specifies that the <title> element must have a
lang attribute of type CDATA and is required.
<!ELEMENT author (#PCDATA)>: Defines that the <author> element can contain parsed
character data.
<!ELEMENT year (#PCDATA)>: Defines that the <year> element can contain parsed
character data.
<!ELEMENT price (#PCDATA)>: Defines that the <price> element can contain parsed
character data.
This DTD describes the structure and constraints of the XML document you provided. It
ensures that the <books> element contains one or more <book> elements, each <book>
has the required elements (<title>, <author>, <year>, and <price>), and the <title> element
must have a required lang attribute.
Unit 4
Explain the procedure to store the form values into a database and
provide an example in a servlet.
Storing form values into a database using a servlet involves several steps. Below is a
step-by-step explanation along with an example servlet code using Java and JDBC
(Java Database Connectivity). In this example, I'll assume you are using a MySQL
database, and the form has fields for name and email.
@WebServlet("/SubmitFormServlet")
public class SubmitFormServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
// Handle exceptions
PrintWriter out = response.getWriter();
out.println("<html><body><h2>Error: " + e.getMessage() +
"</h2></body></html>");
}
}
}
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Development Faster development due to higher-level May require more code for common tasks,
Speed abstractions and less boilerplate code. potentially slowing down development.
Supports custom and standard tag Lacks built-in support for tag libraries,
Built-in Tag
libraries (e.g., JSTL) for common tasks, requiring more code for the same
Libraries
promoting code reuse. functionality.
java
<h1>Hello, <%=
Coding Style response.getWriter().println("<html>
request.getParameter("name")
Example <body><h1>Hello, " + name +
%></h1>
"</h1></body></html>");
Write a Java Servlet program that can handle Http Request and Response.
import java.io.IOException;
import java.io.PrintWriter;
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("/EchoServlet")
public class EchoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Components of MVC:
Model:
AngularJS provides two-way data binding between the model and the view. Changes in
the model automatically reflect in the view, and vice versa, without the need for manual
updates.
MVC Architecture:
Directives are markers on a DOM element that tell AngularJS to attach a specific
behavior to that DOM element or transform the DOM element and its children. Examples
include ng-repeat, ng-model, and ng-show.
Dependency Injection:
AngularJS allows the creation of reusable services that can be injected into controllers,
directives, or other services. Services are singleton objects that perform specific tasks,
such as data retrieval, logging, etc.
Templates:
Templates in AngularJS are written in HTML and extended with AngularJS-specific
markup. The templates define the structure of views and include expressions, directives,
and filters.
Routing:
Filters in AngularJS allow the transformation of data before it is displayed in the view.
Examples include currency, uppercase, and filter.
Form Validation:
Developers can describe the user interface and behavior in a declarative manner using
HTML and AngularJS directives, making the code more readable and expressive.
AngularJS has been widely adopted for building dynamic and interactive web
applications, and it laid the foundation for the development of subsequent versions like
Angular (Angular 2 and above).
Draw and explain the importacce of MVC architecture
With the clear separation of concerns, maintenance becomes easier. Developers can
focus on specific components without being overwhelmed by the entire application's
complexity.
Testability:
Components can be tested independently. Unit tests and integration tests can be
written for the model, view, and controller, ensuring the reliability and correctness of
each component.
Improved Collaboration:
MVC allows for parallel development as different teams or developers can work on
different components simultaneously. This improves collaboration and accelerates
development.
Enhanced Code Readability:
MVC promotes clean code by organizing it into distinct components. This enhances
code readability, making it easier for developers to understand and maintain the
codebase.
Adaptability to Change:
Changes to one component (e.g., updating the user interface) do not necessarily affect
other components. This adaptability to change is crucial for evolving and maintaining
software over time.
Create an AngularJS application to show the text box value below the
field
<!DOCTYPE html>
<html lang="en" ng-app="textBoxApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Text Box Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-controller="TextBoxController">
<label for="inputField">Enter Text:</label>
<input type="text" id="inputField" ng-model="inputText">
<script>
// Define AngularJS module
var app = angular.module('textBoxApp', []);
</body>
</html>
Explanation:
AngularJS and ReactJS are both popular JavaScript frameworks used for building web
applications, but they have different architectures, philosophies, and use cases. Here's a
comparison of AngularJS (Angular 1.x) and ReactJS:
AngularJS:
Framework vs. Library:
AngularJS uses two-way data binding, which means changes in the UI automatically
update the underlying model, and vice versa.
This simplifies development but can have performance implications with complex
applications.
HTML and JavaScript Integration:
AngularJS extends HTML with additional attributes and expressions to handle dynamic
behavior.
The framework relies heavily on declarative programming.
Dependency Injection:
AngularJS has built-in support for dependency injection, making it easy to manage
dependencies and promote modular code.
Directives:
Directives are a core part of AngularJS, allowing developers to create custom HTML
tags and attributes to extend the functionality of the framework.
Complexity:
AngularJS can be considered more opinionated and has a steeper learning curve
compared to React.
It may be better suited for larger applications with complex requirements.
ReactJS:
Library for Building UI:
React is often referred to as a library for building user interfaces.
It focuses on the view layer of the application, leaving other concerns to external
libraries or tools.
Virtual DOM:
React uses a virtual DOM to efficiently update the actual DOM, minimizing the need for
direct manipulation of the DOM.
This can lead to better performance, especially in large and dynamic applications.
JSX:
React uses JSX, a syntax extension that allows mixing HTML with JavaScript.
JSX is compiled to JavaScript and provides a more concise and expressive way to
define components.
One-Way Data Binding:
React primarily uses one-way data binding, which can be more predictable and easier to
reason about.
Data flows in one direction, from parent to child components.
Component-Based Architecture:
React has a large and active community, and it is often used in conjunction with other
libraries and tools (e.g., Redux for state management).
Simplicity and Flexibility:
React is known for its simplicity and flexibility, allowing developers to choose additional
libraries and tools based on project requirements.
It's often favored for its ease of integration into existing projects.
Conclusion:
Choose AngularJS if you prefer a comprehensive MVC framework with built-in features
and conventions.
Choose React if you prefer a more focused library for building UI components, especially
in scenarios where you need a high degree of flexibility or when working with a
component-based architecture.