0% found this document useful (0 votes)
13 views94 pages

WT Merged Final

Uploaded by

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

WT Merged Final

Uploaded by

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

Unit-I • Using this, architecture presentation part, logic part and application

data part is split into the separate section which allows managing of
Why AngularJS? application in a very fluent manner.
• Angular JS is used to make the HTML page as dynamic.
• By using angular one can convert the static page (a page that does
not change except if changes are made by manually in its code) into a
Directives
dynamic page as it extends the functionality of HTML elements.
• Directives are classes that add additional behavior to elements in
• It helps to make a single page application.
your Angular applications.
• It means content gets dynamically written on the page.
• Use Angular's built-in directives to manage forms, lists, styles, and
• A User need not require to refresh the page also the control will also
what users see.
remain on the same page it does not get transfers to another page.
• It tells how to combine data into the HTML template.
• With the use of directive, we can provide extra functionality to our
angular application.
Features of AngularJS • Angular provides a way to create custom directives

Not Browser Specific


• Angular applications are not browser specific means there is no
browser constraint on an angular application.
• It can run on all major browsers except internet explorer 8.0 and
smartphones including Android and ios based phones/tablets.

Code Less
• A programmer can write less and perform more functionalities with
the same code.
• Filters in angular provide the functionality of write less do more.
• The various filters in angular are uppercase, lowercase, currency etc.
• You can use the filter and easily format the data

Data Binding Speed and Performance


• Speed and performance of angular are faster because of :
Data Binding in AngularJS is simply the automatic binding of data between the view and the • Code Generation – When you are writing code using angular, it
model components of MVC architecture. converts your template into a highly optimized code that gives you an
• When data in the model changes, the view reflects the change, and advantage of handwritten code with the productivity of framework.
when data in the view changes, the model is updated as well.
• AngularJS uses the two way data binding technique.
Dependency Injection
Architecture • Dependency injection (DI) is the part of the Angular framework that
• An angular application is built using MVC architecture that stands for provides components with access to services and other resources.
Model View and Controller. • Angular provides the ability for you to inject a service into a
• It separates the application into three parts model part, view part component to give that component access to the service
and controller part as per the components of MVC architecture.
Travel Applications
• Travel application makes it easy to plan a trip.
• Now, in this world of technology, there is no need to go to a travel
agent. One can do the same work on its own.
• Example – JetBlue , Booking.com, MakeMyTrip, Yatra and etc.,
• It offers a wide range of accommodation options, flights, and car
rentals.
Deep linking Weather Applications
• Deep linking allows you to encode the state of application in the URL • To know about the weather, weather application has been built.
so that it can be bookmarked. • It can help us to know about the weather condition of any place even
• For instance, by using the HTML code by sitting far away from that place.
<a href=”http://example.com/page”>Click here</a>, you can create a
deep link that points directly to the specified page. Ex:E-commerce,user-fgenerated portals,mobile commerce,video straming platform etc..

AJS
Routing
• Routing allows the switching/Path between views.
• Being a single page application ngRoute directive provided by angular,
helps a user to navigate from one view to another, but the application
will remain single page.
• It means without reloading the angular application you can switch to
different pages in your application.

Productivity
• Template – Template in the angular application allows a developer to
create user interface quickly as it provides simple and powerful
template syntax.
• Angular CLI – It is a command line tool. It starts building an
application very fast. It adds components, tests it and then deploys it
instantly.
AngularJs Advantages
.Open Source
AngularJS is an open source JavaScript MVC framework, therefore, at
affordable costs custom application can be available to anyone.
• Single Page Application (SPA)
Single page application means only a single HTML web page is
loaded and further updating is done on that single page only.
• No prerequisite knowledge
HTML, CSS and JavaScript are to work on AngularJS.
So, there is no need to learn any other scripting language.
• Easy to extend and customize
Due to certain built-in attributes, it is easy to extend.
These attributes make it possible to extend the functionality of HTML
by attaching a specific behavior with it. AngularJS - MVC Architecture
Customized means adding or removing features or functionality,
which is done to satisfy the specific needs. • Components of MVC

• Google supported • The MVC framework includes the following 3 components:


AngularJs framework is supported by Google.
1. Model-Manages data and business logic.
Regular updates are done.
• Great MVC 2. View-Handles layout and display.
• As we know there are three components of MVC architecture (Model,
3. Controller- Routes commands to the model and view parts.
View, Controller).
• MVC (Model-View-Controller) is a pattern in software design commonly used to
AngularJS Disadvantages implement user interfaces, data, and controlling logic.
• Less secure
• No specific way
• JavaScript-Based
• Not supported everywhere
• Memory leakage
• Less secure
There is no server authorization and authentication in angular.
 Authorization means granting permission for data access and identifying a user by
validating credentials.
 AngularJs can’t provide both the features, that’s we call it less secure.
• Memory leakage
We can define memory leak as the memory requires by application anymore and due to some
factors, it will not return to the pool of the free memory.
• Less secure
There is no server authorization and authentication in angular.
 Authorization means granting permission for data access and dentifying a user by validating
credentials.
AngularJs can’t provide both the features, that’s we call it less secure.
• Memory leakage
We can define memory leak as the memory requires by application anymore and due to some
factors, it will not return to the pool of the free memory.
MVC In AngularJS • AngularJS expressions can also be written inside a directive:
ng-bind="expression".
• Here, we will see how the components of MVC works in AngularJS:
• AngularJS will resolve the expression, and return the result exactly where the
• i. Model Part In Angular Application expression is written.
• It responds to the request made from view part. It can obtain data dynamically means • AngularJS expressions are much like JavaScript expressions:
you can get data from database like from MySQL or you can get data from static They can contain literals, operators, and variables.
JSON (JavaScript Object Notation) file.
• Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}
The MVC pattern is made up of the following three parts:
• An expression may be Numbers , Strings, Objects , Arrays
1. Model: It is responsible for managing application data. It responds to the requests
from view and to the instructions from controller to update itself.
AngularJS Directives
2. View: It is responsible for displaying all data or only a portion of data to the users. It
also specifies the data in a particular format triggered by the controller's decision to • AngularJS lets you extend HTML with new attributes called Directives.
present the data. They are script-based template systems such as JSP, ASP, PHP and • AngularJS has a set of built-in directives which offers functionality to your
very easy to integrate with AJAX technology. applications.

3. Controller: It is responsible to control the relation between models and views. It • AngularJS also lets you define your own directives.
responds to user input and performs interactions on the data model objects. The • AngularJS directives are extended HTML attributes with the prefix ng-
controller receives input, validates it, and then performs business operations that • The ng-app directive initializes an AngularJS application.
modify the state of the data model.
• The ng-init directive initializes application data.
MVC Example • The ng-model directive binds the value of HTML controls (input, select, text area) to
application data.
4. <!DOCTYPE html>
5. <html lang="en">
6. <head>
7. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> AngularJS ng-model Directive
</script>
• The ng-model directive binds the value of HTML controls (input, select, textarea) to
8. </head>
application data.
9. <body ng-app="myapp">
10. <div ng-controller="HelloController" > • <div ng-app="myApp" ng-controller="myCtrl">
11. <h2>Hello {{helloTo.title}} !</h2> Name: <input ng-model="name">
12. </div> </div>
13. <script>
14. angular.module("myapp", []) <script>
15. .controller("HelloController", function($scope) { var app = angular.module('myApp', []);
16. $scope.helloTo = {}; app.controller('myCtrl', function($scope) {
17. $scope.helloTo.title = "World, AngularJS"; $scope.name = “SR Univesrity";
18. } ); });
19. </script> </script>
20. </body>
21. </html> view part line 10,11,12 // controller part line 16-19
AngularJS Data Binding
• In software development technologies, we consider data binding as the most powerful
AngularJS expressions and useful feature.
• AngularJS binds data to HTML using Expressions. • Data binding is the synchronization of data between business logic and view of the
• AngularJS expressions can be written inside double braces: {{ expression }}. application.
• It serves as a bridge between two components of angular that is model part and view
part.
• Data Binding is automatic and provides a way to wire the two important part of an AngularJS Controllers
application that is the UI and application data. • AngularJS controllers control the data of AngularJS applications.
• AngularJS controllers are regular JavaScript Objects.
• AngularJS applications are controlled by controllers.
• The ng-controller directive defines the application controller.
When to use an ng-controller?
• The ng-controller Directive in AngularJS is used to add a controller to the application.
• It can be used to add methods, functions, and variables that can be called on some
• An ng-model directive is used to perform data binding in angular. event like click, etc to perform certain actions.

• <!DOCTYPE html> • <div ng-app="myApp" ng-controller="myCtrl">

• <html> First Name: <input type="text" ng-model="firstName"><br>


• <script Last Name: <input type="text" ng-model="lastName"><br>
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <br>
Full Name: {{firstName + " " + lastName}}
• <body>
• <div ng-app="" > </div>
• <p>Input something in the input box:</p> <script>
• <p>Name: <input type="text" ng-model="language"></p> var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
• <p>You are learning: {{ language }}</p>
$scope.firstName = “SR";
• </div> $scope.lastName = “University";
• </body> });
</script>
• </html>
Types of Data Binding in AngularJS
• Two types of binding in AngularJS are as follow:
AngularJS Scope
• The scope is the binding part between the HTML (view) and the JavaScript
• One Way Data Binding
(controller).
• Two Way Data Binding
• The scope is an object with the available properties and methods.
• How to Use the Scope?
• When you make a controller in AngularJS, you pass the $scope object as an
argument:
• Example:<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{carname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.carname = “BMW"; • Enter subject: <input type = "text" ng-model = "subjectName">
}); • Subject:
</script>
• <ul>
• <li ng-repeat = "subject in student.subjects | filter: subjectName">
AngularJS Filters • {{ subject.name + ', marks:' + subject.marks }}
• Filters can be added in AngularJS to format data. • </li>
• currency Format a number to a currency format. • </ul>
• date Format a date to a specified format.
• filter Select a subset of items from an array. OrderBy Filter
• json Format an object to a JSON string.
• To order subjects by marks, we use orderBy marks.
• limitTo Limits an array/string, into a specified number of
• Subject:
elements/characters.
• <ul>
• lowercase Format a string to lower case.
• <li ng-repeat = "subject in student.subjects | orderBy:'marks'">
• number Format a number to a string.
• {{ subject.name + ', marks:' + subject.marks }}
• orderBy Orders an array by an expression.
• </li>
• uppercase Format a string to upper case.
• </ul>

Uppercase Filter
• Add uppercase filter to an expression using pipe character. Here we've added AngularJS – Tables
uppercase filter to print student name in all capital letters.
• Enter first name:<input type = "text" ng-model = "student.firstName">
• The ng-repeat directive is used to draw tables in AngularJS.
Displaying tables with AngularJS is very easy and simple.
• Enter last name: <input type = "text" ng-model = "student.lastName">
• Name in Upper Case: {{student.fullName() | uppercase}} • Syntax:
<element ng-repeat="expression">Content..<element>
Lowercase Filter <table>
• Enter first name:<input type = "text" ng-model = "student.firstName"> <tr>
• Enter last name: <input type = "text" ng-model = "student.lastName">
<th>Name</th>
• Name in Lower Case: {{student.fullName() | lowercase}}
<th>Marks</th>
Currency Filter </tr>
• Enter fees: <input type = "text" ng-model = "student.fees"> <tr ng-repeat = "subject in student.subjects">
• fees: {{student.fees | currency}} <td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
Filter </tr></table>
• To display only required subjects, we use subject Name as filter.
AngularJS Select Boxes Using ng-repeat:
• AngularJS lets you create dropdown lists based on items in an array, or an object. <select ng-model="selectedCar">
• Creating a Select Box Using ng-options <option ng-repeat="x in cars“ value="{{x.model}}">{{x.model}}</option>
• If you want to create a dropdown list, based on an object or an array in AngularJS, </select>
you should use the ng-options directive: <h1>You selected: {{selectedCar}}</h1>
<!DOCTYPE html> When using the value as an object, use ng-value instead of value:
<html> • Example
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> • Using ng-repeat as an object:
<body> <select ng-model="selectedCar">
<div ng-app="myApp" ng-controller="myCtrl"> <option ng-repeat="x in cars" ng-value="{{x}}">{{x.model}}</option>
<select ng-model="selectedName" ng-options="x for x in names"> </select>
</select> <h1>You selected a {{selectedCar.color}} {{selectedCar.model}}</h1>
</div>
<script> • Using ng-options:
var app = angular.module('myApp', []); <select ng-model="selectedCar" ng-options="x.model for x in cars">
app.controller('myCtrl', function($scope) { </select>
$scope.names = [“Apple", “Banana", “Mango"]; <h1>You selected: {{selectedCar.model}}</h1>
}); <p>Its color is: {{selectedCar.color}}</p>
</script>
<p>This example shows how to fill a dropdown list using the ng-options AngularJS HTML DOM
directive.</p>
• The DOM in AngularJS is a programming interface that allows programmers to easily
</body>
manipulate the page's components.
</html> • Core DOM - standard model for all document types.
• XML DOM - standard model for XML documents.
ng-options vs ng-repeat • HTML DOM - standard model for HTML documents.
• Because the ng-repeat directive repeats a block of HTML code for each item in an • The HTML DOM in AngularJS facilitates the directives that bind the application data
array, it can be used to create options in a dropdown list with the attributes of HTML DOM elements.
• but the ng-options directive was made especially for filling a dropdown list with
options.
• You can use both the ng-repeat directive and the ng-options directive:
• Assume you have an array of objects:
• $scope.cars = [
• {model : "Ford Mustang", color : "red"},
• {model : "Fiat 500", color : "white"},
• {model : "Volvo XC90", color : "black"}];
ng-disabled directive: <td><button ng-click = "clickCounter = clickCounter + 1">Click
Me!</button></td>
• The ng-disabled directive binds AngularJS application data to the disabled attribute of
HTML elements. </tr>

<input type = "checkbox" ng-model = "enableDisableButton">Disable Button </table>

<button ng-disabled = "enableDisableButton">Click Me!</button> </div>


<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
ng-hide Directive </script>
• Add ng-hide attribute to an HTML button and pass it a model. Bind the model to a </body></html>
checkbox and see the variation.
<input type = "checkbox" ng-model = "showHide2">Hide Button
AngularJS Events
<button ng-hide = "showHide2">Click Me!</button>
• An Events in AngularJS can be used to perform particular tasks, based on the
action taken.
ng-click Directive • AngularJS supports the following events −
• Add ng-click attribute to an HTML button and update a model. Bind the model to • ng-click
HTML and see the variation. • ng-dbl-click
• <p>Total click: {{ clickCounter }}</p>
• ng-mousedown
• <button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>
• ng-mouseup
Ex:
• ng-mouseenter
<html> <head>
• ng-mouseleave
<title>AngularJS HTML DOM</title>
• ng-mousemove
</head><body>
• ng-mouseover
<h2>AngularJS Sample Application</h2>
• ng-keydown
<div ng-app = "">
• ng-keyup
<table border = "0"> <tr>
• ng-keypress
<td><input type = "checkbox" ng-model = "enableDisableButton">Disable
Button</td>
• The ng-click directive defines AngularJS code that will be executed when the
<td><button ng-disabled = "enableDisableButton">Click Me!</button></td>
element is being clicked.
</tr><tr>
• <html>
<td><input type = "checkbox" ng-model = "showHide1">Show Button</td>
<script
<td><button ng-show = "showHide1">Click Me!</button></td> src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</tr><tr> <body>
<td><input type = "checkbox" ng-model = "showHide2">Hide Button</td> <div ng-app="myApp" ng-controller="myCtrl">
<td><button ng-hide = "showHide2">Click Me!</button></td> <button ng-click="count = count + 1">Click Me!</button>
</tr> <tr> <p>{{ count }}</p>
<td><p>Total click: {{ clickCounter }}</p></td> </div><script>
var app = angular.module('myApp', []); <div ng-app="myApp" ng-controller="formCtrl">
app.controller('myCtrl', function($scope) { <form>
$scope.count = 0; First Name: <input type="text" ng-model="firstname">
});</script> </form>
</body></html> </div><script>
var app = angular.module('myApp', []);
• Increase the count variable when the mouse moves over the H1 app.controller('formCtrl', function($scope) {
element $scope.firstname = “SR University";
<html><script });</script>
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
• <html>
<div ng-app="myApp" ng-controller="myCtrl">
• <script
<h1 ng-mousemove="count = count + 1">Mouse Over Me!</h1> src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<h2>{{ count }}</h2> • <body>
</div><script> • <div ng-app="">
var app = angular.module('myApp', []); • <form>
app.controller('myCtrl', function($scope) { • First Name: <input type="text" ng-model="firstname">
$scope.count = 0; • </form>
});</script> • <h1>You entered: {{firstname}}</h1>
</body></html> • </div>
• <p>Change the name inside the input field, and you will see the name in the header
changes accordingly.</p>
AngularJS Forms
• </body>
• Forms are collection of controls that is input field, buttons, checkbox and these can
be validated • </html>
real time.
• So a form can be consisting of the many number of controls.
Checkbox
• Input field
A checkbox has the value true or false. Apply the ng-model directive to a checkbox, and use
• Checkbox its value in your application.
• Radiobox • <div ng-app="">
• Button • <form>
• SelectBox(Dropdowns) Check to show a header:
• TextArea <input type="checkbox" ng-model="myVar"> </form>
<h1 ng-show="myVar">I am Btech Student</h1>
Data-Binding </div><p>The header's ng-show attribute is set to true when the checkbox is
checked.</p>
Input controls provides data-binding by using the ng-model directive.
<input type="text" ng-model="firstname">
Radiobuttons AngularJS Form Validation
• Bind radio buttons to your application with the ng-model directive. • AngularJS offers client-side form validation.
• Radio buttons with the same ng-model can have different values, but only the selected • AngularJS monitors the state of the form and input fields (input, textarea, select), and
one will be used. lets you notify the user about the current state.
<form> • AngularJS also holds information about whether they have been touched, or modified,
Obtain one Branch: or not.

<input type="radio" ng-model="myVar" value=“CSE">CSE


<input type="radio" ng-model="myVar" value=“EEE">EEE Form State and Input State
<input type="radio" ng-model="myVar" value=“Civil">Civil</form> • AngularJS is constantly updating the state of both the form and the input fields.
<div ng-switch="myVar"> • Forms have the following states:
<div ng-switch-when=“CSE"> • $pristine No fields have been modified yet
<h1>CSE</h1> • $dirty One or more have been modified
<p>Welcome to a world of CSE.</p> </div> • $invalid The form content is not valid
<div ng-switch-when=“EEE"> • $valid The form content is valid
<h1>EEE</h1> • $submitted The form is submitted
<p>Welcome to EEE.</p> </div>
<div ng-switch-when=“Civil"> • Input fields have the following states:
<h1>Civil</h1> • $untouched The field has not been touched yet
<p>Welcome to Different Cars.</p> </div> • $touched The field has been touched
</div> • $pristine The field has not been modified yet
<p>The ng-switch directive hides and shows HTML sections depending on the value • $dirty The field has been modified
of the radio buttons.</p> • $invalid The field content is not valid
• $valid The field content is valid
Examples
Selectbox <html>
<form> <scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></sc
• Obtain one Branch: ript> <body ng-app="">
<select ng-model="myVar"> <p>Try writing in the input field:</p>
<option value=""> <form name="myForm">
<option value=“CSE">CSE <input name="myInput" ng-model="myInput" required></form>
<option value=“EEE">EEE <p>The input's valid state is:</p>
<option value=“CIVIL">CIVIL <h1>{{myForm.myInput.$valid}}</h1>
</select> </body></html>
</form>
Email <div ng-app="myApp" ng-controller="myCtrl"><p>{{ x1 }}</p>

<form name="myForm"> <p>{{ x2 }}</p></div>

<input name="myInput" ng-model="myInput" type="email"> <script>

</form> var app = angular.module('myApp', []);

<p>The input's valid state is:</p> app.controller('myCtrl', function($scope) {

<h1>{{myForm.myInput.$valid}}</h1> $scope.x1 = “SR UNIVERSITY";

<body ng-app=""> $scope.x2 = angular.lowercase($scope.x1);

<p>Try leaving the first input field blank:</p> });</script></body>

