java web UNIT1
java web UNIT1
Technologies used
The progressive web application is a type of application software for the web, built using
technologies such as HTML, CSS, and JavaScript. In simpler terms, a progressive web app is
a website that looks and feels like an app instead of a website. Web users can browse on their
browser with an URL just like every other website; however, they get the experience of using
an “app” without the need to download and install.
PWA is not limited to either PC or mobile, and they can be implemented both on desktops
and mobile devices. To figure out if a website is a PWA, you can access different pages and
see if the pages reload. If they don’t, they are behaving as an app, and they are an example of
PWA. There are many popular PWA that we are currently using daily such as Pinterest, Uber,
Starbucks, and Spotify.
2.MICRO FRONTENDS
Angular
Angular is a TypeScript-based, open-source, front-end mobile and web application
framework developed by Google in 2010. Angular is a complete rewrite of AngularJS from
the same team. In short, Angular is a platform and framework for building dynamic single-
page client applications through HTML and TypeScript.
Compared to Angular, AngularJS is based on JavaScript and has notions of scope and
controllers instead of a hierarchy of components and services like Angular. AngularJS
follows the MVC (model-view-controller) model, which acts as the central component and
dictates how the applications behave. There is also no mobile support for AngularJS.
Angular is popular due to its ability to create multiple modules for a single web application.
These modules can then act independently, and developers can compile them to create a
single running, dynamic application for end-users. Angular helps developers ensure swift
development and lighter and faster apps due to deleting unnecessary codes.
Since Angular is developed and maintained by Google, there are many resources and
communities that you can learn Angular from and for continuous support and guidance. This
makes Angular one of the top frameworks for your mobile and web app projects.
React
React is an open-source, front-end JavaScript library for creating interactive UIs. React is
developed and maintained by Facebook and a large community of dedicated developers.
React can also be used as a base for a single-page or mobile application.
React is for websites (front-end), while React Native is for mobile applications, including
iOS and Android. Based on React, React Native helps developers produce mobile apps cross-
platform with simplicity and flexibility.
React is still one of the most popular JavaScript front-end frameworks despite being a library
due to its clean programming, strong community, and fast performance.
Java Servlet is Java's first-ever server-side web technology that enables you to define HTTP-
specific classes. The servlet class expands the power and capability of the servers and hosts
the application. These applications can be accessed with the request-response editing model.
Although a servlet can respond to any request, the main purpose of using a servlet is to
extend applications hosted by web servers. For example, you can use servlets to get data
input from an online application or even extend it to appear on the screen or an HTML page.
Additionally, you can use the servlet to write data to a database or file. The servlet works on
the server-side with no application GUI or HTML.
Java Server Pages (JSP) technology is very popular among developers and provides an easy
and fast way to improve dynamic web content. It leads to the rapid development of web
platforms and standalone web applications. Additionally, you can add a snippet of servlet
code to the text document of the app, making JSP friendly to the developer. Also, JSP pages
are text-based documents that include two types of text:
Static Data that can be expressed in any text format, including XML, HTML, or WML. JSP
Technology fully determines dynamic content creation on a web page.
The packages used for JSP page building are javax.servlet.jsp, javax.el,
javax.servlet.jsp.tagexta, and javax.servlet.jsp.el. However, you will need to import them
directly. With JSP, it can be very easy to create a web application with snipped JSP code and
extensions.
You can develop a website with JSP technology pages by using single captions and inserting
them into the header.html file that describes site navigation. To make changes to buttons or
links, you need to make changes to one file, and it will be automatically redirected all over
the site.
Because of this, the Java program development company claims that JSP is the best
technology for creating powerful web contents such as forms, surveys, and more.
The JavaServer Pages Standard Tag Library (JSTL) integrates core functionality common to
many JSP-based applications. Instead of mixing tags from multiple vendors in your
applications, you are using one common set of tags. This configuration allows you to run
your applications on any JSP container that supports JSTL and makes it more likely that the
tag implementation will be improved.
JSTL has duplicate tags and conditional tags to control flow controls, XML document
deciphering tags, global tags, website access tags using SQL, and commonly used function
tags. The packages you can access using JSTL are javax.servlet.jsp.jstl.core,
javax.servlet.jsp.jstl.fmt, javax.servlet.jsp.jstl.sql, and javax.servlet.jsp.jstl. tlv.
4. JDBC API
The Java Database Connectivity (JDBC) API is very popular, and most developers
understand how important JDBC is for web application development as it allows you to
request SQL database commands within Java applications. Additionally, there are no special
restrictions involved, as you can request JDBC API in servlet, JSP pages, or enterprise beans.
JDBC comprises two components, one application-level interface and another service
provider interface. An application-level interface is used to access the database through
application components, and the server provider integrates the JDBC driver into the Java
enterprise platform.
You already know the importance of sending messages, whether between people or parts of
software or applications. Throughout the software program, the messaging system is peer-to-
peer-centric. In short, the messaging client sends a message to the recipient client and
receives messages from other clients.
In this, each client connects to a message agent that assists in creating, sending, receiving,
and reading the message. The Java Messaging Service API is a Java technology platform that
solves the problem of communication between clients and achieves its purpose. Enterprise
messaging offers a flexible, reliable way of data exchange throughout the business. The JMS
API extends this functionality and adds to the provider framework to provide the
development of portable messaging applications in the Java language. Additionally, how you
will be using the JMS is a matter of perception. One way is to use it to maintain innovative
monitoring.
It also provides namespace support that allows your application to work with conflicting
word schemes. It is highly customizable, allows you to use XML and XSL compliant
processors in your application, and supports the W3C schema.
7. Java Naming and Directory Interface (JNDI)
As the name elevates itself, it provides naming and directory features, enabling apps to access
multiple naming services and directory services. In addition, it provides applications with
methods that can perform common directory operations such as object search, attribute
association, and more. In addition, using the JNDI, various types of named Java technology
objects can be stored and retrieved, allowing applications to co-exist with many legacy
applications and systems. Access to the JNDI naming environment is provided by Naming
services to application clients, web components, and enterprise beans.
Additionally, developers can customize the components using a naming environment without
changing or accessing the source code of the component.
The Java Persistence API (JPA) uses an object-relational mapping to link an object-oriented
model to a database. Relational data in Java applications can be easily managed with Java
Persistence. It helps to store or retrieve large amounts of data from the database on a
continuous basis.
You do not have to use excess of codes, proprietary frameworks, etc. In order to connect to
the site, JPA will provide you with an easy way to communicate with the site using an object
relational approach. JPA is a collection of effective classes and methods that can connect you
to a database.
Web applications can use the JavaMail API to send email notifications. The API consists of
two parts: the application-level interface used by the program components to send an email
and the service provider's interface. Service providers use some email protocols, such as
SMTP (Simple Mail Transfer Protocol). Several service providers are included with the
JavaMail API package, and some are available separately. The Java EE forum includes a
JavaMail extension with a service provider that allows parts of the application to send email.
By integrating with the JavaMail extension, you can use the JavaBeans Activation
Framework (JAF) API. This API provides standard services to determine the type of incorrect
data, compile access to it, locate the services available to it, and create an appropriate
component based on the creation of a JavaBeans component (JavaBeans component) to
perform those tasks.
You might want to consider using the following other technologies in your web application,
depending on the application's complexity:
J2EE Connector Architecture: Tool vendors and system integrators use this platform to
create service adapters that support access to business information systems that can be linked
to any product based on Java EE technology.
Java API for XML Registries (JAXR): JAXR allows you to access business registrations
and general purposes on the web.
Java Architecture for XML Binding (JAXB): JAXB provides an easy way to integrate
XML schema into a representation in applications written in Java programming language.
SOAP with Attachments API for Java (SAAJ): SAAJ is a low-level API on which JAX-
WS and JAXR rely.
Java Transaction API (JTA): JTA provides a standard visual interface for designing tasks.
Java Beans: JavaBeans classes combine several elements into one component known as a
bean. JavaBean is a class that should be serializable, have a no argument constructor, and
should also provide methods for setting or acquiring property values.
Net Beans IDE: NetBeans is an open source, free integrated development platform for web,
mobile or desktop applications using Java. It provides complete integrated support for the
development cycle namely from creation to profiling, error correction and deployment.
Before developing the web applications, we need to have idea about design models. There are
two types of programming models (design models)
1. Model 1 Architecture
2. Model 2 (MVC) Architecture
Model 1 Architecture
Servlet and JSP are the main technologies to develop the web applications.
Servlet was considered superior to CGI. Servlet technology doesn't create process, rather it
creates thread to handle request. The advantage of creating thread over process is that it
doesn't allocate separate memory area. Thus many subsequent requests can be easily handled
by servlet.
Problem in Servlet technology Servlet needs to recompile if any designing code is modified.
It doesn't provide separation of concern. Presentation and Business logic are mixed up
JSP overcomes almost all the problems of Servlet. It provides better separation of concern,
now presentation and business logic can be easily separated. You don't need to redeploy the
application if JSP page is modified. JSP provides support to develop web application using
JavaBean, custom tags and JSTL so that we can put the business logic separate from our JSP
that will be easier to test and debug.
As you can see in the above figure, there is picture which show the flow of the model1
architecture.
o Navigation control is decentralized since every page contains the logic to determine
the next page. If JSP page name is changed that is referred by other pages, we need to
change it in all the pages that leads to the maintenance problem.
o Time consuming You need to spend more time to develop custom tags in JSP. So
that we don't need to use scriptlet tag.
o Hard to extend It is better for small applications but not for large applications.
Model The model represents the state (data) and business logic of the application.
View The view module is responsible to display data i.e. it represents the presentation.
Controller The controller module acts as an interface between view and model. It intercepts
all the requests i.e. receives input and commands to Model / View to change accordingly.
o We need to write the controller code self. If we change the controller code, we need to
recompile the class and redeploy the application.
MVC Architecture
In this section, we will discuss the MVC Architecture in Java, alongwith its advantages and
disadvantages and examples to understand the implementation of MVC in Java.
The model designs based on the MVC architecture follow MVC design pattern. The
application logic is separated from the user interface while designing the software using
model designs.
o Model: It represents the business layer of application. It is an object to carry the data
that can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize the
data that the model contains.
o Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data is
changed.
In Java Programming, the Model contains the simple Java classes, the View used to display
the data and the Controller contains the servlets. Due to this separation the user requests are
processed as follows:
1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
Model Layer
The Model in the MVC design pattern acts as a data layer for the application. It represents the
business logic for application and also the state of application. The model object fetch and
store the model state in the database. Using the model layer, rules are applied to the data that
represents the concepts of application.
View Layer
As the name depicts, view represents the visualization of data received from the model. The
view layer consists of output of application or user interface. It sends the requested data to the
client, that is fetched from model layer by controller.
Controller Layer
The controller layer gets the user requests from the view layer and processes them, with the
necessary validations. It acts as an interface between Model and View. The requests are then
sent to model for data processing. Once they are processed, the data is sent back to the
controller and then displayed on the view.
1. Application –
This component basically calls ODBC function and submits SQL statements.
2. Driver Manager –
The role of this component is to load driver for each application.
3. Driver –
Role of this component to handle all function calls and then submits each SQL
requests to a data source.
4. Data Source –
Role of this component to access data.
Features of ODBC :
Following are some of features of ODBC :
Error Codes –
ODBC basically supports error code mechanism to show issues which caused
error to occur while processing SQL statements.
Attributes –
Beside Error Code feature it also provides different types of functions to get
details of attributes and functions that are used in drivers.
Rich metadata –
ODBC also provides huge support to data about data also known as metadata.
ODBC also provides different functions to get data about both functions and
data types used.
Inter-operability –
The most important feature of ODBC is its interoperability that means using
ODBC driver we can develop different applications that can communicate with
different DB also known as Database Management System and switching our
application from one database to another will not create any problem.
SQL Syntax –
ODBC basically implements SQL syntax for easy understanding of user because
SQL syntax are easily understood by end-user. Whenever an SQL statement is
passed by user to ODBC driver it matches given statement to SQL 92 standard
and converts it into respective SQL statement that is accepted by an underlying
database.
1. It is well integrated into many different RAD tools.
4. It also helps to edit multiple different objects at a time, with the help
of templates provided by ODBC.
Disadvantages of ODBC:
Despite having lots of advantages and features ODBC also posses some disadvantages too
these are as follows :
1. Slow with large databases –
As the size of databases increase speed of ODBC reduces.
3. Complicated to build –
These ODBC drivers are complicated to build and also complicated to maintain.
4. Depends on framework –
As ODBC specification specifies only application protocol so it basically
inherits features of framework in which it is used on. Thus we can say that
reliability depends on implementation of request/response protocol of underlying
framework that is being used.
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
We can use JDBC API to handle database using Java program and can perform the following
activities:
API
API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs
can follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc.
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is
now discouraged because of thin driver.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why
it is known as thin driver. It is fully written in Java language.
// Main class
class Main {
System.out.println("enter name");
String name = k.next();
System.out.println("enter class");
String cls = k.next();
// Creating a statement
Statement st = con.createStatement();
// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println(
"inserted successfully : " + sql);
else
System.out.println("insertion failed");
Components of JDBC
There are generally four main components of JDBC through which it can interact with a
database. They are as mentioned below:
1. JDBC API: It provides various methods and interfaces for easy communication with the
database. It provides two packages as follows, which contain the java SE and Java EE
platforms to exhibit WORA(write once run anywhere) capabilities.
java.sql.*;
2. It also provides a standard to connect a database to a client application.
3. JDBC Driver manager: It loads a database-specific driver in an application to establish
a connection with a database. It is used to make a database-specific call to the database to
process the user request.
4. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation)
being performed by JDBC Drivers.
5. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge
translates the JDBC method call to the ODBC function call. It makes use of
the sun.jdbc.odbc package which includes a native library to access ODBC characteristics.
Architecture of JDBC
The JDBC architecture consists of two-tier and three-tier processing models to access a
database. They are as described below:
2. Three-tier model: In this, the user’s queries are sent to middle-tier services,
from which the commands are again sent to the data source. The results are sent
back to the middle tier, and from there to the user.
This type of model is found very useful by management information system
directors.
Interfaces of JDBC API
A list of popular interfaces of JDBC API is given below:
Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
Classes of JDBC API
A list of popular classes of JDBC API is given below:
DriverManager class
Blob class
Clob class
Types class
Working of JDBC
Java application that needs to communicate with the database has to be programmed using
JDBC API. JDBC Driver supporting data sources such as Oracle and SQL server has to be
added in java application for JDBC support which can be done dynamically at run time.
This JDBC driver intelligently communicates the respective data source.
Creating a simple JDBC application
package com.vinayak.jdbc;
import java.sql.*;
// Obtain a connection
Connection con = DriverManager.getConnection(
url, username, password);
// Obtain a statement
Statement st = con.createStatement();
The above example demonstrates the basic steps to access a database using JDBC. The
application uses the JDBC-ODBC bridge driver to connect to the database. You must
import java.sql package to provide basic SQL functionality and use the classes of the
package.
JDBC Statement:
JDBC ResultSet:
java.sql.ResultSet also an interface and is used to retrieve SQL select query results. A
ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is
positioned before the first row. The next method moves the cursor to the next row, and
because it returns false when there are no more rows in the ResultSet object, it can be used in
a while loop to iterate through the result set. It provides getXXX() methods to get data from
each iteration. Here XXX represents datatypes.
The statement interface is used to create SQL basic statements in Java it provides methods
to execute queries with the database. There are different types of statements that are used in
JDBC as follows:
Create Statement
Prepared Statement
Callable Statement
1. Create a Statement: From the connection interface, you can create the object for this
interface. It is generally used for general–purpose access to databases and is useful while
using static SQL statements at runtime.
Syntax:
Statement statement = connection.createStatement();
boolean execute(String SQL): If the ResultSet object is retrieved, then it returns
true else false is returned. Is used to execute SQL DDL statements or for
dynamic SQL.
int executeUpdate(String SQL): Returns number of rows that are affected by
the execution of the statement, used when you need a number for INSERT,
DELETE or UPDATE statements.
ResultSet executeQuery(String SQL): Returns a ResultSet object. Used
similarly as SELECT is used in SQL.
import java.sql.*;
// Class
class GFG {
2. Prepared Statement represents a recompiled SQL statement, that can be executed many
times. This accepts parameterized SQL queries. In this, “?” is used instead of the parameter,
one can pass the parameter dynamically by using the methods of PREPARED
STATEMENT at run time.
Illustration:
Considering in the people database if there is a need to INSERT some values, SQL
statements such as these are used:
INSERT INTO people VALUES ("Ayan",25);
INSERT INTO people VALUES("Kriya",32);
To do the same in Java, one may use Prepared Statements and set the values in the ?
holders, setXXX() of a prepared statement is used as shown:
String query = "INSERT INTO people(name, age)VALUES(?, ?)";
Statement pstmt = con.prepareStatement(query);
pstmt.setString(1,"Ayan");
ptstmt.setInt(2,25);
// where pstmt is an object name
execute(): This returns a boolean value and executes a static SQL statement that
is present in the prepared statement object.
executeQuery(): Returns a ResultSet from the current prepared statement.
executeUpdate(): Returns the number of rows affected by the DML statements
such as INSERT, DELETE, and more that is present in the current Prepared
Statement.
import java.sql.*;
// Importing Scanner class to
// take input from the user
import java.util.Scanner;
// Main class
class GFG {
3. Callable Statement are stored procedures which are a group of statements that we
compile in the database for some task, they are beneficial when we are dealing with
multiple tables with complex scenario & rather than sending multiple queries to the
database, we can send the required data to the stored procedure & lower the logic executed
in the database server itself. The Callable Statement interface provided by JDBC API helps
in executing stored procedures.
Syntax: To prepare a CallableStatement
import java.sql.*;
// Main class
class GFG {
CallableStatement cs
= con.prepareCall("{call peopleinfo(?,?)}");
cs.setString(1, "Bob");
cs.setInt(2, 64);
cs.execute();
ResultSet result
= s.executeQuery("select * from people");
The SQL statements that read data from a database query, return the data in a result set. The
SELECT statement is the standard way to select rows from a database and view them in a
result set. The java.sql.ResultSet interface represents the result set of a database query.
A ResultSet object maintains a cursor that points to the current row in the result set. The term
"result set" refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories −
Navigational methods − Used to move the cursor around.
Get methods − Used to view the data in the columns of the current row being
pointed by the cursor.
Update methods − Used to update the data in the columns of the current row.
The updates can then be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are
designated when the corresponding Statement that generates the ResultSet is created.
JDBC provides the following connection methods to create statements with desired ResultSet
−
createStatement(int RSType, int RSConcurrency);
prepareStatement(String SQL, int RSType, int RSConcurrency);
prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicates the type of a ResultSet object and the second argument is one of
two ResultSet constants for specifying whether a result set is read-only or updatable.
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.
Type Description
Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type,
you will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
// Move cursor to the first row.
// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Viewing a Result Set
The ResultSet interface contains dozens of methods for getting the data of the current row.
There is a get method for each of the possible data types, and each get method has two
versions −
One that takes in a column name.
One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one
of the getInt() methods of ResultSet −
Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive
types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL.
There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for more
information about using these SQL data types.
Updating a Result Set
The ResultSet interface contains a collection of update methods for updating the data of a
result set.
As with the get methods, there are two update methods for each data type −
One that takes in a column name.
One that takes in a column index.
For example, to update a String column of the current row of a result set, you would use one
of the following updateString() methods −
There are update methods for the eight primitive data types, as well as String, Object, URL,
and the SQL data types in the java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet
object, but not in the underlying database. To update your changes to the row in the database,
you need to invoke one of the following methods.