WT Merged Final
WT Merged Final
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
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
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
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.
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>
<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)">×</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.
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.
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.
• 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;
• 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());
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.
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.
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
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.
<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
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.
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.
}
// 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 { }
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
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
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
An optional message body like file, query data or query output. 204 No 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
doGet(request, response);
}
}
Now calling the above servlet would display the following result −
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
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 −
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>
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 −
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>");
}
doGet(request, response);
}
}
<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.
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
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 {
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 −
Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as
follows −
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.
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 {
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.
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>
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.
• 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"/>
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>
• 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 <% %> — 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.
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.
• 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>
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.
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.
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>
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");
} 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>
</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 (
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>