<form name="myForm">
<p>Name: angular.isString()
<input name="myName" ng-model="myName" required> <body>
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The <div ng-app="myApp" ng-controller="myCtrl">
name is required.</span></p> <p>{{ x1 }}</p>
<p>Address: <p>{{ x2 }}</p>
<input name="myAddress" ng-model="myAddress" required></p>
</div><script>
</form>
var app = angular.module('myApp', []);
<p>We use the ng-show directive to only show the error message if the field has been
app.controller('myCtrl', function($scope) {
touched AND is empty.</p>
$scope.x1 = “Hello";
</body>
$scope.x2 = angular.isString($scope.x1);});
</script>
AngularJS API </body>
API stands for Application Programming Interface.
AngularJS Includes
• The AngularJS Global API is a set of global JavaScript functions for performing • With AngularJS, you can include HTML from an external file.
common tasks like: <html>
• Comparing objects <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">
• Iterating objects <div ng-include=“Sample.html'"></div>
• Converting data </body>
</html>
• API Description
• Note: you can create sample.html file as external.
• angular.lowercase() Converts a string to lowercase • Using AngularJS, we can embed HTML pages within an HTML page using ng-include
• angular.uppercase() Converts a string to uppercase directive.
<div ng-app = "" ng-controller = "studentController">
• angular.isString() Returns true if the reference is a string <div ng-include = "'main.html'"></div>
• angular.isNumber() Returns true if the reference is a number <div ng-include = "'subjects.html'"></div>
</div>
Ex: Example: tryAngularJS.html
<body> <html><head>
<title>Angular JS Includes</title>
<script src = AngularJS Animations
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script><style> AngularJS provides animated transitions, with help from CSS.
table, th , td { An animation is when the transformation of an HTML element gives you an illusion of
border: 1px solid grey; motion.
border-collapse: collapse; Example1:
padding: 5px;} <html><style>div {
table tr:nth-child(odd) { transition: all linear 0.5s;
background-color: #f2f2f2;} background-color: lightblue;
table tr:nth-child(even) { height: 100px;
background-color: #ffffff;} width: 100%;
</style></head<body> position: relative;
<h2>AngularJS Sample Application</h2> top: 0;
<div ng-app = "mainApp" ng-controller = "studentController"> left: 0;
<div ng-include = "'/angularjs/src/include/main.htm'"></div> }
<div ng-include = "'/angularjs/src/include/subjects.htm'"></div> .ng-hide {
</div> height: 0;
<script> width: 0;
var mainApp = angular.module("mainApp", []); background-color: transparent;
mainApp.controller('studentController', function($scope) { top:-200px;
$scope.student = { left: 200px;
firstName: "Rama", }</style>
lastName: "Krishna", <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
fees:500,subjects:[ <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
{name:'Physics',marks:70}, animate.js"></script>
{name:'Chemistry',marks:80}, <body ng-app="ngAnimate">
{name:'Math',marks:65}, <h1>Hide the DIV: <input type="checkbox" ng-model="myCheck"></h1>
{name:'English',marks:75}, <div ng-hide="myCheck"></div></body></html>
{name:'Hindi',marks:67}], To make your applications ready for animations, you must include the
fullName: function() { AngularJS Animate library:
var studentObject; <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
studentObject = $scope.student; animate.js"></script>
return studentObject.firstName + " " + studentObject.lastName;}};}); Then you must refer to the ngAnimate module in your application:
</script></body></html> <body ng-app="ngAnimate">
main.html
<table border = "0"><tr>
<td>Enter first name:</td> Or
<td><input type = "text" ng-model = "student.firstName"></td> if your application has a name, add ngAnimate as a dependency in your application module:
</tr><tr><td>Enter last name: </td> <body ng-app="myApp">
<td><input type = "text" ng-model = "student.lastName"></td> <h1>Hide the DIV: <input type="checkbox" ng-model="myCheck"></h1>
</tr><tr> <div ng-hide="myCheck"></div>
<td>Name: </td><td>{{student.fullName()}}</td></tr> <script>
</table> var app = angular.module('myApp', ['ngAnimate']);
</script>
subjects.html
<p>Subjects:</p><table>
<tr><th>Name</th>
<th>Marks</th></tr>
The ngAnimate module adds and removes classes.
The ngAnimate module does not animate your HTML elements, but when ngAnimate notice
<tr ng-repeat = "subject in student.subjects">
certain events, like hide or show of an HTML element, the element gets some pre-defined
<td>{{ subject.name }}</td><td>{{ subject.marks }}</td></tr></table>
classes which can be used to make animations.
The directives in AngularJS who add/remove classes are:
• ng-show })
• ng-hide .when("/green", {
• ng-class templateUrl : "green.htm"
• ng-view })
• ng-include .when("/blue", {
• ng-repeat templateUrl : "blue.htm"
});
• ng-if
});
• ng-switch

AngularJS Application
CSS Transitions It is time to create a real AngularJS Application.
CSS transitions allows you to change CSS property values smoothly, from one value to Make a Shopping List
another, over a given duration: Lets use some of the AngularJS features to make a shopping list, where you can add or
Example: remove items:
When the DIV element gets the .ng-hide class, the transition will take 0.5 seconds, and the
height will smoothly change from 100px to 0:
<style>
div {
transition: all linear 0.5s;
background-color: lightblue;
height: 100px;
}
.ng-hide {
height: 0;
}
</style> <html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
AngularJS Routing <script>
The ngRoute module helps your application to become a Single Page Application. var app = angular.module("myShoppingList", []);
If you want to navigate to different pages in your application, but you also want the app.controller("myCtrl", function($scope) {
application to be a SPA (Single Page Application), with no page reloading, you can use $scope.products = ["Milk", "Bread", "Cheese"];
the ngRoute module. });
The ngRoute module routes your application to different pages without reloading the entire </script>
application. <div ng-app="myShoppingList" ng-controller="myCtrl">
To make your applications ready for routing, you must include the AngularJS Route module: <ul>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></ <li ng-repeat="x in products">{{x}}</li>
script> </ul>
Then you must add the ngRoute as a dependency in the application module: </div>
var app = angular.module("myApp", ["ngRoute"]); <p>So far we have made an HTML list based on the items of an array.</p>
Now your application has access to the route module, which provides the $routeProvider. </body>
Use the $routeProvider to configure different routes in your application: </html>
app.config(function($routeProvider) { Adding Items:
$routeProvider In the HTML, add a text field, and bind it to the application with the ng-model directive.
.when("/", { In the controller, make a function named addItem, and use the value of the addMe input field
templateUrl : "main.htm" to add an item to the products array.
}) Add a button, and give it an ng-click directive that will run the addItem function when the
.when("/red", { button is clicked.
templateUrl : "red.htm" <script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.products.push($scope.addMe);
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>
Removing Items:
We also want to be able to remove items from the shopping list.
In the controller, make a function named removeItem, which takes the index of the item you
want to remove, as a parameter. In the HTML, make a <span> element for each item, and
give them an ng-click directive which calls the removeItem function with the current $index.
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.products.push($scope.addMe);
}
$scope.removeItem = function (x) {
$scope.products.splice(x, 1);
}
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">
{{x}}<span ng-click="removeItem($index)">&times;</span>
</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>
Login Form
Unit 2:jdbc How Java Database Communication is Possible?
Pre-Requisite
• Before moving JDBC, we need to have a good understanding of the following two
subjects −
• Core JAVA Programming
• SQL or MySQL Database
Where is Java Used Mostly?
• Java is mostly used in enterprise applications.
✓ JAVA program only knows method calls and DBMS only knows SQL statements.
• An enterprise application is also known as a business application.
✓ Both have a heterogeneous environment, they cannot communicate directly.
• Enterprise is nothing but a business organization.
✓ So for communication between the JAVA program and database, we have to use
• To computerize the business activities of an enterprise, whatever computer application JDBC.
we develop is known as a business or enterprise application.
• Examples: Bank, Insurance companies and etc.
What is the need for Database communication?
• To promote a dynamic interaction between user and application.
• What is the Limitation of Database?
• To provide security for user confidential data.
• DBMS is weak in data processing and also weak in providing interaction to the end-
user. • To protect data from multiple users.
• What is the contribution of Java to Enterprise applications? • Note: In earlier days to communicate with databases different database vendors
provides their own dependent libraries.
• Java is excellent in data processing and providing interaction to the end-user.
• The following problems are encountered whenever we import database libraries into
• What is the Limitation of Java?
our application:
• Java is weak in holding enterprise data in a persistent, easy, and retrievable manner
which means where DBMS is strong JAVA is weak in that area. • The application becomes database-dependent tightly.
• Migrating from one database to another database is a difficult task.
• It increases the development time and cost of the application also.
General Architecture of Enterprise Application
• To solve the above problem, we need a common library to communicate with any
type of database.
• To meet this requirement, Microsoft in collaboration with IBM, Oracle, and some
other third-party companies join as an open community and introduced database-
independent technology, i.e., ODBC (Open Database Community).

Benefits of ODBC
• It is a language-independent technology because it is implemented in a low-level
• In order to process the data and displayed the process data to the end-user, java has to language or native language.
access the data from the database in every Java-based enterprise application.
Drawbacks of ODBC • The java.sql package contains classes and interfaces for JDBC API.

• ODBC is not directly acceptable in a java application to communicate with the • A list of popular interfaces of JDBC API are given below:
database for the following reasons: • Driver
• Non-object oriented (it is procedure-oriented) • Connection
• OS dependency (because only on windows platform) • Statement
• Non-secure • PreparedStatement
• Note: Now ODBC can be used with LINUX also. • CallableStatement
• ResultSet
What is the Purpose of Java Database Connectivity? • ResultSetMetaData

• Any kind of java program can communicate with any RDBMS like Microsoft’s SQL • DatabaseMetaData
Server, Oracle’s MySQL, and IBM’s DB2.
• RowSet interface
• To communicate with any kind of RDBMS the standard procedure is the same means
A list of popular classes of JDBC API are given below:
the procedure of connectivity is the same.
• DriverManager
• JDBC helps the programmers to write java applications that manage these three
programming activities : • Blob
• It helps us to connect to a data database. • Clob
• It helps us in sending queries and updating statements to the database. • Types
• Retrieving and processing the results received from the database in terms of Differences between JDBC and ODBC
answering your query.

Applications of JDBC
• Java Applications
• Java Applets
• Enterprise JavaBeans (EJBs)
• Java Servlets
• Java Server Pages (JSPs)
• There are two primary packages for JDBC:
1. java.sql
2. javax.sql
• JDBC 4.3 is the latest JDBC version. It is the stable release since 21st September,
2017.
• These packages offer the main classes for interacting with data sources.
• Application: It is a java program or applet or a servlet that communicates with a data
source.
• JDBC API: The JDBC API allows Java programs to execute SQL statements and
retrieve results.
• DriverManager: It plays an important role in the JDBC architecture. It uses some
database-specific drivers to effectively connect enterprise applications to databases.
• JDBC Drivers: To communicate with a data source through JDBC, you need a JDBC
driver that intelligently communicates with the respective data source.

JDBC Drivers
• JDBC drivers are the software components which implements interfaces in JDBC
APIs to enable java application to interact with the database.
• JDBC drivers defined by Sun Microsystem that are mentioned below:
• Type-1 driver or JDBC-ODBC bridge driver
• Type-2 driver or Native-API driver
• Type-3 driver or Network Protocol driver
• Type-4 driver or Thin driver
JDBC-ODBC bridge driver – Type 1 driver Advantages
• Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the • Native-API driver gives better performance than JDBC-ODBC bridge driver.
database. The JDBC-ODBC bridge driver converts JDBC method calls into the
Disadvantages
ODBC function calls.
• Driver needs to be installed separately in individual client machines
• The Vendor client library needs to be installed on client machine.
• Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
• It is a database dependent driver.

Network Protocol driver – Type 3 driver (fully Java driver)


• The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol.

Advantages
• This driver software is built-in with JDK so no need to install separately.
• It is a database independent driver.

Disadvantages
• As a common driver is used in order to interact with different databases, the data
transferred through this driver is not so secured.
• The ODBC bridge driver is needed to be installed in individual client machines.
Advantages
• Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
• Type-3 drivers are fully written in Java, hence they are portable drivers.
• No client side library is required because of application server that can perform many
Native-API driver – Type 2 driver ( Partially Java driver) tasks like auditing, load balancing, logging etc.

• The Native API driver uses the client -side libraries of the database. Disadvantages
• This driver converts JDBC method calls into native calls of the database API. • Network support is required on client machine.
• Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

Thin driver – Type 4 driver (fully Java driver)


• Type-4 driver is also called native protocol driver. This driver interact directly with
database. It does not require any native database library, that is why it is also known
as Thin Driver.
Steps to Connect Java Application with Database
• Below are the steps that explains how to connect to Database in Java:
• Step 1 – Import the Packages
• Step 2 – Load the drivers using the Class.forName() method
• Step 3 – Register the drivers using DriverManager
• Step 4 – Establish a connection using the Connection class object
• Step 5 – Create a statement
• Step 6 – Execute the query
• Step 7 – Close the connections

Pros
Better performance than Types 1 and 2. No need to install special software on client or Step 1: Import the Packages
server. • Import statement in Java is helpful to take a class or all classes visible for a program
specified under a package, with the help of a single statement.
Cons
• Syntax 1:
Not optimized for server operating system, so the driver can’t take advantage of operating
system features. (The driver is optimized for the database and can take advantage of the • import package1[.package2].(*);
database vendor’s functionality.) User needs a different driver for each different database. • Ex:
A native-protocol fully Java technology-enabled driver converts JDBC technology calls into • import java.sql.*;
the network protocol used by DBMSs directly. This allows a direct call from the client
machine to the DBMS server. Step 2: Load the JDBC Driver

Advantages for using this type of driver include the following: • Load the JDBC driver to connect to your database.

• Allows access to almost any database since the databases ODBC drivers are readily • This step is optional in newer versions of Java (JDBC 4.0 and later), as the driver is
available automatically loaded.
• Offers significantly better performance than the JDBC/ODBC Bridge and Type 2 • // For MySQL
Drivers
• Class.forName("com.mysql.cj.jdbc.Driver");
• Scalable
• // For Oracle
• Caching
• Class.forName("oracle.jdbc.driver.OracleDriver");
• Advanced system administration
Step 3: Create a Connection/Establish Connection
• Superior performance
• Establish a connection to the database using the DriverManager class.
• Advance Java feature set
• // MySQL
• Does not require applicable database client libraries
• syntax
• Connection con =
DriverManager.getConnection("jdbc:mysql://hostname:port/dbname", "username",
"password");
• // Oracle • rs.close();
• syntax • stmt.close();
• Connection con = • con.close(); //mandatory
DriverManager.getConnection("jdbc:oracle:thin:@hostname:port:dbname",
"username", "password");
Ex:
• Connection con=DriverManager.getConnection(
import java.io.*;
• "jdbc:oracle:thin:@localhost:1521:xe","system","password");
import java.sql.*;
Step 4:Create a Statement Object
class DemoDB{
• Use the connection object to create a Statement object.
public static void main(String args[]) throws IOException, SQLException {
• This object is used to execute SQL queries.
try{
• Statement stmt = con.createStatement();
Class.forName("oracle.jdbc.OracleDriver");
Step 5: Execute a Query
Connectioncon=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe"
• Execute SQL queries using the Statement object.
,"system","system");
• // For executing a SELECT query
System.out.println("connected to Oracle db");
• ResultSet rs = stmt.executeQuery("SELECT * FROM tablename");
con.close();}
• // For executing an INSERT/UPDATE/DELETE query
catch(Exception e){
• int rowsAffected = stmt.executeUpdate("INSERT INTO tablename (column1,
e.printStackTrace();
column2) VALUES (value1, value2)");
}}}
Step 6: Process the Result Set
• If you executed a SELECT query, process the ResultSet to retrieve data.
• while (rs.next()) { Difference Between executeQuery() Vs executeUpdate() Vs
• int id = rs.getInt("id");
execute() In JDBC
• String name = rs.getString("name"); ResultSet executeQuery(String sql) throws SQLException :

• // Process the data... • This method is used for SQL statements which retrieve some data from the database.

• } • For example is SELECT statement.

• ResultSet rs=stmt.executeQuery("select * from emp"); • This method is meant to be used for select queries which fetch some data from the
database.
• while(rs.next()){
• This method returns one java.sql.ResultSet object which contains the data returned by
• System.out.println(rs.getInt(1)+" "+rs.getString(2)); the query.
• } • import java.sql.*;
Step 7: Close the Connections • class Test {
• Always close the ResultSet, Statement, and Connection objects to free up database • public static void main(String args []) throws Exception {
resources.
• //step-l load the driver (Type-l) • //step-3 create Statement object
• Class.forName ( “ "); • Statement st=cn.createStatement () ;
• //step-2 get the connection • //step-4 execute sql statement
• Connection cn=DriverManager.getConnection (“ ") ; • int k=st.executeUpdate("create table student(name varchar2(20),roll number (7) )");
• //step-3 create Statement, object • if(k<0) {
• Statement st=cn.createStatement(); • System.out.println ("Table created");
• //step-4 execute sql statement • } else {
• ResultSet rs=st .executeQuery ("select * from emp"); • System.out.println("table is not created");}
• //step-5 print the output • cn.close();}}
• while(rs.next ()) { boolean execute(String sql) throws SQLException
• int empno=rs.getInt(1); • This method can be used for all types of SQL statements(both select and non-select
• String ename=rs.getString(2); operation).

• System.out .println ("Employee no "+empno+"Employee name "+ename);} • If you don’t know which method to use for you SQL statements, then this method can
be the best option.
• //step-6 close connection and Statement and .Resultset
• This method returns a boolean value.
• cn.close () ;}}
• boolean b=st.execute(“select * from emp”);
• If we execute select operation then return true.
int executeUpdate(String sql) throws SQLException
• boolean b=st.execute(“create table student(name varchar2(15),roll name(7))”);
• This method is used for SQL statements which update the database in some way.
If we execute non-select operation then return false.
• For example INSERT, UPDATE and DELETE statements.
• All these statements are DML(Data Manipulation Language) statements.
Statement st=cn.createStatement( ) ;
• This method returns an int value which represents the number of rows affected by the
//step-4 execute sql statement
query.
boolean b=st.execute("select * from emp");
• This value will be 0 for the statements which return nothing.
if(b==true) {
• import java.sql.*;
System.out.println ("select operation done") ;
• class CreateTable {
ResultSet rs=st.getResultSet ();
• public static void main(String args[]) throws Exception {
//step-5 print the output
• //step-1 load the driver(Type - 2)
while(rs.next( )) {
• Class.forName (“ ") ;
int rno=rs.getInt(1);
• //step-2 get the connection
String name=rs.getString (2) ;
• Connectioncn=DriverManager.getConnection("jdbc:oracle:thin:@XE:1521","system
","manager"); System.out.println("ROll No "+rno+" Name :" +name);
}}
else {
System.out.println( "non-select operation is done");
int k=st.executeUpdateCount() ;}
//step-6 close connection
cn.close () ;
}}

Statement Interface
• The Statement interface represents the static SQL statement.
• It helps you to create a general purpose SQL statements using Java.
• Creating a statement:
• You can create an object of this interface using the createStatement() method of
the Connection interface.
Connection cn=DriverManager.getConnection (“ ") ;
//create Statement, object
Statement, PreparedStatement and CallableStatement in JDBC Statement st=cn.createStatement();
• A JDBC statement object is used to execute an SQL statement. // execute sql statement
• JDBC API supports three types of JDBC statement object to work with the SQL ResultSet rs=st .executeQuery ("select * from emp");
statements.
Int rows=st.excuteUpdate();
• In JDBC we get three types of statements:
Boolean abc=st.excute();
Statement Interface
Prepared Statement:
PreparedStatement Interface
• A PreparedStatement represents a precompiled SQL statement that can be executed
CallableStatement Interface
multiple times.
• It accepts parameterized SQL queries, with ? as placeholders for parameters, which
can be set dynamically.
• Considering in the people database if there is a need to INSERT some values, SQL
statements such as these are used:
• INSERT INTO student VALUES ("Ajay",20); • PreparedStatement stmt=con.prepareStatement("select * from emp");
• INSERT INTO student VALUES("Kiran",21); • ResultSet rs=stmt.executeQuery();
• In Java, one may use Prepared Statements and set the values in the ? holders, • while(rs.next()){
setInt(),setString(),setFloat() of a prepared statement is used as shown:
• System.out.println(rs.getInt(1)+" "+rs.getString(2));
• String query = "INSERT INTO people(name, age)VALUES(?, ?)";
• }
• PreparedStatement pstmt = con.prepareStatement(query);
• Example of PreparedStatement interface that updates the record
pstmt.setString(1,"Ajay");//1 specifies the first parameter in the query
• PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?")
• ptstmt.setInt(2,20);//2 specifies the first parameter in the query ;
• // where pstmt is an object name • stmt.setString(1,"Sonu");//1 specifies the first parameter in the query i.e. name
• execute(): This returns a boolean value and executes a static SQL statement that is • stmt.setInt(2,101);
present in the prepared statement object.
• int i=stmt.executeUpdate();
• executeQuery(): Returns a ResultSet from the current prepared statement.
• System.out.println(i+" records updated");
• executeUpdate(): Returns the number of rows affected by the DML statements such
• Example of PreparedStatement interface that deletes the record.
as INSERT, DELETE, and more that is present in the current Prepared Statement.
• PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
• //Example on insert record into corresponding table using Prepared stmt:
• stmt.setInt(1,101);
• import java.sql.*;
• int i=stmt.executeUpdate();
• class InsertPrepared{
• System.out.println(i+" records deleted");
• public static void main(String args[]){
• try{ • Callable Statement:
• Class.forName("oracle.jdbc.driver.OracleDriver");
• CallableStatement interface is used to call the stored procedures and functions.
• Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
• Stored procedures are precompiled SQL statements that can be called with
","system","oracle");
parameters.
• PreparedStatement pstmt=con.prepareStatement("insert into Emp values(?,?)");
• They are useful for executing complex operations that involve multiple SQL
• pstmt.setInt(1,101);//1 specifies the first parameter in the query statements.The difference between stored procedures and functions.
• pstmt.setString(2,"Ratan");
• int i=pstmt.executeUpdate();
• System.out.println(i+" records inserted");
• con.close();
• }catch(Exception e)
• { System.out.println(e);}
• } }
• Example of PreparedStatement interface that retrieve the records of a table.
stmt.execute();
Creating a CallableStatement System.out.println("success"); } }
• You can create an object of the CallableStatement (interface) using the prepareCall() • To use Callable Statements in JDBC with an Oracle database:
method of the Connection interface.
• Load the Oracle JDBC DriverLoad the Oracle JDBC driver using Class.forName().
• This method accepts a string variable representing a query to call the stored procedure
• Class.forName("oracle.jdbc.driver.OracleDriver");
and returns a CallableStatement object.
• Establish a Database ConnectionUse DriverManager.getConnection() to establish a
How to get the instance of CallableStatement?
connection to the Oracle database:
• The prepareCall() method of Connection interface returns the instance of
• Connection con = DriverManager.getConnection(
CallableStatement.
"jdbc:oracle:thin:@localhost:1521:xe", "username", "password");
• Syntax is given below:
• Create the Stored Procedure in OracleEnsure that your Oracle database has a stored
• public CallableStatement prepareCall("{ call procedurename(?,?...?)}"); procedure available.
• The example to get the instance of CallableStatement is given below: • Here’s an example of a stored procedure:
• CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}"); • CREATE OR REPLACE PROCEDURE getEmployeeSalary ( empId IN
NUMBER, empSalary OUT NUMBER)
• It calls the procedure myprocedure that receives 2 arguments.
• AS
Example to call the stored procedure using JDBC
• BEGIN
• To call the stored procedure, you need to create it in the database. Here, we are
assuming that stored procedure looks like this. • SELECT salary INTO empSalary FROM Employees WHERE id = empId;

• create or replace procedure addinfo (id IN number, • END;

• name IN varchar2(15)) is /as • Prepare Callable StatementCreate a CallableStatement object for calling the stored
procedure.
• begin
• For Oracle, the syntax is the same:
• insert into student values( id, name);
• CallableStatement stmt = con.prepareCall("{call getEmployeeSalary(?, ?)}");
• end;
• Set Input ParametersSet the input parameters using the setX() methods:
• stmt.setInt(1, 101); // Set employee ID
import java.sql.*;
• Register Output ParametersRegister the output parameter using
public class Proc { registerOutParameter().
public static void main(String[] args) throws Exception{ • Oracle uses specific types like Types.NUMERIC, Types.VARCHAR, etc.:
Class.forName("oracle.jdbc.driver.OracleDriver"); • stmt.registerOutParameter(2, Types.NUMERIC); // Register output for employee
Connection con=DriverManager.getConnection( salary
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); • Execute the Callable StatementExecute the callable statement using the execute()
CallableStatement stmt=con.prepareCall("{call addinfo(?,?)}"); method:’

stmt.setInt(1,1011); • stmt.execute();

stmt.setString(2,"Arun");
• Retrieve Output Parameters.After the procedure execution, retrieve the value of the • class RSMD1 {
output parameter:
• public static void main (String[] args) {
• double empSalary = stmt.getDouble(2);
• try {
• System.out.println("Employee Salary: " + empSalary);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
ResultSetMetaData and DatabaseMetadata in JDBC • "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
ResultSetMetaData • Statement stmt = con.createStatement(); // creating object of statement
• ResultSetMetaData is an interface in Java under the interface
package java.sql.ResultSetMetaData which can be used in determining or retrieving • String query = "SELECT * FROM EMP";
the structural characteristics of a table’s ResultSet.
• ResultSet rs = stmt.executeQuery(query);
• It is not always necessary for the programmer to know the structural information of a
ResultSet column (such as name, datatype, count, or other information associated with • ResultSetMetaData rstmd = rs.getMetaData(); // creating an object of
a specific column) being returned by the ResultSet object’s get( ) method. Resultsetmetadata Interface

• If you have to get metadata of a table like total number of column, column name, • int columnsNumber = rstmd.getColumnCount(); // getting the number of
column type etc. , ResultSetMetaData interface is useful because it provides methods column in table
to get metadata from the ResultSet object. • System.out.println("Column Number: " + columnsNumber);
• } catch (Exception e) {
• e.printStackTrace();
• }}}
• To print all Column types
• // Creating object of statement interface
• Statement stmt = con.createStatement();
• String query = "SELECT * FROM testtable";
• ResultSet rs = stmt.executeQuery(query);
• // Creating an object of Resultsetmetadata Interface
How to get the object of ResultSetMetaData • ResultSetMetaData rstmd = rs.getMetaData();

• The getMetaData() method of ResultSet interface returns the object of System.out.println("Type of column 1 :" + rstmd.getColumnTypeName(1));
ResultSetMetaData.
System.out.println("Type of column 2 :" + rstmd.getColumnTypeName(2));
• Syntax:
System.out.println("Type of column 3 :" + rstmd.getColumnTypeName(3)); }
• public ResultSetMetaData getMetaData()throws SQLException
---------------------------------------------------------------------------------------------
Ex: • import java.sql.*;
• import java.sql.*; • class Rsmd2 {
• public static void main(String args[]) { DatabaseMetaData Interface
• try{ • The DatabaseMetaData interface provides comprehensive information about the
• Class.forName("oracle.jdbc.driver.OracleDriver"); database, including its structure, capabilities, and the data it contains.

• Connection con=DriverManager.getConnection( • This is useful when you need to query database-level information, such as the list of
tables, supported SQL features, or database version.
• "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
• String getDriverName(): it returns the name of the JDBC driver.
• PreparedStatement ps=con.prepareStatement("select * from emp");
• String getDriverVersion(): it returns the version number of the JDBC driver.
• ResultSet rs=ps.executeQuery();
• String getUserName(): it returns the username of the database.
• ResultSetMetaData rsmd=rs.getMetaData();
• String getDatabaseProductName(): it returns the product name of the database.
• System.out.println("Total columns: "+rsmd.getColumnCount());
• String getDatabaseProductVersion(): it returns the product version of the database.
• System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
How to get the object of DatabaseMetaData
• System.out.println("Column Type Name of 1st column:
"+rsmd.getColumnTypeName(1)); } • The getMetaData() method of Connection interface returns the object of
DatabaseMetaData.
• catch(Exception e){
• Syntax:
• System.out.println(e);}
• public DatabaseMetaData getMetaData()throws SQLException
• } }
• Connection con=DriverManager.getConnection(
• ResultSet rs = statement.executeQuery("SELECT * FROM EMP");
• "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
• ResultSetMetaData rsMetaData = rs.getMetaData();
• DatabaseMetaData dbmd=con.getMetaData();
• int columnCount = rsMetaData.getColumnCount();
• System.out.println("Driver Name: "+dbmd.getDriverName());
• for (int i = 1; i <= columnCount; i++) {
• System.out.println("Driver Version: "+dbmd.getDriverVersion());
• System.out.println("Column " + i + ": " +rsMetaData.getColumnName(i) + " of type
" + rsMetaData.getColumnTypeName(i));} • System.out.println("UserName: "+dbmd.getUserName());

• • System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());


• System.out.println("Database Product Version:
"+dbmd.getDatabaseProductVersion());
UNIT-3
Servlet
SERVLET
• A servlet is a Java class that extends the capabilities of a server that hosts applications using
a request-response model. Servlets are often used to extend web server applications,and are a
key part of developing dynamic web content.

What they do
• Servlets can respond to any type of request,but are most commonly used to exten webserver
applications. They handle requests andprovide responses, usually in the form of an HTML
page.

How they work


• Servlets are Java classes that run in a Java-enabled server. They subclass from the class
HttpServlet and usually override the doGet or doPost method.

How to write them


• The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing
servlets. All servlets must implement the Servlet interface, which defines life-cycle methods.
Initializing a Servlet:
Some types of servlets • After the Servlet is instantiated successfully, the Servlet container initializes the instantiated
• HTTP servlets are a special type of servlet that handle HTTP requests and provide HTTP Servlet object. The container initializes the Servlet object by invoking
responses. Servlet.init(ServletConfig) method which accepts ServletConfig object reference as
parameter.The Servlet container invokes the Servlet.init(ServletConfig) method only
Stages of the Servlet Life Cycle:
once,immediately afterthe Servlet.init(ServletConfig) object is instantiated successfully. This
• The Servlet life cycle mainly goes through four
method is used to initialize the resources, such as JDBC datasource.
stages,
• Loading a Servlet. Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing the
• Initializing the Servlet. ServletException or UnavailableException.
• Request handling.
• Destroying the Servlet.
Loading a Servlet: The first stage of the Servlet lifecycle involves loading and initializing the Handling request: After initialization, the Servlet instance is ready to serve the client
Servlet by the Servlet container. The Web container or Servlet Container can load the Servlet requests. The Servlet container performs the following operations when the Servlet
at either of the following two stages : instance is located to service a request :It creates the ServletRequest and ServletResponse
– Initializing the context, on configuring the Servlet with a zero or positive integer value. objects. In this case, if this is a HTTP request, then the Web container creates
– If the Servlet is not preceding stage, it may delay the loading process until the Web HttpServletRequest and HttpServletResponse objects which are subtypes of the
container determines that this Servlet is needed to service a request. ServletRequest and ServletResponse objects respectively.
• After creating the request and response objects it invokesthe Servlet.service(ServletRequest,
The Servlet container performs two operations in this stage :
ServletResponse)method by passing the request and response objects.
Loading : Loads the Servlet class.
Instantiation : Creates an instance of the Servlet. To create a new instance of The service() method while processing the request may throw the ServletException or
the Servlet, the container uses the no-argument constructor. UnavailableException or IOException.
• Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs
the following operations,
– It allows all the threads currently running in the service method of the Servlet instance to
complete their jobs and get released.
After currently running threads have completed their jobs, the Servlet container calls the
destroy() method on the Servlet instance.
• After the destroy() method is executed, the Servlet container releases all the references of
this Servlet instance so that it becomes eligible for garbage collection.
import java.io.IOException; java
import java.io.PrintWriter; Copy code
public class MyServlet extends HttpServlet {
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; • The class MyServlet extends HttpServlet, making it a servlet that can handle HTTP
requests.
public class MyServlet extends HttpServlet { • By extending HttpServlet, this class gains the ability to override specific methods (such
as doGet) to handle HTTP methods.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { 3. doGet Method
// Set the response content type
response.setContentType("text/html"); java
Copy code
public void doGet(HttpServletRequest request, HttpServletResponse response)
// Use PrintWriter to send response to the client throws IOException {
PrintWriter out = response.getWriter();
out.println("<html><body>");
• This method overrides doGet to handle GET requests.
out.println("<h1>Hello Readers</h1>");
• The request parameter contains all data sent by the client (such as form data or URL
out.println("</body></html>");
} parameters).
} • The response parameter allows us to send data back to the client.

Explanation of the Program 4. Setting the Content Type

The Java servlet you've provided is a simple servlet class that sends an HTML response to the java
Copy code
client when a GET request is made. Let’s go through each part step by step. response.setContentType("text/html");

1. Import Statements • This sets the content type of the response to text/html, indicating to the client (usually a
web browser) that the response content will be in HTML format.
java
Copy code
import java.io.IOException; 5. Writing the Response Using PrintWriter
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet; java
import javax.servlet.http.HttpServletRequest; Copy code
import javax.servlet.http.HttpServletResponse; PrintWriter out = response.getWriter();

These import statements bring in the necessary classes to create and manage the servlet: • PrintWriter is used to write HTML directly to the response object.
• Here, response.getWriter() provides a PrintWriter that lets us write to the HTTP
• java.io.IOException: This is for handling input-output exceptions. response body.
• java.io.PrintWriter: This class is used to write data to the response.
• javax.servlet.http.HttpServlet: This is the base servlet class that our class will 6. Sending HTML Content
extend.
• javax.servlet.http.HttpServletRequest and java
javax.servlet.http.HttpServletResponse: These provide methods to handle HTTP Copy code
out.println("<html><body>");
request and response data. out.println("<h1>Hello Readers</h1>");
out.println("</body></html>");
2. Class Declaration
• The out.println statements are used to write the HTML code to the response.
• This code sends a simple HTML page with the content <h1>Hello Readers</h1>. </servlet>
<servlet-mapping>
• The <html><body> tags define the structure of the HTML document, with <h1> defining <servlet-name>MyServlet</servlet-name>
a header text. <url-pattern>/myServlet</url-pattern>
</servlet-mapping>
7. End of Class </web-app>

• The servlet class is closed after the doGet method. This servlet will output a simple 3. Start Tomcat:
HTML page saying "Hello Readers" whenever accessed via a GET request. o Start the Tomcat server if it isn’t already running. You can typically do this
through the Tomcat bin directory by running startup.bat (Windows) or
startup.sh (Linux/macOS).
Summary
4. Access the Servlet in a Browser:
o Open a web browser and go to:
This servlet, MyServlet, is a basic example that sends an HTML page as a response to a GET
request. When accessed, it displays "Hello Readers" within an HTML page on the client browser. bash
Copy code
http://localhost:8080/MyApp/myServlet
To run the servlet program
In Command Prompt: o This URL will trigger your servlet, and you should see the output as defined in
MyServlet.java.
C:\javaprg>javac -cp ".;C:\Program Files\Apache Software Foundation\Tomcat 9.0\lib\servlet-api.jar"
MyServlet.java Note

If Tomcat’s default port 2525 has been changed, replace it with the correct port number. Also,
TO RUN servlets:
replace MyApp with your actual application name if it’s different.
Steps to Run the Servlet on Tomcat Let me know if you need more guidance on any step!
1. Deploy the Servlet on Tomcat:
o Move the compiled MyServlet.class file to the appropriate location in Tomcat’s
webapps directory.
o For example, if your web application is named MyApp, place MyServlet.class
under:

makefile
Copy code
C:\Program Files\Apache Software Foundation\Tomcat
9.0\webapps\MyApp\WEB-INF\classes

2. Configure web.xml:
o Inside your web application's WEB-INF directory, you’ll need a web.xml file to
define the servlet and map a URL to it.
o Example web.xml configuration:

xml
Copy code
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
Page 1 of 5 Page 2 of 5

public void init(FilterConfig filterConfig)


Servlets - Writing Filters 2 This method is called by the web container to indicate to a filter that it is being
placed into service.
Servlet Filters are Java classes that can be used in Servlet Programming for the following
public void destroy()
purposes −
3 This method is called by the web container to indicate to a filter that it is being
taken out of service.
To intercept requests from a client before they access a resource at back end.

To manipulate responses from server before they are sent back to the client.
Servlet Filter − Example
Following is the Servlet Filter Example that would print the clients IP address and current
There are various types of filters suggested by the specifications −
date time. This example would give you basic understanding of Servlet Filter, but you can
write more sophisticated filter applications using the same concept −
Authentication Filters.

Data compression Filters. // Import required java libraries


Encryption Filters. import java.io.*;
import javax.servlet.*;
Filters that trigger resource access events.
import javax.servlet.http.*;
Image Conversion Filters. import java.util.*;
Logging and Auditing Filters.
// Implements Filter class
MIME-TYPE Chain Filters.
public class LogFilter implements Filter {
Tokenizing Filters . public void init(FilterConfig config) throws ServletException {

XSL/T Filters That Transform XML Content.


// Get init parameter
String testParam = config.getInitParameter("test-param");
Filters are deployed in the deployment descriptor file web.xml and then map to either
servlet names or URL patterns in your application's deployment descriptor. //Print the init parameter
System.out.println("Test Param: " + testParam);
When the web container starts up your web application, it creates an instance of each
}
filter that you have declared in the deployment descriptor. The filters execute in the order
that they are declared in the deployment descriptor.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws java.io.IOException, ServletException {
Servlet Filter Methods
// Get the IP address of client machine.
A filter is simply a Java class that implements the javax.servlet.Filter interface. The
String ipAddress = request.getRemoteAddr();
javax.servlet.Filter interface defines three methods −

// Log the IP address and current timestamp.


Sr.No. Method & Description
System.out.println("IP "+ ipAddress + ", Time " + new Date().toString());
public void doFilter (ServletRequest, ServletResponse, FilterChain)
This method is called by the container each time a request/response pair is // Pass request back down the filter chain
1 chain.doFilter(request,response);
passed through the chain due to a client request for a resource at the end of
the chain. }
Page 3 of 5 Page 4 of 5

public void destroy( ) {


<filter>
/* Called before the Filter instance is removed from service by the web cont
} <filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
}
<init-param>
<param-name>test-param</param-name>
Compile LogFilter.java in usual way and put your class file in <Tomcat- <param-value>Initialization Paramter</param-value>
installationdirectory>/webapps/ROOT/WEB-INF/classes </init-param>
</filter>
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
<filter>
<filter-name>AuthenFilter</filter-name>
Servlet Filter Mapping in Web.xml <filter-class>AuthenFilter</filter-class>
<init-param>
Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet
<param-name>test-param</param-name>
is defined and then mapped to a URL pattern. Create the following entry for filter tag in
<param-value>Initialization Paramter</param-value>
the deployment descriptor file web.xml
</init-param>
</filter>
<filter>
<filter-name>LogFilter</filter-name> <filter-mapping>
<filter-class>LogFilter</filter-class> <filter-name>LogFilter</filter-name>
<init-param> <url-pattern>/*</url-pattern>
<param-name>test-param</param-name> </filter-mapping>
<param-value>Initialization Paramter</param-value>
</init-param> <filter-mapping>
</filter> <filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
<filter-mapping> </filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> Filters Application Order
The order of filter-mapping elements in web.xml determines the order in which the web
The above filter would apply to all the servlets because we specified /* in our
container applies the filter to the servlet. To reverse the order of the filter, you just need to
configuration. You can specicy a particular servlet path if you want to apply filter on few
reverse the filter-mapping elements in the web.xml file.
servlets only.
For example, above example would apply LogFilter first and then it would apply
Now try to call any servlet in usual way and you would see generated log in your web
AuthenFilter to any servlet but the following example would reverse the order −
server log. You can use Log4J logger to log above log in a separate file.

<filter-mapping>
Using Multiple Filters
<filter-name>AuthenFilter</filter-name>
Your web application may define several different filters with a specific purpose. Consider, <url-pattern>/*</url-pattern>
you define two filters AuthenFilter and LogFilter. Rest of the process would remain as </filter-mapping>
explained above except you need to create a different mapping as mentioned below −
<filter-mapping>
<filter-name>LogFilter</filter-name>
Page 5 of 5

<url-pattern>/*</url-pattern>
</filter-mapping>
Page 1 of 6 Page 2 of 6

This header instructs the browser whether to use persistent in HTTP


connections or not. A value of close instructs the browser not to use persistent
Servlets - Server HTTP Response HTTP connections and keepalive means using persistent connections.

As discussed in the previous chapter, when a Web server responds to an HTTP request, the Content-Disposition
response typically consists of a status line, some response headers, a blank line, and the 4 This header lets you request that the browser ask the user to save the
document. A typical response looks like this − response to disk in a file of the given name.

Content-Encoding
HTTP/1.1 200 OK
5 This header specifies the way in which the page was encoded during
Content-Type: text/html
transmission.
Header2: ...
... Content-Language
HeaderN: ... 6 This header signifies the language in which the document is written. For
(Blank Line) example en, en-us, ru, etc
<!doctype ...>
Content-Length
<html>
7 This header indicates the number of bytes in the response. This information is
<head>...</head>
needed only if the browser is using a persistent (keep-alive) HTTP connection.
<body>
... Content-Type
</body> 8 This header gives the MIME (Multipurpose Internet Mail Extension) type of the
</html> response document.

Expires
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 9 This header specifies the time at which the content should be considered out-
in the example), and a very short message corresponding to the status code (OK in the of-date and thus no longer be cached.
example).
Last-Modified
Following is a summary of the most useful HTTP 1.1 response headers which go back to This header indicates when the document was last changed. The client can
the browser from web server side and you would use them very frequently in web 10
then cache the document and supply a date by an If-Modified-Since request
programming − header in later requests.

Sr.No. Header & Description Location


This header should be included with all responses that have a status code in
11
Allow the 300s. This notifies the browser of the document address. The browser
1 This header specifies the request methods (GET, POST, etc.) that the server automatically reconnects to this location and retrieves the new document.
supports.
Refresh
Cache-Control This header specifies how soon the browser should ask for an updated page.
12
This header specifies the circumstances in which the response document can You can specify time in number of seconds after which a page would be
safely be cached. It can have values public, private or no-cache etc. Public refreshed.
2
means document is cacheable, Private means document is for a single user and
can only be stored in private (non-shared) caches and nocache means Retry-After
document should never be cached. 13 This header can be used in conjunction with a 503 (Service Unavailable)
response to tell the client how soon it can repeat its request.
3 Connection
14 Set-Cookie
Page 3 of 6 Page 4 of 6

This header specifies a cookie associated with the page.


void sendError(int sc)
12 Sends an error response to the client using the specified status code and
Methods to Set HTTP Response Header clearing the buffer.

There are following methods which can be used to set HTTP response header in your void sendError(int sc, String msg)
13
servlet program. These methods are available with HttpServletResponse object. Sends an error response to the client using the specified status.

void sendRedirect(String location)


Sr.No. Method & Description
14 Sends a temporary redirect response to the client using the specified redirect
String encodeRedirectURL(String url) location URL.
1 Encodes the specified URL for use in the sendRedirect method or, if encoding is
void setBufferSize(int size)
not needed, returns the URL unchanged. 15
Sets the preferred buffer size for the body of the response.
String encodeURL(String url)
void setCharacterEncoding(String charset)
2 Encodes the specified URL by including the session ID in it, or, if encoding is
16 Sets the character encoding (MIME charset) of the response being sent to the
not needed, returns the URL unchanged.
client, for example, to UTF-8.
boolean containsHeader(String name)
void setContentLength(int len)
3 Returns a Boolean indicating whether the named response header has already
17 Sets the length of the content body in the response In HTTP servlets, this
been set.
method sets the HTTP Content-Length header.
boolean isCommitted()
4 void setContentType(String type)
Returns a Boolean indicating if the response has been committed.
18 Sets the content type of the response being sent to the client, if the response
void addCookie(Cookie cookie) has not been committed yet.
5
Adds the specified cookie to the response.
void setDateHeader(String name, long date)
19
void addDateHeader(String name, long date) Sets a response header with the given name and date-value.
6
Adds a response header with the given name and date-value.
void setHeader(String name, String value)
20
void addHeader(String name, String value) Sets a response header with the given name and value.
7
Adds a response header with the given name and value.
void setIntHeader(String name, int value)
21
void addIntHeader(String name, int value) Sets a response header with the given name and integer value
8
Adds a response header with the given name and integer value.
void setLocale(Locale loc)
22
void flushBuffer() Sets the locale of the response, if the response has not been committed yet.
9
Forces any content in the buffer to be written to the client.
void setStatus(int sc)
23
void reset() Sets the status code for this response
10 Clears any data that exists in the buffer as well as the status code and
headers.
HTTP Header Response Example
void resetBuffer() You already have seen setContentType() method working in previous examples and
11 Clears the content of the underlying buffer in the response without clearing following example would also use same method, additionally we would use
headers or status code. setIntHeader() method to set Refresh header.
Page 5 of 6 Page 6 of 6

}
// Import required java libraries
import java.io.*; // Method to handle POST method request.
import javax.servlet.*;
public void doPost(HttpServletRequest request, HttpServletResponse response)
import javax.servlet.http.*; throws ServletException, IOException {
import java.util.*;

doGet(request, response);
// Extend HttpServlet class
}
public class Refresh extends HttpServlet { }

// Method to handle GET method request.


public void doGet(HttpServletRequest request, HttpServletResponse response) Now calling the above servlet would display current system time after every 5 seconds as
throws ServletException, IOException { follows. Just run the servlet and wait to see the result −

// Set refresh, autoload time as 5 seconds


response.setIntHeader("Refresh", 5);
Auto Refresh Header Setting
Current Time is: 9:44:50 PM
// Set response content type
response.setContentType("text/html");

// Get current time


Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";

String CT = hour+":"+ minute +":"+ second +" "+ am_pm;

PrintWriter out = response.getWriter();


String title = "Auto Refresh Header Setting";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n"
);
Page 1 of 5 Page 2 of 5

101 Switching Protocols The server switches protocol.


Servlets - Http Status Codes 200 OK The request is OK

The format of the HTTP request and HTTP response messages are similar and will have The request is complete, and a new resource
following structure − 201 Created
is created

The request is accepted for processing, but


An initial status line + CRLF ( Carriage Return + Line Feed i.e. New Line ) 202 Accepted
the processing is not complete.
Zero or more header lines + CRLF
203 Non-authoritative Information
A blank line, i.e., a CRLF

An optional message body like file, query data or query output. 204 No Content

205 Reset Content


For example, a server response header looks as follows −
206 Partial Content

HTTP/1.1 200 OK
A link list. The user can select a link and go to
Content-Type: text/html 300 Multiple Choices
that location. Maximum five addresses
Header2: ...
... 301 Moved Permanently The requested page has moved to a new url
HeaderN: ...
The requested page has moved temporarily to
(Blank Line) 302 Found
a new url
<!doctype ...>
<html> The requested page can be found under a
303 See Other
<head>...</head> different url
<body>
... 304 Not Modified
</body>
305 Use Proxy
</html>
This code was used in a previous version. It is
306 Unused
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 no longer used, but the code is reserved
in the example), and a very short message corresponding to the status code (OK in the
The requested page has moved temporarily to
example). 307 Temporary Redirect
a new url.
Following is a list of HTTP status codes and associated messages that might be returned
400 Bad Request The server did not understand the request
from the Web Server −
The requested page needs a username and a
Code Message Description 401 Unauthorized
password

Only a part of the request has been received 402 Payment Required You cannot use this code yet
by the server, but as long as it has not been
100 Continue
rejected, the client should continue with the 403 Forbidden Access is forbidden to the requested page
request
404 Not Found The server cannot find the requested page.
Page 3 of 5 Page 4 of 5

The method specified in the request is not 504 Gateway Timeout The gateway has timed out.
405 Method Not Allowed
allowed.
The server does not support the "http
505 HTTP Version Not Supported
The server can only generate a response that protocol" version.
406 Not Acceptable
is not accepted by the client.

You must authenticate with a proxy server Methods to Set HTTP Status Code
407 Proxy Authentication Required
before this request can be served.
The following methods can be used to set HTTP Status Code in your servlet program.
The request took longer than the server was These methods are available with HttpServletResponse object.
408 Request Timeout
prepared to wait.
Sr.No. Method & Description
The request could not be completed because
409 Conflict
of a conflict. public void setStatus ( int statusCode )
This method sets an arbitrary status code. The setStatus method takes an int
410 Gone The requested page is no longer available. 1 (the status code) as an argument. If your response includes a special status
code and a document, be sure to call setStatus before actually returning any of
The "Content-Length" is not defined. The
411 Length Required the content with the PrintWriter.
server will not accept the request without it.
public void sendRedirect(String url)
The precondition given in the request
412 Precondition Failed 2 This method generates a 302 response along with a Location header giving the
evaluated to false by the server.
URL of the new document

The server will not accept the request,


413 Request Entity Too Large public void sendError(int code, String message)
because the request entity is too large.
3 This method sends a status code (usually 404) along with a short message that
is automatically formatted inside an HTML document and sent to the client.
The server will not accept the request,
because the url is too long. Occurs when you
414 Request-url Too Long
convert a "post" request to a "get" request HTTP Status Code Example
with a long query information.
Following is the example which would send a 407 error code to the client browser and
The server will not accept the request, browser would show you "Need authentication!!!" message.
415 Unsupported Media Type
because the media type is not supported.

417 Expectation Failed // Import required java libraries


import java.io.*;
The request was not completed. The server import javax.servlet.*;
500 Internal Server Error
met an unexpected condition. import javax.servlet.http.*;
import java.util.*;
The request was not completed. The server
501 Not Implemented
did not support the functionality required. // Extend HttpServlet class
public class showError extends HttpServlet {
The request was not completed. The server
502 Bad Gateway received an invalid response from the
// Method to handle GET method request.
upstream server.
public void doGet(HttpServletRequest request, HttpServletResponse response)
The request was not completed. The server is throws ServletException, IOException {
503 Service Unavailable
temporarily overloading or down.
// Set error code and reason.
Page 5 of 5

response.sendError(407, "Need authentication!!!" );


}

// Method to handle POST method request.


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

Now calling the above servlet would display the following result −

HTTP Status 407 - Need authentication!!!


type Status report

messageNeed authentication!!!

descriptionThe client must first authenticate itself with the proxy (Need authentication!!!)

Apache Tomcat/5.5.29
Page 1 of 10 Page 2 of 10

getParameterValues() − Call this method if the parameter appears more than


once and returns multiple values, for example checkbox.
Servlets - Form Data getParameterNames() − Call this method if you want a complete list of all

You must have come across many situations when you need to pass some information parameters in the current request.
from your browser to web server and ultimately to your backend program. The browser
uses two methods to pass this information to web server. These methods are GET Method
and POST Method.
GET Method Example using URL
Here is a simple URL which will pass two values to HelloForm program using GET method.
GET Method
http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI
The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ? (question mark) symbol as Given below is the HelloForm.java servlet program to handle input given by web
follows − browser. We are going to use getParameter() method which makes it very easy to
access passed information −

http://www.test.com/hello?key1 = value1&key2 = value2


// Import required java libraries
import java.io.*;
The GET method is the default method to pass information from browser to web server
import javax.servlet.*;
and it produces a long string that appears in your browser's Location:box. Never use the import javax.servlet.http.*;
GET method if you have password or other sensitive information to pass to the server. The
GET method has size limitation: only 1024 characters can be used in a request string. // Extend HttpServlet class
public class HelloForm extends HttpServlet {
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using
public void doGet(HttpServletRequest request, HttpServletResponse response)
doGet() method.
throws ServletException, IOException {

POST Method // Set response content type


A generally more reliable method of passing information to a backend program is the POST response.setContentType("text/html");
method. This packages the information in exactly the same way as GET method, but
instead of sending it as a text string after a ? (question mark) in the URL it sends it as a PrintWriter out = response.getWriter();
separate message. This message comes to the backend program in the form of the String title = "Using GET Method to Read Form Data";
standard input which you can parse and use for your processing. Servlet handles this type String docType =
of requests using doPost() method. "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"

Explore our latest online courses and learn new skills at your own pace. Enroll and out.println(docType +
become a certified expert to boost your career. "<html>\n" +
"<head><title>" + title + "</title></head>\n" +
Reading Form Data using Servlet "<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
Servlets handles form data parsing automatically using the following methods depending "<ul>\n" +
on the situation − " <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
getParameter() − You call request.getParameter() method to get the value of a " <li><b>Last Name</b>: "
form parameter. + request.getParameter("last_name") + "\n" +
Page 3 of 10 Page 4 of 10

"</ul>\n" +
<html>
"</body>" +
"</html>" <body>
<form action = "HelloForm" method = "GET">
);
} First Name: <input type = "text" name = "first_name">
<br />
}
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
Assuming your environment is set up properly, compile HelloForm.java as follows − </form>
</body>
$ javac HelloForm.java </html>

If everything goes fine, above compilation would produce HelloForm.class file. Next you Keep this HTML in a file Hello.htm and put it in <Tomcat-
would have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB- installationdirectory>/webapps/ROOT directory. When you would access
INF/classes and create following entries in web.xml file located in <Tomcat-installation- http://localhost:8080/Hello.htm, here is the actual output of the above form.
directory>/webapps/ROOT/WEB-INF/
First Name: Last Name: Submit

<servlet> Try to enter First Name and Last Name and then click submit button to see the result on
<servlet-name>HelloForm</servlet-name> your local machine where tomcat is running. Based on the input provided, it will generate
<servlet-class>HelloForm</servlet-class> similar result as mentioned in the above example.
</servlet>

POST Method Example Using Form


<servlet-mapping>
<servlet-name>HelloForm</servlet-name> Let us do little modification in the above servlet, so that it can handle GET as well as POST
<url-pattern>/HelloForm</url-pattern> methods. Below is HelloForm.java servlet program to handle input given by web browser
</servlet-mapping> using GET or POST methods.

Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your // Import required java libraries


browser's Location:box and make sure you already started tomcat server, before firing import java.io.*;
above command in the browser. This would generate following result − import javax.servlet.*;
import javax.servlet.http.*;

Using GET Method to Read Form Data // Extend HttpServlet class


public class HelloForm extends HttpServlet {

First Name: ZARA // Method to handle GET method request.


public void doGet(HttpServletRequest request, HttpServletResponse response)
Last Name: ALI
throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");
GET Method Example Using Form
PrintWriter out = response.getWriter();
Here is a simple example which passes two values using HTML FORM and submit button. String title = "Using GET Method to Read Form Data";
We are going to use same Servlet HelloForm to handle this input.
Page 5 of 10 Page 6 of 10

String docType = First Name: Last Name: Submit


"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n"; Based on the input provided, it would generate similar result as mentioned in the above
examples.
out.println(docType +
"<html>\n" + Passing Checkbox Data to Servlet Program
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" + Checkboxes are used when more than one option is required to be selected.
"<h1 align = \"center\">" + title + "</h1>\n" +
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" + <html>
" <li><b>Last Name</b>: " <body>
+ request.getParameter("last_name") + "\n" + <form action = "CheckBox" method = "POST" target = "_blank">
"</ul>\n" + <input type = "checkbox" name = "maths" checked = "checked" /> Maths
"</body>" <input type = "checkbox" name = "physics" /> Physics
"</html>" <input type = "checkbox" name = "chemistry" checked = "checked" />
); Chemistry
} <input type = "submit" value = "Select Subject" />
</form>
// Method to handle POST method request. </body>
public void doPost(HttpServletRequest request, HttpServletResponse response) </html>
throws ServletException, IOException {
The result of this code is the following form
doGet(request, response);
} Maths Physics Chemistry Select Subject
}
Given below is the CheckBox.java servlet program to handle input given by web browser
for checkbox button.
Now compile and deploy the above Servlet and test it using Hello.htm with the POST
method as follows −
// Import required java libraries
import java.io.*;
<html> import javax.servlet.*;
<body> import javax.servlet.http.*;
<form action = "HelloForm" method = "POST">
First Name: <input type = "text" name = "first_name"> // Extend HttpServlet class
<br /> public class CheckBox extends HttpServlet {
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" /> // Method to handle GET method request.
</form> public void doGet(HttpServletRequest request, HttpServletResponse response)
</body> throws ServletException, IOException {
</html>
// Set response content type
Here is the actual output of the above form, Try to enter First and Last Name and then response.setContentType("text/html");
click submit button to see the result on your local machine where tomcat is running.
Page 7 of 10 Page 8 of 10

PrintWriter out = response.getWriter();


String title = "Reading Checkbox Data";
Reading All Form Parameters
String docType = Following is the generic example which uses getParameterNames() method of
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n" HttpServletRequest to read all the available form parameters. This method returns an
Enumeration that contains the parameter names in an unspecified order
out.println(docType +
"<html>\n" + Once we have an Enumeration, we can loop down the Enumeration in standard way by,
"<head><title>" + title + "</title></head>\n" + using hasMoreElements() method to determine when to stop and using nextElement()
"<body bgcolor = \"#f0f0f0\">\n" + method to get each parameter name.
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" + // Import required java libraries
" <li><b>Maths Flag : </b>: " import java.io.*;
+ request.getParameter("maths") + "\n" + import javax.servlet.*;
" <li><b>Physics Flag: </b>: " import javax.servlet.http.*;
+ request.getParameter("physics") + "\n" + import java.util.*;
" <li><b>Chemistry Flag: </b>: "
+ request.getParameter("chemistry") + "\n" + // Extend HttpServlet class
"</ul>\n" + public class ReadParams extends HttpServlet {
"</body>"
"</html>" // Method to handle GET method request.
); public void doGet(HttpServletRequest request, HttpServletResponse response)
} throws ServletException, IOException {

// Method to handle POST method request. // Set response content type


public void doPost(HttpServletRequest request, HttpServletResponse response) response.setContentType("text/html");
throws ServletException, IOException {
PrintWriter out = response.getWriter();
doGet(request, response); String title = "Reading All Form Parameters";
} String docType =
} "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"

For the above example, it would display following result − out.println(docType +


"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
Reading Checkbox Data "<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
Maths Flag : : on "<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"
Physics Flag: : null
"<th>Param Value(s)</th>\n"+
Chemistry Flag: : on "</tr>\n"
);

Enumeration paramNames = request.getParameterNames();


Page 9 of 10 Page 10 of 10

while(paramNames.hasMoreElements()) { </body>
String paramName = (String)paramNames.nextElement(); </html>
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
Now calling servlet using the above form would generate the following result −

// Read single valued data


if (paramValues.length == 1) { Reading All Form Parameters
String paramValue = paramValues[0];
if (paramValue.length() == 0)
Param Name Param Value(s)
out.println("<i>No Value</i>");
else maths on
out.println(paramValue);
} else { chemistry on
// Read multiple valued data
out.println("<ul>");

for(int i = 0; i < paramValues.length; i++) { You can try the above servlet to read any other form's data having other objects like text
out.println("<li>" + paramValues[i]); box, radio button or drop down box etc.
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}

// Method to handle POST method request.


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}

Now, try the above servlet with the following form −

<html>
<body>
<form action = "ReadParams" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chem
<input type = "submit" value = "Select Subject" />
</form>
Page 1 of 9 Page 2 of 9

GET / HTTP/1.0
Servlets - Cookies Handling Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Cookies are text files stored on the client computer and they are kept for various Host: zink.demon.co.uk:1126
information tracking purpose. Java Servlets transparently supports HTTP cookies. Accept: image/gif, */*
Accept-Encoding: gzip
There are three steps involved in identifying returning users −
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Server script sends a set of cookies to the browser. For example name, age, or
Cookie: name = xyz
identification number etc.

Browser stores this information on local machine for future use.


A servlet will then have access to the cookie through the request method
When next time browser sends any request to web server then it sends those request.getCookies() which returns an array of Cookie objects.
cookies information to the server and server uses that information to identify the
user.
Servlet Cookies Methods
Following is the list of useful methods which you can use while manipulating cookies in
This chapter will teach you how to set or reset cookies, how to access them and how to
servlet.
delete them.

Sr.No. Method & Description


The Anatomy of a Cookie
public void setDomain(String pattern)
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
1 This method sets the domain to which cookie applies, for example
directly on a browser). A servlet that sets a cookie might send headers that look
tutorialspoint.com.
something like this −
public String getDomain()
HTTP/1.1 200 OK 2 This method gets the domain to which cookie applies, for example
Date: Fri, 04 Feb 2000 21:03:38 GMT tutorialspoint.com.
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
public void setMaxAge(int expiry)
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;
3 This method sets how much time (in seconds) should elapse before the cookie
path = /; domain = tutorialspoint.com
expires. If you don't set this, the cookie will last only for the current session.
Connection: close
Content-Type: text/html public int getMaxAge()
4 This method returns the maximum age of the cookie, specified in seconds, By
default, -1 indicating the cookie will persist until browser shutdown.
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and
a domain. The name and value will be URL encoded. The expires field is an instruction to
public String getName()
the browser to "forget" the cookie after the given time and date.
5 This method returns the name of the cookie. The name cannot be changed

If the browser is configured to store cookies, it will then keep this information until the after creation.

expiry date. If the user points the browser at any page that matches the path and domain
public void setValue(String newValue)
of the cookie, it will resend the cookie to the server. The browser's headers might look 6
This method sets the value associated with the cookie
something like this −
public String getValue()
7
This method gets the value associated with the cookie.
Page 3 of 9 Page 4 of 9

public void setPath(String uri) response.addCookie(cookie);


This method sets the path to which this cookie applies. If you don't specify a
8
path, the cookie is returned for all URLs in the same directory as the current
page as well as all subdirectories. Example
public String getPath() Let us modify our Form Example to set the cookies for first and last name.
9
This method gets the path to which this cookie applies.

public void setSecure(boolean flag) // Import required java libraries


10 This method sets the boolean value indicating whether the cookie should only import java.io.*;
be sent over encrypted (i.e. SSL) connections. import javax.servlet.*;
import javax.servlet.http.*;
public void setComment(String purpose)
11 This method specifies a comment that describes a cookie's purpose. The // Extend HttpServlet class
comment is useful if the browser presents the cookie to the user. public class HelloForm extends HttpServlet {

public String getComment() public void doGet(HttpServletRequest request, HttpServletResponse response)


12 This method returns the comment describing the purpose of this cookie, or null throws ServletException, IOException {
if the cookie has no comment.
// Create cookies for first and last names.
Explore our latest online courses and learn new skills at your own pace. Enroll and Cookie firstName = new Cookie("first_name", request.getParameter("first_name
become a certified expert to boost your career. Cookie lastName = new Cookie("last_name", request.getParameter("last_name"))

Setting Cookies with Servlet // Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
Setting cookies with servlet involves three steps − lastName.setMaxAge(60*60*24);

(1) Creating a Cookie object − You call the Cookie constructor with a cookie name and
// Add both the cookies in the response header.
a cookie value, both of which are strings.
response.addCookie( firstName );
response.addCookie( lastName );
Cookie cookie = new Cookie("key","value");
// Set response content type

Keep in mind, neither the name nor the value should contain white space or any of the response.setContentType("text/html");
following characters −
PrintWriter out = response.getWriter();
String title = "Setting Cookies Example";
[]()=,"/?@:; String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"
(2) Setting the maximum age − You use setMaxAge to specify how long (in seconds)
the cookie should be valid. Following would set up a cookie for 24 hours. out.println(docType +
"<html>\n" +
"<head>
cookie.setMaxAge(60 * 60 * 24);
<title>" + title + "</title>
</head>\n" +
(3) Sending the Cookie into the HTTP response headers − You use
response.addCookie to add cookies in the HTTP response header as follows − "<body bgcolor = \"#f0f0f0\">\n" +
Page 5 of 9 Page 6 of 9

"<h1 align = \"center\">" + title + "</h1>\n" + To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling
"<ul>\n" + the getCookies() method of HttpServletRequest. Then cycle through the array, and use
" <li><b>First Name</b>: " getName() and getValue() methods to access each cookie and associated value.
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: " Example
+ request.getParameter("last_name") + "\n" +
"</ul>\n" + Let us read cookies which we have set in previous example −
"</body>
</html>" // Import required java libraries
); import java.io.*;
} import javax.servlet.*;
} import javax.servlet.http.*;

Compile the above servlet HelloForm and create appropriate entry in web.xml file and // Extend HttpServlet class
finally try following HTML page to call servlet. public class ReadCookies extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
<html>
<body>
Cookie cookie = null;
<form action = "HelloForm" method = "GET">
Cookie[] cookies = null;
First Name: <input type = "text" name = "first_name">
<br />
// Get an array of Cookies associated with this domain
Last Name: <input type = "text" name = "last_name" />
cookies = request.getCookies();
<input type = "submit" value = "Submit" />
</form>
// Set response content type
</body>
response.setContentType("text/html");
</html>

PrintWriter out = response.getWriter();


Keep above HTML content in a file Hello.htm and put it in <Tomcat- String title = "Reading Cookies Example";
installationdirectory>/webapps/ROOT directory. When you would access String docType =
http://localhost:8080/Hello.htm, here is the actual output of the above form. "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
First Name:
Last Name: Submit out.println(docType +
"<html>\n" +
Try to enter First Name and Last Name and then click submit button. This would display "<head><title>" + title + "</title></head>\n" +
first name and last name on your screen and same time it would set two cookies firstName "<body bgcolor = \"#f0f0f0\">\n" );
and lastName which would be passed back to the server when next time you would press
Submit button. if( cookies != null ) {
out.println("<h2> Found Cookies Name and Value</h2>");
Next section would explain you how you would access these cookies back in your web
application.
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
Reading Cookies with Servlet out.print("Name : " + cookie.getName( ) + ", ");
Page 7 of 9 Page 8 of 9

out.print("Value: " + cookie.getValue( ) + " <br/>");


} public void doGet(HttpServletRequest request, HttpServletResponse response)
} else { throws ServletException, IOException {
out.println("<h2>No cookies founds</h2>");
} Cookie cookie = null;
out.println("</body>"); Cookie[] cookies = null;
out.println("</html>");
} // Get an array of Cookies associated with this domain
} cookies = request.getCookies();

// Set response content type


Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you
response.setContentType("text/html");
would have set first_name cookie as "John" and last_name cookie as "Player" then running
http://localhost:8080/ReadCookies would display the following result −
PrintWriter out = response.getWriter();
String title = "Delete Cookies Example";

Found Cookies Name and Value String docType =


"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"

Name : first_name, Value: John


out.println(docType +
"<html>\n" +
Name : last_name, Value: Player
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );

Delete Cookies with Servlet


if( cookies != null ) {
To delete cookies is very simple. If you want to delete a cookie then you simply need to out.println("<h2> Cookies Name and Value</h2>");
follow up following three steps −
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
Read an already existing cookie and store it in Cookie object.

Set cookie age as zero using setMaxAge() method to delete an existing cookie if((cookie.getName( )).compareTo("first_name") == 0 ) {
Add this cookie back into response header. cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie : " + cookie.getName( ) + "<br/>");
Example }
out.print("Name : " + cookie.getName( ) + ", ");
The following example would delete and existing cookie named "first_name" and when you out.print("Value: " + cookie.getValue( )+" <br/>");
would run ReadCookies servlet next time it would return null value for first_name. }
} else {
// Import required java libraries out.println("<h2>No cookies founds</h2>");
import java.io.*; }
import javax.servlet.*; out.println("</body>");
import javax.servlet.http.*; out.println("</html>");
}
// Extend HttpServlet class }
public class DeleteCookies extends HttpServlet {
Page 9 of 9

Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now
running http://localhost:8080/DeleteCookies would display the following result −

Cookies Name and Value

Deleted cookie : first_name

Name : first_name, Value: John

Name : last_name, Value: Player

Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as
follows −

Found Cookies Name and Value

Name : last_name, Value: Player

You can delete your cookies in Internet Explorer manually. Start at the Tools menu and
select Internet Options. To delete all cookies, press Delete Cookies.
Page 1 of 6 Page 2 of 6

Host
9
Servlets - Client HTTP Request This header specifies the host and port as given in the original URL.

If-Modified-Since
When a browser requests for a web page, it sends lot of information to the web server
This header indicates that the client wants the page only if it has been changed
which cannot be read directly because this information travel as a part of header of HTTP 10
after the specified date. The server sends a code, 304 which means Not
request. You can check HTTP Protocol for more information on this.
Modified header if no newer result is available.
Following is the important header information which comes from browser side and you
If-Unmodified-Since
would use very frequently in web programming −
11 This header is the reverse of If-Modified-Since; it specifies that the operation
should succeed only if the document is older than the specified date.
Sr.No. Header & Description
Referer
Accept
This header indicates the URL of the referring Web page. For example, if you
This header specifies the MIME types that the browser or other clients can 12
1 are at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is
handle. Values of image/png or image/jpeg are the two most common
included in the Referrer header when the browser requests Web page 2.
possibilities.
User-Agent
Accept-Charset
13 This header identifies the browser or other client making the request and can
2 This header specifies the character sets the browser can use to display the
be used to return different content to different types of browsers.
information. For example ISO-8859-1.

Accept-Encoding Methods to read HTTP Header


3 This header specifies the types of encodings that the browser knows how to
handle. Values of gzip or compress are the two most common possibilities. There are following methods which can be used to read HTTP header in your servlet
program. These methods are available with HttpServletRequest object
Accept-Language
4 This header specifies the client's preferred languages in case the servlet can Sr.No. Method & Description
produce results in more than one language. For example en, en-us, ru, etc
Cookie[] getCookies()
Authorization 1 Returns an array containing all of the Cookie objects the client sent with this
5 This header is used by clients to identify themselves when accessing password- request.
protected Web pages.
Enumeration getAttributeNames()
Connection 2 Returns an Enumeration containing the names of the attributes available to this
This header indicates whether the client can handle persistent HTTP request.
6 connections. Persistent connections permit the client or other browser to
retrieve multiple files with a single request. A value of Keep-Alive means that Enumeration getHeaderNames()
3
persistent connections should be used. Returns an enumeration of all the header names this request contains.

Content-Length Enumeration getParameterNames()


7 This header is applicable only to POST requests and gives the size of the POST 4 Returns an Enumeration of String objects containing the names of the
data in bytes. parameters contained in this request

Cookie HttpSession getSession()


8 This header returns cookies to servers that previously sent them to the 5 Returns the current session associated with this request, or if the request does
browser. not have a session, creates one.
Page 3 of 6 Page 4 of 6

HttpSession getSession(boolean create) String getQueryString()


19
6 Returns the current HttpSession associated with this request or, if if there is no Returns the query string that is contained in the request URL after the path.
current session and value of create is true, returns a new session.
String getRemoteAddr()
20
Locale getLocale() Returns the Internet Protocol (IP) address of the client that sent the request.
7 Returns the preferred Locale that the client will accept content in, based on the
Accept-Language header. String getRemoteHost()
21
Returns the fully qualified name of the client that sent the request.
Object getAttribute(String name)
8 Returns the value of the named attribute as an Object, or null if no attribute of String getRemoteUser()
the given name exists. 22 Returns the login of the user making this request, if the user has been
authenticated, or null if the user has not been authenticated.
ServletInputStream getInputStream()
9 String getRequestURI()
Retrieves the body of the request as binary data using a ServletInputStream.
23 Returns the part of this request's URL from the protocol name up to the query
String getAuthType() string in the first line of the HTTP request.
10 Returns the name of the authentication scheme used to protect the servlet, for
example, "BASIC" or "SSL," or null if the JSP was not protected. String getRequestedSessionId()
24
Returns the session ID specified by the client.
String getCharacterEncoding()
11 String getServletPath()
Returns the name of the character encoding used in the body of this request. 25
Returns the part of this request's URL that calls the JSP.
String getContentType()
12 Returns the MIME type of the body of the request, or null if the type is not String[] getParameterValues(String name)
known. 26 Returns an array of String objects containing all of the values the given request
parameter has, or null if the parameter does not exist.
String getContextPath()
13 Returns the portion of the request URI that indicates the context of the boolean isSecure()
request. 27 Returns a Boolean indicating whether this request was made using a secure
channel, such as HTTPS.
String getHeader(String name)
14 int getContentLength()
Returns the value of the specified request header as a String.
28 Returns the length, in bytes, of the request body and made available by the
String getMethod() input stream, or -1 if the length is not known.
15 Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT. int getIntHeader(String name)
29
Returns the value of the specified request header as an int.
String getParameter(String name)
16 Returns the value of a request parameter as a String, or null if the parameter int getServerPort()
30
does not exist. Returns the port number on which this request was received.

String getPathInfo()
17 Returns any extra path information associated with the URL the client sent
HTTP Header Request Example
when it made this request Following is the example which uses getHeaderNames() method of HttpServletRequest
to read the HTTP header information. This method returns an Enumeration that contains
String getProtocol()
18 the header information associated with the current HTTP request.
Returns the name and version of the protocol the request.
Page 5 of 6 Page 6 of 6

Once we have an Enumeration, we can loop down the Enumeration in the standard }
manner, using hasMoreElements() method to determine when to stop and using
nextElement() method to get each parameter name // Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Import required java libraries
import java.io.*;
doGet(request, response);
import javax.servlet.*;
}
import javax.servlet.http.*;
}
import java.util.*;

// Extend HttpServlet class Now calling the above servlet would generate the following result −
public class DisplayHeader extends HttpServlet {

// Method to handle GET method request. HTTP Header Request Example


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { Header Name Header Value(s)

// Set response content type accept */*


response.setContentType("text/html");
accept-language en-us

PrintWriter out = response.getWriter();


user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; In
String title = "HTTP Header Request Example";
String docType = accept-encoding gzip, deflate
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"
host localhost:8080
out.println(docType +
"<html>\n" + connection Keep-Alive
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" + cache-control no-cache
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);

Enumeration headerNames = request.getHeaderNames();

while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
UNIT-4
5. Verbose and Boilerplate Code
Introduction to JSP • Writing servlets often requires repetitive boilerplate code for handling HTTP requests and
responses, managing headers,parsing parameters, etc. This verbosity can lead to error-prone
code and is less efficient compared to using higher-level frameworks.
Introduction to JSP:
1. It is a server-side technology that is used for creating web applications.
6. Poor Integration with Modern JavaScript Frameworks
2. It is used to create dynamic web content.
• Servlets were designed before modern JavaScript frameworks like React, Angular, or Vue
3. JSP consists of both HTML tags and JSP tags.
became popular. As a result,integrating servlets with these frameworks requires additional
4. In this, JSP tags are used to insert JAVA code into HTML pages. It is an advanced version
workarounds, making it harder to develop rich, interactive client-side applications.
of Servlet Technology i.e. a web-based technology that helps us to create dynamic and
platform-independent web pages.
5. In this, Java code can be inserted in HTML/ XML pages or both. 7. Limited Built-in Support forRESTful APIs
6. JSP is first converted into a servlet by the JSP container before processing the client’s • While servlets can be used to create REST APIs, they lack out-of-the-box support for
request. JSP has various features like JSP Expressions, JSP tags, JSP Expression Language, RESTful conventions. This means that developers often turn to frameworks like Spring
etc. Boot,which offers more convenient tools for building APIs.

8. Deployment and Maintenance Overhead


The Problem with Servlet. • Servlets require a Java servlet container (like Apache Tomcat) for deployment. Managing
Servlets are Java programs that run on a web server and handle requests and responses in web and maintaining the servlet container, handling versioning, and deploying updates can add
applications. While they provide a powerful way tocreate dynamic web content, servlets can administrative overhead.
present several challenges and limitations:
1.Complexity in Managing Sessions and State
• Servlets need to manage user sessions manually, which can be complex. Storing and Anatomy of JSP
retrieving session data across multiple requests requires careful handling, especially in The anatomy of a JSP (JavaServer Pages) involves several key elementsthat combine HTML,
applications with many concurrent users. Java, and special JSP syntax to create dynamic web content. Here’s a breakdown of the main
components that make up a typical JSP page:

2. Scalability Limitations 1. Directives


• Servlets may not be inherently scalable for high-traffic applications. Since each request to a Directives provide instructions to the JSP container and affect the overall structure of
servlet spawns a new thread, handling a large number of requests can be resource-intensive, the JSP page. They are defined within <%@ ... %> tags and are processed at page
especially in high-concurrency environments. translation time.
• Page Directive (<%@ page ... %>):Sets page-specific attributes, such as language,
content type, and import statements.
3. Difficulty in Managing HTML
<%@ page language="java"
• Mixing Java code with HTML can make servlet code harder to maintain. Traditionally,
contentType="text/html;
servlets use PrintWriter to generate HTML, which leads to long and difficult-to-read code
charset=UTF-8"
that is not ideal for designing web pages.
pageEncoding="UTF-8"%>
• Include Directive (<%@ include ...%>): Includes a static file (like a header or
4. Limited MVC Support footer) during the translation phase.
• Servlets themselves are not well-suited to follow the Model-View-Controller (MVC) design
pattern.While servlets are useful as controllers, they don't provide native support for jsp
separating application layers, which is often Copy code
handled better by frameworks like Spring MVC. <%@ include file="header.jsp" %>
• Taglib Directive (<%@ taglib ...%>): Declares custom tag libraries, such as JSTL
(JavaServer Pages Standard Tag Library).
jsp 5. Expression Language (EL)
Copy code Expression Language (EL) simplifies data access by using ${...} syntax to access Java
<%@ taglib url="http://java.sun.com/jsp/jstl/core" prefix="c" %> objects stored in different scopes (request, session,application). It is commonly used with
JSTL.

2. Scriptlets
Scriptlets allow embedding Java code directly within the JSP page. They are defined jsp
using <% ... %> and executed when the page is requested.Scriptlets can perform actions Copy code
like accessing session variables or executing server-side logic. <p>Welcome, ${user.name}!</p>

6. Standard Tags and JSTL(JavaServer Pages Standard Tag Library)JSTL provides a


jsp collection of standard tags that support common tasks, such as iteration, conditionals,
Copy code and internationalization. Using JSTL tags helps keep the JSP clean and maintainable.
<%String message = "Hello, JSP!";out.println(message);%>
Note: Scriptlets are less commonly used now in favor of JSTL and EL(Expression
Language) due to their potential for cluttering the code.
• Core JSTL Tags:
jsp
Copy code
3. Expressions <c:if test="${user.loggedIn}">
Expressions evaluate a Java expression and output the result directly to the client. They <p>Welcome back,
are enclosed within <%= ... %> and are commonly used to display values. ${user.name}!</p>
jsp </c:if>
Copy code • Formatting Tags:
<p>Today’s date: <%= new jsp
java.util.Date() %></p> Copy code
<fmt:formatDate
value="${currentDate}"
pattern="MM/dd/yyyy"/>

4. Declarations
Declarations allow defining variables or methods that can be used across the page. These
elements are defined within <%! ... %> 7. HTML and Static Content
JSP pages can contain any HTML,CSS, and JavaScript content, making it easy to
combine dynamic and static content.
jsp
jsp Copy code
Copy code <html><head>
<%!int counter = 0; <title>Welcome</title>
public int getNextCounter() { </head>
return ++counter; <body><h1>Welcome to My JSP Page</h1>
}%> </body>
</html>
8. Comments:JSP supports two types of comments: pages using HTML, Java, and XML elements. The processing of a JSP file is handled in
• JSP Comments (<%-- comment --%>): Not visible to the client, used for server-side several stages, from the request to the response. Below is an overview of how JSP
comments. processing works:
1. JSP Request
jsp When a client (browser) sends a request to the server for a JSP page,the following
Copy code step are involved in processing the JSP:
<%-- This comment is for developers only --%> 2. Compilation of JSP to Servlet
• HTML Comments (<!-- comment -->): Visible to the client in the HTML source. • First-Time Request: The JSP file is translated into a servlet by the web container
html (like Apache Tomcat, Jetty, etc.). This is done automatically by the server the first
Copy code time the JSP is requested or after changes to the JSP file.
<!-- This comment will be visible in the HTML source --> .Java Code to Servlet: The JSP file is converted into a Java servlet (a class that
extends HttpServlet).All the HTML and JSP-specific tags (like <% %>, <%= %>,
Example: Anatomy of a Complete JSP <jsp:...>) are converted into Java code.
Page
• Compilation: Once the JSP is translated to a servlet, the server compiles the
Here’s a sample JSP page that combines several of the elements described above:
generated Java code into bytecode (a .class file).
jsp
Copy code 3. Execution of Servlet
<%@ page language="java" contentType="text/html; After compilation, the servlet is executed. During this phase, the
following happens:
charset=UTF-8" • Service Method: The web container calls the service() method of the generated
pageEncoding="UTF-8"%> servlet, which processes the request and prepares a response.
<%@ taglib url=http://java.sun.com/jsp/jstl/core prefix="c" %>
• JSP Tag Handling: Any tags or expressions (such as <%= %> for dynamic content
<html>
<head> or custom tags) in the JSP are processed at this point.
<title>Welcome Page</title> 4. JSP Implicit Objects
</head> During execution, JSP provides several implicit objects that simplify programming,
<body> such as:
<h1>Welcome to Our Site</h1> • request(javax.servlet.http.HttpServletRequest)
<%-- Scriptlet Example --%> • response(javax.servlet.http.HttpServletResponse)
<%String greeting = "Hello,JSP!";out.println("<p>" + greeting+ "</p>");%> • out (PrintWriter used to write to the response)
<%-- Expression Example --%> • session (HttpSession)
<p>Today’s Date: <%= new java.util.Date() %></p> • application (ServletContext)
<c:when test="${user.loggedIn}"> • config (ServletConfig)
<p>Welcome back, • pageContext (JspContext)
${user.name}!</p> .page (the current JSP object,typically this)
</c:when> • exception (used for error pages)
<c:otherwise> These objects help developers interact with the request, response,session, and other
<p>Welcome, Guest!Please <a href="login.jsp">login</a>.</p> environment settings.
</c:otherwise>
</c:choose>
5. Generating Response
</body> • The servlet writes the response content (HTML, JSON, etc.) to theresponse object.
</html> This includes any dynamic content that was generated in the JSP, like data
This example demonstrates the common elements found in a JSP page, allowing it to from Java beans, database queries, or business logic.
dynamically display content, execute Java code, and maintain a clean separation between 6. Sending Response Back to Client
business logic and presentation. After the servlet finishes processing,the response is sent back to the client. The
client’s browser renders the content, which may include dynamic data, interactive
forms, etc.
JSP PROCESSING
7. Caching and Reuse
JSP Processing refers to the steps involved in processing a Java Server Pages (JSP) file in • Subsequent Requests: After the initial compilation and execution,the generated
a web server environment. JSP is a technology that helps developers create dynamic web servlet is cached by the web container. If the same JSP page is requested again, the
web container does not need to recompile it but can simply call the already compiled JSP Application Development:
servlet. Generating Dynamic Content
• Automatic Updates: If the JSP file In JavaServer Pages (JSP), dynamic content is generated by embedding Java code
is modified, the web container within HTML tags. This allows for the creation of interactive and data-driven web
detects the change and recompiles pages. Here's an overview of how JSP facilitates dynamic content generation and how
the JSP to keep the servlet up-to- to use various JSP features, such as scripting elements, implicit objects, and declaring
date. variables and methods.
8. Error Handling 1. Generating Dynamic Content in JSP
• If any errors occur during JSP processing, such as syntax errors or runtime To generate dynamic content, you can embed Java code inside a JSP page. The server
exceptions, JSP pages can define error pages using the <error-page> directive in processes this Java code, which can be used to pull data from databases, handle form
web.xml, or by using try-catch blocks within the JSP itself. submissions, or even generate dynamic HTML based on conditions.
Key Concepts in JSP Processing: Basic Example of Dynamic Content
• Directives: Provide global information to the JSP page, such as the page language, Generation:
buffer size,etc. jsp
<%@ page %> — for page-level configurations. Copy code
<%@ include %> — to include a file at compile-time. <%@ page language="java" contentType="text/html;charset=ISO-8859-1" %>
<%@ taglib %> — to declare custom tags. <html>
• Declarations: Allows you to define Java methods or variables at the page level. <head>
<%! %> — used for declaring methods and variables. <title>Dynamic Content
• Scriptlets: Embedded Java code in the JSP page. Example</title>
<% %> — Java code blocks within the page. </head>
Expressions: Used to output dynamic content directly. <body>
<%= %> — evaluates Java expressions and outputs them directly into the HTML <h2>Welcome to My Website</h2>
Example of JSP Code: <p>The current time is: <%= new java.util.Date() %></p>
jsp </body>
Copy code </html>
<%@ page language="java" contentType="text/html;charset=ISO-8859-1"%> In this example:
<html><body> • The expression <%= new java.util.Date() %> is used to output the current date and
<h2>Welcome to JSP Example</h2> time.Every time the page is requested, the Java code inside the <%= %> tag is
<%String userName =request.getParameter("name");out.println("Hello, " evaluated, and the result is included in the HTML response.
+userName);%> 2. Using JSP Scripting Elements
</body> JSP scripting elements are used to embed Java code within a JSP page.
</html> There are three main types of scripting elements:
In this example: 2.1. Scriptlets (<% %>)
• The JSP page receives a parameter name from the request. Scriptlets allow you to insert Java code that will be executed when the
• The value of name is dynamically inserted into the response,displaying a JSP is processed.
personalized message. • Syntax: <% java code %>
Common Lifecycle Phases: • Usage: Ideal for small Java code blocks such as loops or conditionals.
1. Page Translation: JSP file is translated into a servlet. jsp
2. Compilation: The generated servlet is compiled. Copy code
3. Initialization: The servlet’s init() method is called. <%
4. Request Handling: The service() method handles client requests. int num = 5;
5. Destruction: The servlet’s destroy() method is called when the servlet is unloaded out.println("The value of num is: "+ num);
or the server shuts down.This process ensures that JSP pages are dynamically %>
generated on the server and provide interactive, data-driven content to the client. In this example:
• The variable num is initialized to 5, and its value is printed in the HTML response.
Here are the most commonly used implicit objects in JSP:
2.2. Declarations (<%! %>) 3.1. request (HttpServletRequest) This object represents the client's request to the server. It
Declarations allow you to declarevariables or methods that can be used throughout the allows access to request parameters, headers, and other information about the request.
entire JSP page.These variables and methods are placed in the generated servlet as String userName =request.getParameter("name");out.println("Hello, " + userName);
instance fields and methods. %>
• Syntax: <%! declarations %> 3.2. response (HttpServletResponse)
• Usage: Use for declaring class-level variables or methods that should be shared This object represents the responsecsent back to the client. It allows youcto control the
across multiple requests. response, includingcsetting content types, writing to thecoutput stream, or redirecting the
jsp user.
Copy code Example:
<%! jsp
private int counter = 0; Copy code
public int getNextCounterValue() { <%response.setContentType("text/html"); %>
<html><body>HellocWorld!</body></html>
counter++;
return counter; 3.3. session (HttpSession)
}
This object represents the HTTP session associated with the current request. It allows you to
%>
store and retrieve session-specific data.
<html> Example:
<body> jsp
<h2>Counter Value: <%= Copy code
getNextCounterValue() %></h2> <%
</body> session.setAttribute("user","John");
</html> String user = (String)
In this example: session.getAttribute("user");out.println("User: " + user);
• A variable counter is declared and a method getNextCounterValue() is created to %>
return an incremented value. Every time the page is requested, the counter value is 3.4. application (ServletContext)
incremented and displayed. This object represents the entire web application. You can store application-wide data
(available to all users) here.
2.3. Expressions (<%= %>) Example:
Expressions allow you to output the result of a Java expression directly into the response. jsp
• Syntax: <%= expression %>
• Usage: Ideal for simple expressions like printing variable values or calculations. Copy code
jsp <%
Copy code application.setAttribute("siteName","My Awesome Site");
<html> String siteName = (String)
<body> application.getAttribute("siteName");
<h2>The sum of 5 + 3 is: <%= 5 out.println("Site: " + siteName);
+ 3 %></h2> %>
</body> 3.5. out (JspWriter)
</html> This object allows you to writecontent to the response, which will be sent to the client. You
In this example: can use out.println() or out.print() to send dynamic content.
• The expression 5 + 3 is evaluated,and the result (8) is printed in the HTML response. Example:
jsp
3. Implicit JSP Objects Copy code
JSP provides several implicit objectsvthat allow you to easily interact with various <%
components of the request,response, session, and page context.These objects are out.println("This is dynamic content generated in JSP!");
automatically available to you in the JSP environment without needing to %>
explicitly declare them.
3.6 config (ServletConfig) public int incrementCounter() {
This object contains initialization parameters defined in the web.xmlconfiguration file. It is counter++;
typically used in servlets, but it's available in JSP too. return counter;}
Example: %>
jsp <html>
Copy code <body>
<% <h2>Current Counter: <%=incrementCounter() %></h2>
String configParam =config.getInitParameter("configParam"); </body>
out.println("Config Parameter: " +configParam); </html>
%> In this example:
• The counter variable is declared in the declaration section, and the incrementCounter()
7. pageContext (PageContext) method is used to increment and return the counter value each time the page is loaded
This object provides access to all the scope objects (request, session,application, etc.), and it
offers various utility methods. It is not commonly used directly in JSP.

3.8. page (JSP Object)


Represents the instance of the current JSP. It’s equivalent to this in Java.
Example:
jsp
Copy code
<%
out.println("Current page object is:" + page);
%>

3.9. exception (Throwable)


Available only when an exception is thrown, this object can be used to display error details in
custom error pages.
Example:
jsp
Copy code
<%@ page isErrorPage="true" %>
<%Throwable throwable = (Throwable)
request.getAttribute("javax.servlet.error.exception");
out.println("Error Message: " +
throwable.getMessage());
%>

4. Declaring Variables and Methods in JSP


You can declare variables and methods in JSP using declarations.
Declarations are used to define instance-level variables and methods in the generated servlet.
• Declaring Variables: Declare instance variables in the <%! %> block.
• Declaring Methods: Declare methods that can be used anywhere in the JSP.
Example of Declaring Variables and Methods:
jsp
Copy code
<%!
private int counter = 0;
4. Limited MVC Support
UNIT-4
Introduction to JSP: The Problem with Servlet. The Anatomy of a JSP Page, JSP • Servlets themselves are not well-suited to follow the Model-View-Controller (MVC) design
Processing, JSP Application Development: Generating Dynamic Content, Using pattern. While servlets are useful as controllers, they don't provide native support for separating
application layers, which is often handled better by frameworks like Spring MVC.
Scripting Elements, Implicit JSP Objects, Declaring Variables and Methods.
5. Verbose and Boilerplate Code
Introduction to JSP:
• Writing servlets often requires repetitive boilerplate code for handling HTTP requests and
responses, managing headers, parsing parameters, etc. This verbosity can lead to error-prone code
1. It is a server-side technology that is used for creating web applications. and is less efficient compared to using higher-level frameworks.
2. It is used to create dynamic web content.
3. JSP consists of both HTML tags and JSP tags. 6. Poor Integration with Modern JavaScript Frameworks
4. In this, JSP tags are used to insert JAVA code into HTML pages. It is
• Servlets were designed before modern JavaScript frameworks like React, Angular, or Vue
an advanced version of Servlet Technology i.e. a web-based technology
became popular. As a result, integrating servlets with these frameworks requires additional
that helps us to create dynamic and platform-independent web pages. workarounds, making it harder to develop rich, interactive client-side applications.
5. In this, Java code can be inserted in HTML/ XML pages or both.
6. JSP is first converted into a servlet by the JSP container before 7. Limited Built-in Support for RESTful APIs
processing the client’s request. JSP has various features like JSP
• While servlets can be used to create REST APIs, they lack out-of-the-box support for RESTful
Expressions, JSP tags, JSP Expression Language, etc. conventions. This means that developers often turn to frameworks like Spring Boot, which offers
more convenient tools for building APIs.
The Problem with Servlet.
8. Deployment and Maintenance Overhead
Servlets are Java programs that run on a web server and handle requests and responses in
web applications. While they provide a powerful way to create dynamic web content, • Servlets require a Java servlet container (like Apache Tomcat) for deployment. Managing and
servlets can present several challenges and limitations: maintaining the servlet container, handling versioning, and deploying updates can add
administrative overhead.
1. Complexity in Managing Sessions and State

• Servlets need to manage user sessions manually, which can be complex. Storing and retrieving Anatomy of JSP
session data across multiple requests requires careful handling, especially in applications with
many concurrent users. The anatomy of a JSP (JavaServer Pages) involves several key elements that combine HTML,
Java, and special JSP syntax to create dynamic web content. Here’s a breakdown of the main
2. Scalability Limitations components that make up a typical JSP page:

• Servlets may not be inherently scalable for high-traffic applications. Since each request to a
servlet spawns a new thread, handling a large number of requests can be resource-intensive,
especially in high-concurrency environments. 1. Directives

3. Difficulty in Managing HTML Directives provide instructions to the JSP container and affect the overall structure of the JSP
page. They are defined within <%@ ... %> tags and are processed at page translation time.
• Mixing Java code with HTML can make servlet code harder to maintain. Traditionally, servlets
use PrintWriter to generate HTML, which leads to long and difficult-to-read code that is not • Page Directive (<%@ page ... %>): Sets page-specific attributes, such as language, content
ideal for designing web pages. type, and import statements.
<%@ page language="java" contentType="text/html; charset=UTF-8" public int getNextCounter() {
pageEncoding="UTF-8"%> return ++counter;
}
• Include Directive (<%@ include ... %>): Includes a static file (like a header or footer) during %>
the translation phase.
5. Expression Language (EL)
jsp
Copy code Expression Language (EL) simplifies data access by using ${...} syntax to access Java objects
<%@ include file="header.jsp" %> stored in different scopes (request, session, application). It is commonly used with JSTL.

• Taglib Directive (<%@ taglib ... %>): Declares custom tag libraries, such as JSTL jsp
(JavaServer Pages Standard Tag Library). Copy code
<p>Welcome, ${user.name}!</p>
jsp
6. Standard Tags and JSTL (JavaServer Pages Standard Tag Library)
Copy code
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
JSTL provides a collection of standard tags that support common tasks, such as iteration,
2. Scriptlets conditionals, and internationalization. Using JSTL tags helps keep the JSP clean and
maintainable.
Scriptlets allow embedding Java code directly within the JSP page. They are defined using <%
... %> and executed when the page is requested. Scriptlets can perform actions like accessing • Core JSTL Tags:
session variables or executing server-side logic.
jsp
jsp Copy code
Copy code <c:if test="${user.loggedIn}">
<% <p>Welcome back, ${user.name}!</p>
String message = "Hello, JSP!"; </c:if>
out.println(message);
%> • Formatting Tags:

Note: Scriptlets are less commonly used now in favor of JSTL and EL (Expression Language) jsp
due to their potential for cluttering the code. Copy code
<fmt:formatDate value="${currentDate}" pattern="MM/dd/yyyy"/>

3. Expressions 7. HTML and Static Content

Expressions evaluate a Java expression and output the result directly to the client. They are JSP pages can contain any HTML, CSS, and JavaScript content, making it easy to combine
enclosed within <%= ... %> and are commonly used to display values. dynamic and static content.
jsp jsp
Copy code Copy code
<p>Today’s date: <%= new java.util.Date() %></p> <html>
<head>
4. Declarations <title>Welcome</title>
</head>
Declarations allow defining variables or methods that can be used across the page. These <body>
<h1>Welcome to My JSP Page</h1>
elements are defined within <%! ... %>. </body>
</html>
jsp
Copy code
<%!
int counter = 0;
8. Comments </html>

JSP supports two types of comments: This example demonstrates the common elements found in a JSP page, allowing it to
dynamically display content, execute Java code, and maintain a clean separation between
• JSP Comments (<%-- comment --%>): Not visible to the client, used for server-side business logic and presentation.
comments.
JSP PROCESSING
jsp
Copy code
<%-- This comment is for developers only --%>
JSP Processing refers to the steps involved in processing a Java Server Pages (JSP) file in a web
server environment. JSP is a technology that helps developers create dynamic web pages using
• HTML Comments (<!-- comment -->): Visible to the client in the HTML source. HTML, Java, and XML elements. The processing of a JSP file is handled in several stages, from
the request to the response. Below is an overview of how JSP processing works:
html
Copy code 1. JSP Request
<!-- This comment will be visible in the HTML source -->
When a client (browser) sends a request to the server for a JSP page, the following steps are
involved in processing the JSP:
Example: Anatomy of a Complete JSP Page
2. Compilation of JSP to Servlet
Here’s a sample JSP page that combines several of the elements described above:
• First-Time Request: The JSP file is translated into a servlet by the web container (like Apache
jsp
Copy code Tomcat, Jetty, etc.). This is done automatically by the server the first time the JSP is requested or
<%@ page language="java" contentType="text/html; charset=UTF-8" after changes to the JSP file.
pageEncoding="UTF-8"%> • Java Code to Servlet: The JSP file is converted into a Java servlet (a class that extends
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> HttpServlet). All the HTML and JSP-specific tags (like <% %>, <%= %>, <jsp:...>) are
converted into Java code.
<html> • Compilation: Once the JSP is translated to a servlet, the server compiles the generated Java code
<head> into bytecode (a .class file).
<title>Welcome Page</title>
</head>
<body> 3. Execution of Servlet
<h1>Welcome to Our Site</h1>
After compilation, the servlet is executed. During this phase, the following happens:
<%-- Scriptlet Example --%>
<%
String greeting = "Hello, JSP!"; • Service Method: The web container calls the service() method of the generated servlet, which
out.println("<p>" + greeting + "</p>"); processes the request and prepares a response.
%> • JSP Tag Handling: Any tags or expressions (such as <%= %> for dynamic content or custom
tags) in the JSP are processed at this point.
<%-- Expression Example --%>
<p>Today’s Date: <%= new java.util.Date() %></p> 4. JSP Implicit Objects
<%-- JSTL Tag Example --%>
<c:choose> During execution, JSP provides several implicit objects that simplify programming, such as:
<c:when test="${user.loggedIn}">
<p>Welcome back, ${user.name}!</p> • request (javax.servlet.http.HttpServletRequest)
</c:when> • response (javax.servlet.http.HttpServletResponse)
<c:otherwise>
• out (PrintWriter used to write to the response)
<p>Welcome, Guest! Please <a href="login.jsp">login</a>.</p>
</c:otherwise> • session (HttpSession)
</c:choose> • application (ServletContext)
</body> • config (ServletConfig)
• pageContext (JspContext) o <%= %> — evaluates Java expressions and outputs them directly into the HTML.
• page (the current JSP object, typically this)
• exception (used for error pages) Example of JSP Code:
jsp
These objects help developers interact with the request, response, session, and other environment Copy code
settings. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"%>
<html>
5. Generating Response
<body>
• The servlet writes the response content (HTML, JSON, etc.) to the response object. This <h2>Welcome to JSP Example</h2>
includes any dynamic content that was generated in the JSP, like data from Java beans, database <%
queries, or business logic. String userName = request.getParameter("name");
out.println("Hello, " + userName);
6. Sending Response Back to Client
%>
After the servlet finishes processing, the response is sent back to the client. The client’s browser </body>
renders the content, which may include dynamic data, interactive forms, etc. </html>

7. Caching and Reuse In this example:

• Subsequent Requests: After the initial compilation and execution, the generated servlet is • The JSP page receives a parameter name from the request.
cached by the web container. If the same JSP page is requested again, the web container does not • The value of name is dynamically inserted into the response, displaying a personalized message.
need to recompile it but can simply call the already compiled servlet.
• Automatic Updates: If the JSP file is modified, the web container detects the change and Common Lifecycle Phases:
recompiles the JSP to keep the servlet up-to-date.
1. Page Translation: JSP file is translated into a servlet.
8. Error Handling 2. Compilation: The generated servlet is compiled.
3. Initialization: The servlet’s init() method is called.
• If any errors occur during JSP processing, such as syntax errors or runtime exceptions, JSP pages 4. Request Handling: The service() method handles client requests.
can define error pages using the <error-page> directive in web.xml, or by using try-catch
5. Destruction: The servlet’s destroy() method is called when the servlet is unloaded or the
blocks within the JSP itself.
server shuts down.
Key Concepts in JSP Processing:
This process ensures that JSP pages are dynamically generated on the server and provide
interactive, data-driven content to the client.
• Directives: Provide global information to the JSP page, such as the page language, buffer size,
etc.

o <%@ page %> — for page-level configurations.


o <%@ include %> — to include a file at compile-time. JSP Application Development: Generating Dynamic Content
o <%@ taglib %> — to declare custom tags.
• Declarations: Allows you to define Java methods or variables at the page level. In JavaServer Pages (JSP), dynamic content is generated by embedding Java code within HTML
tags. This allows for the creation of interactive and data-driven web pages. Here's an overview of
o <%! %> — used for declaring methods and variables. how JSP facilitates dynamic content generation and how to use various JSP features, such as
• Scriptlets: Embedded Java code in the JSP page. scripting elements, implicit objects, and declaring variables and methods.

o <% %> — Java code blocks within the page. 1. Generating Dynamic Content in JSP
• Expressions: Used to output dynamic content directly.
To generate dynamic content, you can embed Java code inside a JSP page. The server processes %>
this Java code, which can be used to pull data from databases, handle form submissions, or even
generate dynamic HTML based on conditions. In this example:

Basic Example of Dynamic Content Generation: • The variable num is initialized to 5, and its value is printed in the HTML response.

jsp 2. Declarations (<%! %>)


Copy code
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %> Declarations allow you to declare variables or methods that can be used throughout the entire
<html> JSP page. These variables and methods are placed in the generated servlet as instance fields and
methods.
<head>
<title>Dynamic Content Example</title> • Syntax: <%! declarations %>
</head> • Usage: Use for declaring class-level variables or methods that should be shared across multiple
<body> requests.
<h2>Welcome to My Website</h2>
<p>The current time is: <%= new java.util.Date() %></p> jsp
</body> Copy code
</html> <%!
private int counter = 0;
In this example:
public int getNextCounterValue() {
• The expression <%= new java.util.Date() %> is used to output the current date and time. counter++;
Every time the page is requested, the Java code inside the <%= %> tag is evaluated, and the result
return counter;
is included in the HTML response.
}
%>

2. Using JSP Scripting Elements


<html>
<body>
JSP scripting elements are used to embed Java code within a JSP page. There are three main
types of scripting elements: <h2>Counter Value: <%= getNextCounterValue() %></h2>
</body>
1. Scriptlets (<% %>) </html>

Scriptlets allow you to insert Java code that will be executed when the JSP is processed. In this example:

• Syntax: <% java code %> • A variable counter is declared and a method getNextCounterValue() is created to return an
• Usage: Ideal for small Java code blocks such as loops or conditionals. incremented value. Every time the page is requested, the counter value is incremented and
displayed.
jsp
Copy code 3. Expressions (<%= %>)
<%
Expressions allow you to output the result of a Java expression directly into the response.
int num = 5;
out.println("The value of num is: " + num); • Syntax: <%= expression %>
• Usage: Ideal for simple expressions like printing variable values or calculations. jsp
Copy code
jsp <% response.setContentType("text/html"); %>
Copy code <html><body>Hello World!</body></html>
<html>
<body> 3. session (HttpSession)
<h2>The sum of 5 + 3 is: <%= 5 + 3 %></h2>
</body> This object represents the HTTP session associated with the current request. It allows you to
</html> store and retrieve session-specific data.

In this example: Example:

• The expression 5 + 3 is evaluated, and the result (8) is printed in the HTML response. jsp
Copy code
<%
3. Implicit JSP Objects session.setAttribute("user", "John");
String user = (String) session.getAttribute("user");
JSP provides several implicit objects that allow you to easily interact with various components of out.println("User: " + user);
the request, response, session, and page context. These objects are automatically available to you %>
in the JSP environment without needing to explicitly declare them.
4. application (ServletContext)
Here are the most commonly used implicit objects in JSP:
This object represents the entire web application. You can store application-wide data (available
1. request (HttpServletRequest) to all users) here.

This object represents the client's request to the server. It allows access to request parameters, Example:
headers, and other information about the request.
jsp
Example: Copy code
<%
jsp
application.setAttribute("siteName", "My Awesome Site");
Copy code
String siteName = (String) application.getAttribute("siteName");
<%
out.println("Site: " + siteName);
String userName = request.getParameter("name");
%>
out.println("Hello, " + userName);
%> 5. out (JspWriter)
2. response (HttpServletResponse) This object allows you to write content to the response, which will be sent to the client. You can
use out.println() or out.print() to send dynamic content.
This object represents the response sent back to the client. It allows you to control the response,
including setting content types, writing to the output stream, or redirecting the user. Example:
Example: jsp
Copy code Copy code
<% <%@ page isErrorPage="true" %>
out.println("This is dynamic content generated in JSP!"); <%
%> Throwable throwable = (Throwable)
request.getAttribute("javax.servlet.error.exception");
6. config (ServletConfig) out.println("Error Message: " + throwable.getMessage());
%>
This object contains initialization parameters defined in the web.xml configuration file. It is
typically used in servlets, but it's available in JSP too.
4. Declaring Variables and Methods in JSP
Example:
You can declare variables and methods in JSP using declarations. Declarations are used to
jsp define instance-level variables and methods in the generated servlet.
Copy code
• Declaring Variables: Declare instance variables in the <%! %> block.
<% • Declaring Methods: Declare methods that can be used anywhere in the JSP.
String configParam = config.getInitParameter("configParam");
out.println("Config Parameter: " + configParam); Example of Declaring Variables and Methods:
%>
jsp
7. pageContext (PageContext) Copy code
<%!
This object provides access to all the scope objects (request, session, application, etc.), and it private int counter = 0;
offers various utility methods. It is not commonly used directly in JSP.
public int incrementCounter() {
8. page (JSP Object)
counter++;
Represents the instance of the current JSP. It’s equivalent to this in Java. return counter;
}
Example: %>

jsp <html>
Copy code <body>
<% <h2>Current Counter: <%= incrementCounter() %></h2>
out.println("Current page object is: " + page); </body>
%> </html>

9. exception (Throwable) In this example:

Available only when an exception is thrown, this object can be used to display error details in • The counter variable is declared in the declaration section, and the incrementCounter()
custom error pages. method is used to increment and return the counter value each time the page is loaded.

Example:

jsp
1. Sharing Data Between JSP Pages Session attributes are used when you want to persist data across multiple requests for
the same user (usually throughout the duration of the user’s session). This is
In JSP, there are several ways to share data between pages. This is important when commonly used for storing login information, shopping cart contents, etc.
you need to pass data from one page to another, for example, after a form submission
or when navigating between different views. Example: Passing data between JSP pages using session attributes.

• Page 1 (Setting Session Data)


Ways to Share Data Between JSP Pages:

• Using Request Attributes jsp


• Using Session Attributes Copy code
• Using Application Attributes (ServletContext) <%
• Using URL Parameters String userName = request.getParameter("username");
session.setAttribute("username", userName);
1.1 Using Request Attributes
response.sendRedirect("page2.jsp");
%>
Request attributes are used to share data between JSP pages within the same request
(i.e., when you are forwarding a request from one page to another). These attributes
• Page 2 (Getting Session Data)
are temporary and are discarded once the request is complete (when the response is
sent back to the client).
jsp
Example: Passing data from one JSP page to another using request attributes. Copy code
<%
• Page 1 (Sending Data) String userName = (String) session.getAttribute("username");
out.println("Welcome back, " + userName);
jsp %>
Copy code
<% In this example, userName is saved in the session using session.setAttribute()
String userName = request.getParameter("username"); and can be accessed by other pages during the same session.
request.setAttribute("username", userName);
RequestDispatcher dispatcher = 1.3 Using Application Attributes (ServletContext)
request.getRequestDispatcher("page2.jsp");
Application attributes are used to store data that is shared across all users and sessions
dispatcher.forward(request, response);
in the entire web application. These are commonly used for storing global information
%>
(e.g., configuration data, application-wide settings).
• Page 2 (Receiving Data)
Example: Using application attributes for shared data.
jsp • Page 1 (Setting Application Data)
Copy code
<% jsp
String userName = (String) request.getAttribute("username"); Copy code
out.println("Hello, " + userName); <%
%> String appName = "My Web Application";
application.setAttribute("appName", appName);
In this example, page1.jsp collects a username from the client, sets it as a request response.sendRedirect("page2.jsp");
attribute, and forwards the request to page2.jsp. On page2.jsp, we retrieve the %>
username using request.getAttribute().
• Page 2 (Getting Application Data)
1.2 Using Session Attributes
jsp 2.1 Request Dispatcher
Copy code
<% The RequestDispatcher object allows one page to forward control to another page
String appName = (String) application.getAttribute("appName"); on the server (without the client being aware of it). It can also pass data (request
out.println("Application Name: " + appName); attributes) to the target page.
%> • Forwarding with Request Dispatcher

Here, the appName is set as an application attribute, which is accessible by all JSP jsp
pages across the entire application.
Copy code
<%
1.4 Using URL Parameters
String username = request.getParameter("username");
URL parameters (query strings) are used to pass small amounts of data between pages request.setAttribute("username", username);
by appending them to the URL. The data is then extracted on the receiving page. RequestDispatcher dispatcher =
request.getRequestDispatcher("welcome.jsp");
Example: Passing data via URL parameters. dispatcher.forward(request, response);
%>
• Page 1 (Sending Data via URL)
This forwards the request to welcome.jsp without changing the URL in the browser.
jsp Data is shared using request attributes.
Copy code
<% 2.2 Redirecting
String userName = "JohnDoe";
response.sendRedirect("page2.jsp?username=" + userName); When you use response.sendRedirect(), the browser is instructed to send a new
%> request to a different page (client-side redirect). This does not preserve request
attributes, but it allows you to pass data through the URL or via session attributes.
• Page 2 (Receiving Data via URL)
• Redirect Example
jsp
Copy code jsp
<% Copy code
String userName = request.getParameter("username"); <%
out.println("Hello, " + userName); String username = request.getParameter("username");
%> response.sendRedirect("welcome.jsp?username=" + username);
%>
In this case, the username parameter is passed in the URL and is accessed using
request.getParameter(). In this example, after processing, the page redirects the user to welcome.jsp with the
username passed as a URL parameter.

2. Users Passing Control and Data between Pages


3. JSP Application Design with JDBC
Control flow in JSP applications is typically managed using:
JSP is often used in combination with JDBC (Java Database Connectivity) to interact
• Request Dispatching with databases. This involves executing SQL queries and fetching data from a
• Redirecting database in a JSP page. The typical approach is to handle database logic in Java
• Forwarding classes (such as servlets or model classes) and then display results in JSP.
Example: Simple JSP Application with JDBC } catch (SQLException e) {
e.printStackTrace();
1. Database Connection Utility (DBUtil.java) }
}
o A utility class to manage database connections.
%>
java
<h2>User List</h2>
Copy code
<ul>
import java.sql.*;
<%
public class DBUtil {
for (String user : users) {
public static Connection getConnection() throws SQLException {
out.println("<li>" + user + "</li>");
String url = "jdbc:mysql://localhost:3306/mydb";
}
String user = "root";
%>
String password = "password";
</ul>
return DriverManager.getConnection(url, user, password);
}
This page fetches user data from a database and dynamically generates an HTML list
} of users.
1. JSP Page (userList.jsp)

o This page retrieves user data from a database and displays it.
4. JSP Application Design with MVC (Model-View-Controller)
jsp
MVC is a design pattern used to separate concerns in an application. JSP typically fits
Copy code into the View layer, which is responsible for displaying data. The Model represents
<%@ page import="java.sql.*, java.util.*" %> the data and business logic, and the Controller manages the flow of the application
<% (request processing).
Connection conn = null;
Statement stmt = null; 4.1 Model
ResultSet rs = null;
List<String> users = new ArrayList<>(); The Model represents the data and business logic of the application. It could be a Java
class, such as a User class or a DAO (Data Access Object) that interacts with the
database.
try {
conn = DBUtil.getConnection(); Example: A simple User model.
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT username FROM users"); java
Copy code
while (rs.next()) { public class User {
users.add(rs.getString("username")); private String username;
} private String password;
} catch (SQLException e) {
e.printStackTrace(); // Getters and Setters
} finally { }
try {
if (rs != null) rs.close(); 4.2 Controller
if (stmt != null) stmt.close();
if (conn != null) conn.close();
The Controller handles user requests, processes business logic, and forwards the
result to the appropriate view (JSP).
Conclusion
Example: A simple servlet that acts as the controller.
By using JSP, JDBC, and the MVC design pattern, you can build well-structured,
java maintainable web applications. Here's a summary of the key points:
Copy code
@WebServlet("/login")public class LoginController extends HttpServlet • Sharing data between JSP pages: Use request, session, application attributes, or URL
parameters.
{
• Passing control and data between pages: You can forward or redirect to another page, using
protected void doPost(HttpServletRequest request, RequestDispatcher or response.sendRedirect().
HttpServletResponse response) throws ServletException, IOException { • JSP with JDBC: To fetch data from databases, use JDBC for database connectivity and then
String username = request.getParameter("username"); display the results dynamically in JSP pages.
• JSP with MVC: Separate concerns by using the MVC pattern, where the Model handles
String password = request.getParameter("password");
business logic, the View is handled by JSP, and the Controller manages user requests and
forwards data to the view.
// Logic to authenticate user (e.g., checking against
database) This architecture ensures clean separation of concerns, making the application easier
if ("admin".equals(username) && "admin123".equals(password)) to maintain and scale.
{
request.setAttribute("username", username);
RequestDispatcher dispatcher =
request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);
} else {
response.sendRedirect("login.jsp");
}
}
}

4.3 View

The View (JSP page) is responsible for rendering the data. It retrieves the necessary
data from the request or session and displays it in a user-friendly format.

Example: welcome.jsp

jsp
Copy code
<%@ page import="java.util.*" %>
<h2>Welcome, <%= request.getAttribute("username") %>!</h2>

In this setup:

• The LoginController (Controller) processes the login form data and forwards the result
to welcome.jsp (View).
• The User (Model) contains the data and business logic (such as validating a username and
password).
1)Develop Angular JS program that allows user </style> var num1 =
to input their first name and last name and
parseFloat($scope.number1);
display their full name. </head>
Note: The default values for first name and var num2 =
<body ng-app="calculatorApp" ng-
last name may be included in the program. parseFloat($scope.number2);
controller="CalculatorController">
<!DOCTYPE html>
var operator = $scope.operator;
<html>
<head> switch (operator) {
2)Develop a simple Angular JS calculator <h1>Simple Calculator</h1>
<title>First name last name</title> application that can perform basic case '+':
mathematical operations (addition, <input type="number" ng-
<script
src="https://ajax.googleapis.com/ajax/libs/ang subtraction, multiplication, division) based on model="number1" placeholder="Enter $scope.result = num1 +
ularjs/1.8.2/angular.min.js"></script> user input.
first number" /> num2;
</head> <!DOCTYPE html>
<select ng-model="operator"> break;
<body ng-app="bindingapp" ng- <html>
controller="bindingctrl"> <option value="+">+</option> case '-':
<label>First Name: </label> <head>
<option value="-">-</option> $scope.result = num1 -
<input type="text" ng-model="fname" <title>AngularJS Calculator</title>
placeholder="Enter your first name"> num2;
<option value="*">*</option>
<label>Last Name: </label> <script
break;
<option value="/">/</option>
<input type="text" ng-model="lname" src="https://ajax.googleapis.com/ajax/libs/
placeholder="Enter your first name"> case '*':
angularjs/1.8.2/angular.min.js"></script> </select>
<h2>Hello, {{fname + ' ' + lname}}</h2> $scope.result = num1 *
<style> <input type="number" ng-
<script> num2;
model="number2" placeholder="Enter
var app = angular.module('bindingapp', body {
[]); second number" /> break;
font-family: Arial, sans-serif;
app.controller('bindingctrl', <button ng- case '/':
function($scope) { margin: 50px;
click="calculate()">Calculate</button>
$scope.fname = ""; if (num2 !== 0) {
}
$scope.lname = ""; <h2>Result: {{result}}</h2>
$scope.result = num1 /
}); input, select, button { <script> num2;
</script> margin: 10px; var app = } else {
</body>
padding: 10px; angular.module('calculatorApp', []);
</html> $scope.result = 'Error:
font-size: 16px; app.controller('CalculatorController', Division by zero';
function($scope) {
} }
Output: $scope.calculate = function() {
break; <script </head> {name: 'Charan', cgpa: 9.4},
src="https://ajax.googleapis.com/ajax/libs/
default: <body ng-app="studentApp" ng- {name: 'Abhinay', cgpa: 8.9},
angularjs/1.8.2/angular.min.js"></script>
controller="StudentController">
$scope.result = 'Invalid {name: 'Siddhardha', cgpa: 8.5}
<style>
operation';
];
body {
} <h1>Student Details</h1>
});
font-family: Arial, sans-serif;
}; <table>
</script>
margin: 50px;
}); <tr>
</body>
}
</script> <th>Student Name</th>
</html>
table {
</body> <th>CGPA</th>
Output:
width: 50%;
</html> </tr>
border-collapse: collapse;
Output: <tr ng-repeat="student in students">
margin-bottom: 20px;
<td>{{student.name}}</td>
}
<td>{{student.cgpa}}</td>
th, td {
</tr>
padding: 10px;
</table>
border: 1px solid #ddd;
<h2>Total Number of Students:
text-align: left; {{students.length}}</h2>

3)Develop Angular JS application that displays } <script>


a detail of students and their CGPA. Allow
users to read the number of students and th { var app =
4)Develop Angular JS program to create a
display the count. Note: Student details may angular.module('studentApp', []); login form, with validation for the username
be included in the program. background-color: #f4f4f4;
and password fields.
app.controller('StudentController',
<!DOCTYPE html> } <!DOCTYPE html>
function($scope) {
<html> h2, p { <html>
$scope.students = [
<head> margin-top: 20px; <head>
{name: 'Harsha', cgpa: 9.6},
<title>Student Details</title> } <title>AngularJS Login Form</title>
{name: 'Abhi', cgpa: 9.3},
</style>
<script } </div> if ($scope.loginForm.$valid) {
src="https://ajax.googleapis.com/ajax/libs/
.error { <input type="password" alert('Login
angularjs/1.8.2/angular.min.js"></script>
name="password" ng- successful!\nUsername: ' +
color: red;
<style> model="user.password" $scope.user.username);
font-size: 12px; placeholder="Password" required ng-
body { } else {
} minlength="6" />
font-family: Arial, sans-serif; alert('Please fill out the form
</style> <div ng-
correctly.');
margin: 50px; show="loginForm.password.$touched &&
</head> }
} loginForm.password.$invalid"
<body ng-app="loginApp" ng- class="error"> };
form {
controller="LoginController">
<span ng- });
width: 300px;
show="loginForm.password.$error.require
</script>
margin: 0 auto; d">Password is required.</span>
<h1>Login Form</h1>
</body>
padding: 50px; <span ng-
<form name="loginForm" ng-
show="loginForm.password.$error.minlen </html>
border: 1px solid #ddd; submit="login()" novalidate>
gth">Password must be at least 6
Output:
border-radius: 5px; <input type="text" name="username"
characters long.</span>
ng-model="user.username"
box-shadow: 2px 2px 12px rgba(0,
</div>
placeholder="Username" required ng-
0, 0, 0.2);
minlength="3" /> <button type="submit" ng-
}
disabled="loginForm.$invalid">Login</bu
<div ng-
input, button { tton>
show="loginForm.username.$touched &&

width: 100%; loginForm.username.$invalid" </form>


class="error">
padding: 10px; <script>
<span ng-
margin: 10px 0; var app = angular.module('loginApp',
show="loginForm.username.$error.require
[]); 5)Create an AngularJS application that displays
font-size: 16px; d">Username is required.</span>
a list of students in a table and allows users to
app.controller('LoginController', filter the students by name.
} <span ng-
function($scope) {
show="loginForm.username.$error.minlen Task:
input.ng-invalid.ng-touched {
gth">Username must be at least 3 $scope.user = {}; Create an array of student objects with
border-color: red; properties like name, age, grade, and city.
characters long.</span> $scope.login = function() {
Display the list of students in a table. padding: 12px; <th>City</th> { name: 'Abhiram', age: 22, grade: 'B',
city: 'HZB' }
Add a text input field above the table that text-align: left; </tr>
allows users to filter students by their name. ];
} </thead>
As the user types in the text input, the table
should dynamically update to show only the th { <tbody>
students whose names match the search $scope.searchQuery = '';
background-color: #f2f2f2; <tr ng-repeat="student in
query. students | filter:searchQuery"> });
}
Code: <td>{{ student.name }}</td>
input[type="text"] {
<html> <td>{{ student.age }}</td> </script>
width: 100%;
<head> <td>{{ student.grade }}</td> </body>
padding: 10px;
<title>Student List</title> <td>{{ student.city }}</td> </html>
margin-bottom: 10px;
<script </tr> Output:
src="https://ajax.googleapis.com/ajax/libs/ box-sizing: border-box;
angularjs/1.8.2/angular.min.js"></script> </tbody>
}
<style> </table>
</style>
body { </div>
</head>
font-family: Arial, sans-serif; </div>
<body>
margin: 50px;
} <script>
<div ng-app="studentFilterApp" ng-
h1 { controller="StudentController"> var app =
angular.module('studentFilterApp', []);
color: #4CAF50; <h1>Student List</h1>
6)Write a program to Establish a connection
} with the database using JDBC and display
app.controller('StudentController',
.table-container { <input type="text" ng- appropriate message with try and catch.
function($scope) {
model="searchQuery"
margin-top: 20px; placeholder="Search by Name"> $scope.students = [ Code:
} { name: 'Harsha', age: 20, grade: 'A', import java.sql.*;

table { city: 'HNK' }, class task {


<div class="table-container">
width: 100%; { name: 'Abhi', age: 22, grade: 'B', public static void main(String[] args) {
<table>
city: 'HNK' },
border-collapse: collapse; Connection cnn = null;
<thead>
{ name: 'Sri Charan', age: 21, grade:
try {
} <tr> 'A', city: 'HNK' },
// Load Oracle JDBC Driver
table, th, td { <th>Name</th> { name: 'Sidhardha', age: 23, grade:
border: 1px solid #ddd; 'C', city: 'KMP' },
<th>Age</th> Class.forName("oracle.jdbc.driver.OracleDrive
} { name: 'Ruthwik', age: 24, grade: 'A', r");
<th>Grade</th> city: 'BTP' },
th, td {
// Establish the connection
cnn =
stmt.executeUpdate(createTableSQL);
DriverManager.getConnection("jdbc:oracle:thi
n:@localhost:1521:xe","system","Harsha");
System.out.println("Table
System.out.println("Connection
'customer46' created successfully!");
successful");
} catch (ClassNotFoundException e)
System.out.println(cnn);
{
System.out.println("Oracle JDBC
} catch (ClassNotFoundException e) { Write a program to create table on Customer Driver not found. Include the driver in
with Cno, Name &Address using JDBC with try your library path.");
System.out.println("Oracle JDBC catch block.(Using statement )
Driver not found. Include the driver in your e.printStackTrace();
library path."); Code:
} catch (SQLException e) {
e.printStackTrace(); import java.sql.*;
} catch (SQLException e) {
System.out.println("Error creating
table. Check SQL syntax or database
System.out.println("Connection failed. connection.");
class Customer{
Check the connection URL, username, or
password."); public static void main(String[] args) { e.printStackTrace();
e.printStackTrace(); Connection cnn = null; } finally {
Write a program to Insert a row into Customer
} finally {
Statement stmt = null; try { table using JDBC.
try { if (stmt != null) stmt.close(); import java.sql.Connection;
try {
// Close the connection if it was if (cnn != null) { import java.sql.DriverManager;
established
Class.forName("oracle.jdbc.driver.Oracle cnn.close(); import java.sql.PreparedStatement;
if (cnn != null) { Driver");
import java.sql.SQLException;
cnn.close(); cnn = System.out.println("Connection closed.");
System.out.println("Connection DriverManager.getConnection("jdbc:oracl
closed."); e:thin:@localhost:1521:xe", "system", }
class insert{
"Harsha"); } catch (SQLException e) {
} public static void main(String[] args) {
stmt = cnn.createStatement(); System.out.println("Failed to
} catch (SQLException e) {
close resources."); Connection cnn = null;
System.out.println("Failed to close
the connection."); e.printStackTrace(); PreparedStatement pstmt = null;
String createTableSQL =
e.printStackTrace(); "CREATE TABLE customer46 (" } try {

} + "Cno INT PRIMARY KEY, }


" Class.forName("oracle.jdbc.driver.Oracle
} } Driver");
+ "Name VARCHAR(50), "
} } cnn =
+ "Address DriverManager.getConnection("jdbc:oracl
}
VARCHAR(100))"; Output:
Output:
e:thin:@localhost:1521:xe", "system", }
"Harsha");
} catch (SQLException e) { // Establish the connection // Close the statement
System.out.println("Failed to cnn = stmt.close();
String insertSQL = "INSERT INTO close resources."); DriverManager.getConnection("jdbc:oracl
} catch (ClassNotFoundException e)
customer46 (Cno, Name, Address) e:thin:@localhost:1521:xe", "system",
e.printStackTrace(); {
VALUES (?, ?, ?)"; "Harsha");
} System.out.println("Oracle JDBC
pstmt = System.out.println("Connection
Driver not found.");
cnn.prepareStatement(insertSQL); } successful");
e.printStackTrace();
pstmt.setInt(1, 1); // Example Cno }
} catch (SQLException e) {
pstmt.setString(2, "Harsha } // Create a statement object to
vardhan"); // Example Name execute queries System.out.println("SQL error
Output: occurred.");
pstmt.setString(3, "Hnk"); // Statement stmt =
Example Address cnn.createStatement(); e.printStackTrace();
} finally {
int rowsInserted = // Fetch and display all records try {
pstmt.executeUpdate(); from the cust table
if (cnn != null) {
System.out.println(rowsInserted + String selectSQL = "SELECT *
" row(s) inserted into Customer table."); FROM cust"; cnn.close();

} catch (ClassNotFoundException e) ResultSet rs =


{ stmt.executeQuery(selectSQL); System.out.println("Connection closed.");

System.out.println("Oracle JDBC }
Driver not found. Include the driver in Write a program to Retrieve (Select) all rows } catch (SQLException e) {
form an existing emp table such as empno, // Print header
your library path.");
ename, job and salary. System.out.printf("%-10s %-15s System.out.println("Failed to
e.printStackTrace(); close the connection.");
Code: %-15s%n", "Cno", "Name", "Address");
} catch (SQLException e) { e.printStackTrace();
import java.sql.*;
System.out.println("Error inserting }
// Print rows
data. Check SQL syntax or constraints.");
while (rs.next()) { }
e.printStackTrace(); class RetrieveCustomer {
int Cno = rs.getInt("Cno"); }
} finally { public static void main(String[] args) {
String Name = }
try { Connection cnn = null;
rs.getString("Name"); Output:
if (pstmt != null) pstmt.close(); try {
String Address =
if (cnn != null) { // Load Oracle JDBC Driver rs.getString("Address");
cnn.close(); System.out.printf("%-10d %-15s
Class.forName("oracle.jdbc.driver.Oracle %-15s%n", Cno, Name, Address);
Driver");
System.out.println("Connection closed."); }
} catch (SQLException e) { cnn.close(); e:thin:@localhost:1521:xe", "system",
System.out.println("Table "harsha");

doesn't exist or cannot be dropped, System.out.println("Connection System.out.println("Connection


successful");
proceeding to create."); closed.");
} }
String createTableSQL = } catch (SQLException e) { PreparedStatement pstmt =
cnn.prepareStatement("insert into
"CREATE TABLE Student1051 (" System.out.println("Failed to Student1051 values(?,?,?,?)");
+ "Sid INT PRIMARY close resources.");
pstmt.setInt(1,1051);
KEY, " e.printStackTrace();
7)To create a table on Student with Id, sname, + "sname VARCHAR(10), } pstmt.setString(2,"Harsha");
age, dept using oracle with SQL command. " } pstmt.setInt(3,19);
Code: }
import java.sql.*; +"age INT," } pstmt.setString(4,"CSE");
class Student{ + "dept VARCHAR(10))"; int i=pstmt.executeUpdate();
Output:
public static void main(String[] args)
{ stmt.executeUpdate(createTableSQL); pstmt.setInt(1,1041);
Connection cnn = null;
Statement stmt = null; System.out.println("Table pstmt.setString(2,"Sricharan");

try { 'Student1051' created successfully!"); pstmt.setInt(3,40);


} catch (ClassNotFoundException
Class.forName("oracle.jdbc.driver.Orac e) {
Write a program to Insert a row into Student pstmt.setString(4,"CSE");
table using Prepared Statement.
leDriver"); System.out.println("Oracle i+=pstmt.executeUpdate();
Code:
cnn = JDBC Driver not found. Include the
import java.sql.*; pstmt.setInt(1,1046);
DriverManager.getConnection("jdbc:or driver in your library path.");
e.printStackTrace(); class InsertStudent{
acle:thin:@localhost:1521:xe",
pstmt.setString(2,"Abhi");
"system", "harsha"); } catch (SQLException e) { public static void main(String[] args) {
pstmt.setInt(3,25);
stmt = cnn.createStatement(); System.out.println("Error Connection cnn = null;
try { creating table. Check SQL syntax or try {
pstmt.setString(4,"ECE");
String dropTableSQL = database connection.");
i+=pstmt.executeUpdate();
"DROP TABLE Student1051"; e.printStackTrace(); Class.forName("oracle.jdbc.driver.Oracle
Driver");
} finally {
System.out.println(i+" records
stmt.executeUpdate(dropTableSQL); try { inserted");
System.out.println("Existing if (stmt != null) stmt.close(); cnn =
DriverManager.getConnection("jdbc:oracl
table dropped successfully."); if (cnn != null) {
pstmt.close(); Write a program to Retrieve (Select) all rows } catch (SQLException e) { </form>
form an existing Student table.(Using web.XML
} catch (ClassNotFoundException e) Prepared statement) System.out.println("SQL error <web-app>
{ occurred.");
Code: <servlet>
System.out.println("Oracle JDBC e.printStackTrace();
Driver not found."); import java.sql.*; <servlet-name>s1</servlet-name>
} finally {
e.printStackTrace(); class RetrieveStudent{ <servlet-class>TestServlet</servlet-class>
try {
} catch (SQLException e) { public static void main(String[] args) { </servlet>
if (cnn != null) {
System.out.println("SQL error Connection cnn = null; <servlet-mapping>
cnn.close();
occurred."); <servlet-name>s1</servlet-name>
try {
e.printStackTrace(); <url-pattern>/TestServlet</url-pattern>
System.out.println("Connection closed.");
} finally { Class.forName("oracle.jdbc.driver.OracleD </servlet-mapping>
river"); }
try { </web-app>
} catch (SQLException e) {
if (cnn != null) { TestServlet.java:
cnn = System.out.println("Failed to import java.io.*;
cnn.close(); DriverManager.getConnection("jdbc:oracle close the connection.");
import jakarta.servlet.*;
:thin:@localhost:1521:xe", "system", e.printStackTrace();
"harsha"); import jakarta.servlet.http.*;
System.out.println("Connection closed.");
}
} System.out.println("Connection
successful"); }
public class TestServlet extends HttpServlet {
} catch (SQLException e) {
}
public void doGet(HttpServletRequest req,
System.out.println("Failed to
PreparedStatement } HttpServletResponse res) throws IOException,
close the connection.");
ServletException {
pstmt=cnn.prepareStatement("select * from Output:
e.printStackTrace(); Student1051"); res.setContentType("text/html");
} ResultSet PrintWriter out = res.getWriter();
} rs=pstmt.executeQuery();
String s1 = req.getParameter("tf1");
} while(rs.next()){
out.print("<h1>Welcome " + s1 +
} "</h1>");
System.out.println(rs.getInt(1)+"
Output: out.close();
"+rs.getString(2)+" "+rs.getInt(3)+" Servlet Code:
"+rs.getString(4)); }

} Index.html: }
<form action="TestServlet" method="get"> Cookies:
pstmt.close();
Index.html:
} catch (ClassNotFoundException e) { Enter name:<input type="text" name="tf1"
<!DOCTYPE html>
/><br>
System.out.println("Oracle JDBC <html lang="en">
Driver not foPund."); <input type="submit" value="submit" />
<head>
e.printStackTrace();
<meta charset="UTF-8"> <servlet> if (cookies != null) { res.setContentType("text/html");

<meta name="viewport" <servlet- for (Cookie cookie : cookies) { PrintWriter out = res.getWriter();
content="width=device-width, initial- name>GetCookieServlet</servlet-name>
if (cookie.getName().equals("name")) String s1 = req.getParameter("tf1");
scale=1.0">
<servlet-class>GetCookieServlet</servlet- {
String s2 = req.getParameter("tp1");
<title>Login Page</title> class>
name = cookie.getValue();
Cookie c1= new Cookie("name",s1);
</head> </servlet>
} else if
Cookie c2= new Cookie("password",s2);
<body> <servlet-mapping> (cookie.getName().equals("password")) {
res.addCookie(c1);
<h2>Login Form</h2> <servlet- password = cookie.getValue();
name>GetCookieServlet</servlet-name> res.addCookie(c2);
<form action="TestServlet" method="get"> }
<url-pattern>/GetCookieServlet</url- out.println("Welcome To my
<label for="name">Enter Name:</label> }
pattern> Website"+s1);
<input type="text" id="name" name="tf1" }
</servlet-mapping> out.println("<a
required>
href='GetCookieServlet'>Request Login</a>");
</web-app>
<br><br>
GetCookieServlet.java: // Display cookie values out.close();
<label for="password">Enter import java.io.*;
out.println("<html><body>"); }
Password:</label>
import jakarta.servlet.*;
out.println("Name from cookie: " + name }
<input type="password" id="password"
import jakarta.servlet.http.*; + "<br>"); Httpsession and jsp base program
name="tp1" required>
out.println("Password from cookie: " +
<br><br> <!DOCTYPE html>
password);
public class GetCookieServlet extends
<input type="submit" value="Submit"> <html>
HttpServlet { out.println("</body></html>");
</form> <head>

</body> <title>Login Page</title>


public void doGet(HttpServletRequest req, out.close();
</html> HttpServletResponse res) throws IOException </head>
{ }
<body>
res.setContentType("text/html"); }
Web.xml:
<h2>Login</h2>
<web-app>
PrintWriter out = res.getWriter(); TestServlet.java:
<form action="login.jsp" method="post">
<servlet> import java.io.*;
<label
<servlet-name>s1</servlet-name> import jakarta.servlet.*;
// Retrieve cookies from the request for="username">Username:</label>
<servlet-class>TestServlet</servlet-class> import jakarta.servlet.http.*;
Cookie[] cookies = req.getCookies(); <input type="text" id="username"
</servlet> name="username" required><br>
String name = "Not Found";
<servlet-mapping> public class TestServlet extends HttpServlet { <label for="password">Password:</label>
String password = "Not Found";
<servlet-name>s1</servlet-name> <input type="password" id="password"
name="password" required><br>
<url-pattern>/TestServlet</url-pattern> public void doGet(HttpServletRequest req,
// Check if cookies are present and
HttpServletResponse res) throws IOException <button type="submit">Login</button>
</servlet-mapping> extract values
{
</form>
</body> HttpSession session = 2. Develop an Angular JS application that
request.getSession(false);
displays a list of shopping items. Allow app.controller('ShoppingListController',
</html>
function($scope) {
Login.jsp: users to add and remove items from the list
<%@ page import="java.io.*, if (session == null || using directives and controllers.
javax.servlet.http.*, javax.servlet.*" %> session.getAttribute("username") == null) { $scope.shoppingList = ['Milk',
<% // No valid session found, redirect to login Note: The default values of items may be 'Bread', 'Cheese'];
included in the program. $scope.addItem = function() {
// Fetch user input response.sendRedirect("login.html");

String username = } else { Code: if ($scope.newItem) {


request.getParameter("username");
// Retrieve user data from session <!DOCTYPE html>
String password = $scope.shoppingList.push($scope.newItem
String username = (String) <html> );
request.getParameter("password");
session.getAttribute("username");
<head> $scope.newItem = '';
%>
// Dummy authentication logic <title>Shopping List</title> }
<h2>Welcome, <%= username %>!</h2>
if ("admin".equals(username) && <script };
"password".equals(password)) {
<a href="logout.jsp">Logout</a> src="https://ajax.googleapis.com/ajax/libs/
angularjs/1.8.2/angular.min.js"></script> $scope.removeItem =
<% function(index) {
// Create a session and store user data
} </head>
HttpSession session =
request.getSession(); %> <body ng-app="shoppingApp" ng- $scope.shoppingList.splice(index, 1);
logout.jsp: controller="ShoppingListController">
session.setAttribute("username", };
<%@ page import="java.io.*, <h1>Shopping List</h1>
username);
javax.servlet.http.*, javax.servlet.*" %> });
<input type="text" ng-
<% model="newItem" placeholder="Enter </script>
// Redirect to welcome page item" />
// Get the current session and invalidate it </body>
response.sendRedirect("welcome.jsp"); <button ng-click="addItem()">Add
HttpSession session = </html>
} else { request.getSession(false); Item</button>

out.println("<h3>Invalid username or <ul>


password. Please try again.</h3>");
if (session != null) { <li ng-repeat="item in
out.println("<a href='login.html'>Back to shoppingList">
session.invalidate();
Login</a>");
{{item}} <button ng-
}
} click="removeItem($index)">Remove</bu
out.println("<h3>You have successfully tton>
%>
logged out!</h3>");
Welcome.jsp: </li>
<%@ page import="java.io.*, out.println("<a href='login.html'>Login
javax.servlet.http.*, javax.servlet.*" %> </ul>
Again</a>");
<% <script>
%>
// Get the current session var app =
angular.module('shoppingApp', []);
3. Implement form controls with validation, model="user.username" <span ng- ng-required="true"
ensuring that required fields are filled and the
input is in the correct format. Code: placeholder="Enter Username" show="userForm.password.$touche ng-min="18" /><br/>
<html > d && userForm.password.$invalid"
ng-required="true" ng- <span ng-
style="color:red;">
<head> minlength="3" /><br/> show="profileForm.age.$touched
<span ng- && profileForm.age.$invalid"
<title>User Registration <span ng-
show="userForm.password.$error.re style="color:red;">
Form</title> show="userForm.username.$touche
quired">Password is
d && userForm.username.$invalid" <span ng-
<script required.</span>
style="color:red;"> show="profileForm.age.$error.requir
src="https://ajax.googleapis.com/aja
<span ng- ed">Age is required.</span>
x/libs/angularjs/1.8.2/angular.min.js" <span ng-
show="userForm.password.$error.m
></script> show="userForm.username.$error.re <span ng-
inlength">Password must be at least
quired">Username is show="profileForm.age.$error.min"
</head> 6 characters long.</span>
required.</span> >You must be at least 18 years
<body ng- </span><br/> old.</span>
<span ng-
app="userRegistrationApp">
show="userForm.username.$error.m </form> </span><br/>
inlength">Username must be at least
<div ng-
<div ng- 3 characters long.</span>
controller="ProfileInfoController">
<label>Gender:</label>
controller="UserDetailsController"> </span><br/>
<h3>Profile
<select name="gender"
<h2>User Registration Information</h3>
ng-model="profile.gender" ng-
Form</h2>
<label>Password:</label> <form name="profileForm" required="true">
<h3>User Details</h3> novalidate>
<input type="password" <option value=""
<form name="userForm" name="password" ng- <label>Age:</label> disabled selected>Select
novalidate> model="user.password" Gender</option>
<input type="number"
<label>Username:</label> placeholder="Enter Password"
name="age" ng-model="profile.age" <option
<input type="text" ng-required="true" ng- placeholder="Enter Age" value="Male">Male</option>
name="username" ng- minlength="6" /><br/>
<option </div> 8 SELECT sal INTO v_salary

value="Female">Female</option> 9 FROM e1051


</body>
10 WHERE e_id = p_emp_id;
<option
<script> </html> 11 IF v_salary < 50000 THEN
value="Other">Other</option>
12 v_bonus := v_salary * 0.10;
var app =
</select><br/> 13 ELSIF v_salary < 100000 THEN
angular.module('userRegistrationAp
14 v_bonus := v_salary * 0.15;
<span ng- p', []);
15 ELSE
show="profileForm.gender.$touched
16 v_bonus := v_salary * 0.20;
&& profileForm.gender.$invalid"
app.controller('UserDetailsControlle 17 END IF;
style="color:red;">
r', function($scope) { 18 RETURN v_bonus;
Gender is required. 19 EXCEPTION
$scope.user = {
20 WHEN NO_DATA_FOUND
</span><br/>
username: '', THEN

</form> 21 RETURN 0;
password: ''
22 END;
<h3>Summary</h3>
}; 23 /

});
<p><strong>Username:</strong>
{{user.username}}</p>
4. Create a stored function in Oracle that
app.controller('ProfileInfoController'
accepts an employee's ID and returns the
, function($scope) { calculated bonus based on their salary. Use
<p><strong>Password:</strong> the Callable Statement to invoke the stored
$scope.profile = { function from a Java program and retrieve the
{{user.password}}</p> returned bonus value.
SQL> CREATE OR REPLACE
age: '',
<p><strong>Age:</strong> FUNCTION calculate_bonus (

{{profile.age}}</p> gender: '' 2 p_emp_id IN e1051.e_id%TYPE


3 ) RETURN NUMBER
};
4 AS
<p><strong>Gender:</strong>
}); 5 v_salary e1051.sal%TYPE;
{{profile.gender}}</p>
6 v_bonus NUMBER;
</script>
</div> 7 BEGIN import java.sql.*;
class employeebonus { try {
public static void main(String[] args) { if (callableStatement != null)
callableStatement.close();
Connection connection = null;
if (connection != null)
CallableStatement callableStatement
connection.close();
= null;
} catch (SQLException e) {
try {
e.printStackTrace();
Class.forName("oracle.jdbc.driver.Oracle }
Driver");
}
connection =
}
DriverManager.getConnection("jdbc:oracl
e:thin:@localhost:1521:xe", "system", }
"harsha");
Output:
String sql = "{? = call
calculate_bonus(?)}";
callableStatement =
connection.prepareCall(sql);

int employeeId = 1051;

callableStatement.registerOutParameter(1,
Types.DOUBLE);
callableStatement.setInt(2,
employeeId);

callableStatement.execute();

double bonus =
callableStatement.getDouble(1);

System.out.println("Calculated
Bonus: " + bonus);
} catch (Exception e) {
e.printStackTrace();
} finally {
SERVLETS: button {
Index.html width: 100%;
<!DOCTYPE html> padding: 10px;
<html> border: none;
<head> border-radius: 4px;
<title>Login Form</title> background-color: #4CAF50;
<style> color: white;
body { font-size: 16px;
font-family: Arial, sans-serif; cursor: pointer;
display: flex; }
justify-content: center; button:hover {
align-items: center; background-color: #45a049;
height: 100vh; }
margin: 0; </style>
background-color: #f0f2f5; </head>
} <body>
.login-container {
width: 300px; <div class="login-container">
padding: 20px; <h2>Login</h2>
border-radius: 5px; <form action="TestServlet" method="get">
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); Enter name:<input type="text"name="tf1"/><br>
background-color: white; Password:<input type="password" name="tp1"/><br>
text-align: center; <input type="submit" value="submit">
}
h2 { </form>
margin-bottom: 20px; </div>
color: #333; </body>
} </html>
input[type="text"], input[type="password"] { WEB.XML
width: 100%; <web-app>
padding: 10px; <servlet>
margin: 8px 0; <servlet-name>s1</servlet-name>
border: 1px solid #ddd; <servlet-class>TestServlet</servlet-class>
border-radius: 4px; </servlet>
box-sizing: border-box; <servlet-mapping>
} <servlet-name>s1</servlet-name>
<url-pattern>/TestServlet</url-pattern> <servlet-class>Add1</servlet-class>
</servlet-mapping> </servlet>
</web-app> <servlet-mapping>
TESTSERVELETS.java <servlet-name>s1</servlet-name>
import java.io.*; <url-pattern>/Add1</url-pattern>
import javax.servlet.*; </servlet-mapping>
import javax.servlet.http.*; <servlet>
public class TestServlet extends HttpServlet{ <servlet-name>Display1</servlet-name>
public void doGet(HttpServletRequest req,HttpServletResponse res)throws <servlet-class>Display1</servlet-class>
IOException,ServletException </servlet>
{ <servlet-mapping>
res.setContentType("text/html"); <servlet-name>Display1</servlet-name>
PrintWriter out=res.getWriter(); <url-pattern>/Display1</url-pattern>
String s1=req.getParameter("tf1"); </servlet-mapping>
String s2=req.getParameter("tp1"); </web-app>
out.print("<h1>Welcome"+s1+"</h1>");
out.close(); Add1.java
} import java.io.*;
} import javax.servlet.*;
import javax.servlet.http.*;
public class Add1 extends HttpServlet
HTTPS SESSIONS: {
Index.html public void doGet(HttpServletRequest req,HttpServletResponse res)throws
<html> IOException,ServletException
<head></head> {
<body> res.setContentType("text/html");
<form action="Add1" method="get"> PrintWriter out=res.getWriter();
Enter name:<input type="text" name="tf1"/><br> String s1=req.getParameter("tf1");
Password:<input type="password" name="p1" /><br> String s2=req.getParameter("tp1");
<input type="submit" value="submit" /> HttpSession ses=req.getSession(true);
</form></body> ses.setAttribute("username",s1);
</html> ses.setAttribute("password",s1);
Web.xml out.print("<h1><a href='Display1'>Wecome"+s1+"</a></h1>");
<web-app> out.close();
<servlet> }}
<servlet-name>s1</servlet-name>
Display1.java return a + b;
import java.io.*; }
import javax.servlet.*; %>
import javax.servlet.http.*; <html>
public class Display1 extends HttpServlet <body>
{ <h1>Addition</h1>
public void doGet(HttpServletRequest req,HttpServletResponse res)throws <%
IOException,ServletException String x1 = request.getParameter("t1");
{ String y1 = request.getParameter("t2");
res.setContentType("text/html"); int x = 0, y = 0;
PrintWriter out=res.getWriter(); if (x1 != null && y1 != null) {
HttpSession ses=req.getSession(false); try {
String n=(String)ses.getAttribute("username"); x = Integer.parseInt(x1);
out.print("Hello"+n); y = Integer.parseInt(y1);
out.close(); } catch (NumberFormatException e) {
}} out.println("<p>Error: Invalid input. Please enter valid numbers.</p>");
}
JSP CODES: }
Add.html int sum1 = add(10, 20);
<html><form action="sample.jsp" method="get"> int sum2 = add(x, y);
First Number:<input type=textname="t1"> %>
Second Number:<input type=textname="t2"> <p>Sum of 10 and 20: <%= sum1 %></p>
<input type=submit value="submit"> <p>Sum of provided numbers: <%= sum2 %></p>
</form> </body>
</html> </html>

Web.xml
<webapp> 8) servlets
<welcome-file-list> File: GreetingServlet.java
<welcome-file>add.html</welcome-file> import java.io.IOException;
</welcome-file-list> import java.io.PrintWriter;
</webapp> import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
Sample.jsp import javax.servlet.http.HttpServlet;
<%! import javax.servlet.http.HttpServletRequest;
public int add(int a, int b) { import javax.servlet.http.HttpServletResponse;
@WebServlet("/greet") <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
public class GreetingServlet extends HttpServlet { <servlet>
@Override <servlet-name>GreetingServlet</servlet-name>
protected void doGet(HttpServletRequest request, HttpServletResponse <servlet-class>com.example.GreetingServlet</servlet-class>
response) throws ServletException, IOException { </servlet>
response.setContentType("text/html"); <servlet-mapping>
PrintWriter out = response.getWriter(); <servlet-name>GreetingServlet</servlet-name>
// HTML form for user input <url-pattern>/greet</url-pattern>
out.println("<html>"); </servlet-mapping>
out.println("<head><title>Greeting Servlet</title></head>"); </web-app>
out.println("<body>"); 9) cookies
out.println("<h1>Welcome to the Greeting Servlet!</h1>"); import java.io.IOException;
out.println("<form action='greet' method='post'>"); import java.io.PrintWriter;
out.println("Enter your name: <input type='text' name='username'><br>"); import javax.servlet.ServletException;
out.println("<input type='submit' value='Submit'>"); import javax.servlet.annotation.WebServlet;
out.println("</form>"); import javax.servlet.http.Cookie;
out.println("</body>"); import javax.servlet.http.HttpServlet;
out.println("</html>"); import javax.servlet.http.HttpServletRequest;
} import javax.servlet.http.HttpServletResponse;
@Override @WebServlet("/createCookie")
protected void doPost(HttpServletRequest request, HttpServletResponse public class CreateCookieServlet extends HttpServlet {
response) throws ServletException, IOException { @Override
response.setContentType("text/html"); protected void doGet(HttpServletRequest request, HttpServletResponse
PrintWriter out = response.getWriter(); response) throws ServletException, IOException {
// Retrieving user input // Create a cookie with name "username" and value "JohnDoe"
String name = request.getParameter("username"); Cookie userCookie = new Cookie("username", "JohnDoe");
// Displaying personalized greeting // Set the cookie to expire after 24 hours
out.println("<html>"); userCookie.setMaxAge(60 * 60 * 24);
out.println("<head><title>Greeting Result</title></head>"); // Add the cookie to the response
out.println("<body>"); response.addCookie(userCookie);
out.println("<h1>Hello, " + name + "! Welcome to the Servlet Example.</h1>"); response.setContentType("text/html");
out.println("</body>"); PrintWriter out = response.getWriter();
out.println("</html>"); // Display a confirmation message
} out.println("<html>");
} out.println("<head><title>Cookie Created</title></head>");
File: web.xml out.println("<body>");
out.println("<h1>Cookie has been created successfully!</h1>"); session.setAttribute("username", "JohnDoe");
out.println("<p>Cookie Name: username</p>"); session.setAttribute("role", "Admin");
out.println("<p>Cookie Value: JohnDoe</p>"); // HTML response to confirm session creation
out.println("</body>"); out.println("<html>");
out.println("</html>"); out.println("<head><title>Session Created</title></head>");
} out.println("<body>");
} out.println("<h1>Session Created Successfully</h1>");
File: web.xml out.println("<p>Session ID: " + session.getId() + "</p>");
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1"> out.println("<p>Username: JohnDoe</p>");
<servlet> out.println("<p>Role: Admin</p>");
<servlet-name>CreateCookieServlet</servlet-name> out.println("<a href='/'>Go Back</a>");
<servlet-class>CreateCookieServlet</servlet-class> out.println("</body>");
</servlet> out.println("</html>");
<servlet-mapping> }
<servlet-name>CreateCookieServlet</servlet-name> }
<url-pattern>/createCookie</url-pattern> web.xml
</servlet-mapping> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
</web-app> <servlet>
10) sessions <servlet-name>CreateSessionServlet</servlet-name>
CreateSessionServlet.java <servlet-class>CreateSessionServlet</servlet-class>
import java.io.IOException; </servlet>
import java.io.PrintWriter; <servlet-mapping>
import javax.servlet.ServletException; <servlet-name>CreateSessionServlet</servlet-name>
import javax.servlet.http.HttpServlet; <url-pattern>/createSession</url-pattern>
import javax.servlet.http.HttpServletRequest; </servlet-mapping>
import javax.servlet.http.HttpServletResponse; </web-app>
import javax.servlet.http.HttpSession; 11) JSP
public class CreateSessionServlet extends HttpServlet { ArithmeticOperations.jsp
@Override <%@ page language="java" contentType="text/html; charset=UTF-8"
protected void doGet(HttpServletRequest request, HttpServletResponse pageEncoding="UTF-8"%>
response) throws ServletException, IOException { <%@ page import="java.io.*" %>
response.setContentType("text/html"); <%
PrintWriter out = response.getWriter(); String result = "";
// Create or retrieve the existing session // Check if the form was submitted
HttpSession session = request.getSession(); if(request.getMethod().equalsIgnoreCase("POST")) {
// Store data in the session // Get the input values from the form
String num1 = request.getParameter("num1"); <html>
String num2 = request.getParameter("num2"); <head>
String operation = request.getParameter("operation"); <title>Arithmetic Operations</title>
if (num1 != null && num2 != null && !num1.isEmpty() && !num2.isEmpty()) { </head>
try { <body>
// Convert input to integers <h2>Arithmetic Operations</h2>
int number1 = Integer.parseInt(num1); <!-- Form to input numbers and choose an operation -->
int number2 = Integer.parseInt(num2); <form method="post">
int res = 0; Number 1: <input type="text" name="num1"><br><br>
// Perform the selected arithmetic operation Number 2: <input type="text" name="num2"><br><br>
if (operation.equals("add")) { <label>Select operation:</label><br>
res = number1 + number2; <input type="radio" name="operation" value="add"> Add<br>
result = "Result: " + res; <input type="radio" name="operation" value="subtract"> Subtract<br>
} else if (operation.equals("subtract")) { <input type="radio" name="operation" value="multiply"> Multiply<br>
res = number1 - number2; <input type="radio" name="operation" value="divide"> Divide<br><br>
result = "Result: " + res; <input type="submit" value="Calculate">
} else if (operation.equals("multiply")) { </form>
res = number1 * number2; <h3><%= result %></h3>
result = "Result: " + res; </body>
} else if (operation.equals("divide")) { </html>
if (number2 != 0) { web.xml
res = number1 / number2; <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
result = "Result: " + res; <servlet>
} else { <servlet-name>ArithmeticOperations</servlet-name>
result = "Error: Division by zero is not allowed."; <jsp-file>/ArithmeticOperations.jsp</jsp-file>
} </servlet>
} <servlet-mapping>
} catch (NumberFormatException e) { <servlet-name>ArithmeticOperations</servlet-name>
result = "Error: Please enter valid numbers."; <url-pattern>/arithmetic</url-pattern>
} </servlet-mapping>
} else { </web-app>
result = "Error: Please enter both numbers.";
}
}
%>
<!DOCTYPE html>

You might also like