0% found this document useful (0 votes)
2 views37 pages

Java Unit 5 Notes

The document provides an overview of the Spring Framework and Spring Boot, covering key concepts such as Dependency Injection, Inversion of Control, and Aspect-Oriented Programming. It discusses the advantages of Spring, including its lightweight nature, loose coupling, and fast development capabilities, as well as various bean scopes and autowiring features. Additionally, it highlights the use of annotations in Spring for configuration and metadata purposes.

Uploaded by

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

Java Unit 5 Notes

The document provides an overview of the Spring Framework and Spring Boot, covering key concepts such as Dependency Injection, Inversion of Control, and Aspect-Oriented Programming. It discusses the advantages of Spring, including its lightweight nature, loose coupling, and fast development capabilities, as well as various bean scopes and autowiring features. Additionally, it highlights the use of annotations in Spring for configuration and metadata purposes.

Uploaded by

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

Spring Boot:

Spring Framework: Spring Core Basics-Spring Dependency Injection concepts, Spring Inversion of

Control, AOP, Bean Scopes- Singleton, Prototype, Request, Session, Application, Web Socket, Auto

wiring, Annotations, Life Cycle Call backs, Bean Configuration styles.

Spring Boot: Spring Boot Build Systems, Spring Boot Code Structure, Spring Boot Runners, Logger,

BUILDING RESTFUL WEB SERVICES, Rest Controller, Request Mapping, Request Body, Path

Variable, Request Parameter, GET, POST, PUT, DELETE APIs, Build Web Applications.

LECTURE-1

Java Framework is the body or platform of pre-written codes used by Java developers to develop Java
applications or web applications. In other words, Java Framework is a collection of predefined classes
and functions that is used to process input, manage hardware devices interacts with system software.
It acts like a skeleton that helps the developer to develop an application by writing their own code.

It was developed by Rod Johnson in 2003. Spring framework makes the easy development of JavaEE
application.

It is helpful for beginners and experienced persons.

Spring Framework
Spring is a lightweight framework. It can be thought of as a framework of frameworks because it
provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. The
framework, in broader sense, can be defined as a structure where we find solution of the various
technical problems.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC
etc. We will learn these modules in next page. Let's understand the IOC and Dependency Injection first.

Advantages of Spring Framework


There are many advantages of Spring Framework. They are as follows:
1) Predefined Templates

Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no need
to write too much code. It hides the basic steps of these technologies.

Let's take the example of JdbcTemplate, you don't need to write the code for exception handling,
creating connection, creating statement, committing transaction, closing connection etc. You need to
write the code of executing query only. Thus, it save a lot of JDBC code.

2) Loose Coupling

The Spring applications are loosely coupled because of dependency injection.

3) Easy to test

The Dependency Injection makes easier to test the application. The EJB or Struts application require
server to run the application but Spring framework doesn't require server.

4) Lightweight

Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't
force the programmer to inherit any class or implement any interface. That is why it is said non-invasive.

5) Fast Development

The Dependency Injection feature of Spring Framework and it support to various frameworks makes
the easy development of JavaEE application.

6) Powerful abstraction

It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.

7) Declarative support

It provides declarative support for caching, validation, transactions and formatting.

Spring - Dependency Injection

Every Java-based application has a few objects that work together to present what the end-user sees
as a working application. When writing a complex Java application, application classes should be
as independent as possible of other Java classes to increase the possibility to reuse these classes and
to test them independently of other classes while unit testing. Dependency Injection (or sometime
called wiring) helps in gluing these classes together and at the same time keeping them
independent.

Consider you have an application which has a text editor component and you want to provide a
spell check. Your standard code would look something like this −

public class TextEditor {


private SpellChecker spellChecker;

public TextEditor() {
spellChecker = new SpellChecker();
}

What we've done here is, create a dependency between the TextEditor and the
SpellChecker. In an inversion of control scenario, we would instead do
something like this −

public class TextEditor {


private SpellChecker spellChecker;

public TextEditor(SpellChecker spellChecker) {


this.spellChecker = spellChecker;
}
}

Here, the TextEditor should not worry about SpellChecker implementation. The
SpellChecker will be implemented independently and will be provided to the
TextEditor at the time of TextEditor instantiation. This entire procedure is
controlled by the Spring Framework.

Here, we have removed total control from the TextEditor and kept it
somewhere else (i.e. XML configuration file) and the dependency (i.e. class
SpellChecker) is being injected into the class TextEditor through a Class
Constructor. Thus the flow of control has been "inverted" by Dependency
Injection (DI) because you have effectively delegated dependances to some
external system.

The second method of injecting dependency is through Setter Methods of the


TextEditor class where we will create a SpellChecker instance. This instance
will be used to call setter methods to initialize TextEditor's properties.
Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control).
The Spring-Core module is responsible for injecting dependencies through either
Constructor or Setter methods. The design principle of Inversion of Control emphasizes
keeping the Java classes independent of each other and the container frees them from
object creation and maintenance. These classes, managed by Spring, must adhere to the
standard definition of Java-Bean. Dependency Injection in Spring also ensures loose
coupling between the classes. There are two types of Spring Dependency Injection.

1.Constructor-based dependency injection


Constructor-based DI is accomplished when the container
invokes a class constructor with a number of arguments, each
representing a dependency on the other class.
2.Setter-based dependency injection
Setter-based DI is accomplished by the container calling setter
methods on your beans after invoking a no-argument constructor
or no-argument static factory method to instantiate your bean.

You can mix both, Constructor-based and Setter-based DI but it is a good rule
of thumb to use constructor arguments for mandatory dependencies and
setters for optional dependencies.

The code is cleaner with the DI principle and decoupling is more effective when
objects are provided with their dependencies. The object does not look up its
dependencies and does not know the location or class of the dependencies,
rather everything is taken care by the Spring Framework.
LECTURE-2

Spring IoC (Inversion of Control)

Inversion of Control is a principle in software engineering which transfers the control of objects or
portions of a program to a container or framework. We most often use it in the context of object-
oriented programming.

Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the
objects, configures and assembles their dependencies, manages their entire life cycle. The
Container uses Dependency Injection(DI) to manage the components that make up the
application. It gets the information about the objects from a configuration file(XML) or Java
Code or Java Annotations and Java POJO class. These objects are called Beans. Since the
Controlling of Java objects and their lifecycle is not done by the developers, hence the name
Inversion Of Control. The followings are some of the main features of Spring IoC,
• Creating Object for us,
• Managing our objects,
• Helping our application to be configurable,
• Managing dependencies

AOP in Spring Framework


Aspect oriented programming(AOP) as the name suggests uses aspects in programming.
It can be defined as the breaking of code into different modules, also known
as modularisation, where the aspect is the key unit of modularity. Aspects enable the
implementation of crosscutting concerns such as- transaction, logging not central to
business logic without cluttering the code core to its functionality. It does so by adding
additional behaviour that is the advice to the existing code. For example- Security is a
crosscutting concern, in many methods in an application security rules can be applied,
therefore repeating the code at every method, define the functionality in a common class
and control were to apply that functionality in the whole application.
Dominant Frameworks in AOP:
AOP includes programming methods and frameworks on which modularisation of code is
supported and implemented. Let’s have a look at

the three dominant frameworks in AOP:

• AspectJ: It is an extension for Java programming created at PARC research centre. It


uses Java like syntax and included IDE integrations for displaying crosscutting structure.
It has its own compiler and weaver, on using it enables the use of full AspectJ language.
• JBoss: It is an open source Java application server developed by JBoss, used for Java
development.
• Spring: It uses XML based configuration for implementing AOP, also it uses annotations
which are interpreted by using a library supplied by AspectJ for parsing and matching.
Currently, AspectJ libraries with Spring framework are dominant in the market, therefore
let’s have an understanding of how Aspect-oriented programming works with Spring.

How Aspect-Oriented Programming works with Spring:


One may think that invoking a method will automatically implement cross-cutting concerns
but that is not the case. Just invocation of the method does not invoke the advice(the job
which is meant to be done). Spring uses proxy based mechanism i.e. it creates a proxy
Object which will wrap around the original object and will take up the advice which is
relevant to the method call. Proxy objects can be created either manually through proxy
factory bean or through auto proxy configuration in the XML file and get destroyed when the
execution completes. Proxy objects are used to enrich the Original behaviour of the real
object.

A cross-cutting concern is a concern that can affect the whole application and should be centralized
in one location in code as possible, such as transaction management, authentication, logging, security
etc.

Common terminologies in AOP:


1. Aspect: The class which implements the JEE application cross-cutting concerns(transaction, logger
etc) is known as the aspect. It can be normal class configured through XML configuration or
through regular classes annotated with @Aspect.
2. Weaving: The process of linking Aspects with an Advised Object. It can be done at load
time, compile time or at runtime time. Spring AOP does weaving at runtime.
Let’s write our first aspect class but before that have a look at the jars required and the
Bean configuration file for AOP.

BEAN SCOPE
Bean Definition: In Spring, the objects that form the backbone of your application and that
are managed by the Spring IoC container are called beans. A bean is an object that is
instantiated, assembled, and otherwise managed by a Spring IoC container.
Bean Scopes refers to the lifecycle of Bean that means when the object of Bean will be
instantiated, how long does that object live, and how many objects will be created for that
bean throughout. Basically, it controls the instance creation of the bean and it is managed
by the spring container.

The following are the different scopes provided for a bean:

1. Singleton: Only one instance will be created for a single bean definition per Spring IoC
container and the same object will be shared for each request made for that bean.
2. Prototype: A new instance will be created for a single bean definition every time a
request is made for that bean.
3. Request: A new instance will be created for a single bean definition every time an HTTP
request is made for that bean. But Only valid in the context of a web-aware Spring
ApplicationContext.
4. Session: Scopes a single bean definition to the lifecycle of an HTTP Session. But Only
valid in the context of a web-aware Spring ApplicationContext.
5. Global-Session: Scopes a single bean definition to the lifecycle of a global HTTP
Session. It is also only valid in the context of a web-aware Spring ApplicationContext.
Singleton Scope:

If the scope is a singleton, then only one instance of that bean will be instantiated per Spring
IoC container and the same instance will be shared for each request. That is when the
scope of a bean is declared singleton, then whenever a new request is made for that bean,
spring IOC container first checks whether an instance of that bean is already created or not.
If it is already created, then the IOC container returns the same instance otherwise it creates
a new instance of that bean only at the first request. By default, the scope of a bean is a
singleton.

Prototype Scope:

If the scope is declared prototype, then spring IOC container will create a new instance of
that bean every time a request is made for that specific bean. A request can be made to the
bean instance either programmatically using getBean() method or by XML for Dependency
Injection of secondary type. Generally, we use the prototype scope for all beans that are
stateful, while the singleton scope is used for the stateless beans.

Request Scope
In request scope, container creates a new instance for each and every HTTP request. So, if
the server is currently handling 50 requests, then the container can have at most 50
individual instances of the bean class. Any state change to one instance, will not be visible
to other instances. A bean instance is destructed as soon as the request is completed.

Session Scope
In session scope, the application context creates a new instance for each and every HTTP
session. So, if the server has 20 active sessions, then the container can have at most 20
individual instances of the bean class. All HTTP requests within a single session lifetime will
have access to the same single bean instance in that session scope.

Any state change to one instance will not be visible to other instances. An instance is
destructed as soon as the session ends.
Application Scope
In application scope, the container creates one instance per web application runtime. It is
almost similar to singleton scope with only two differences i.e.

1. The application scoped bean is singleton per ServletContext,


whereas singleton scoped bean is singleton per ApplicationContext. Please note
that there can be multiple application contexts within a single application.

2. The application scoped bean is visible as a ServletContext attribute.

WebSocket Scope
The WebSocket Protocol enables two-way communication between a client and a remote
host that has opted-in to communicate with the client. WebSocket Protocol provides a
single TCP connection for traffic in both directions. This is especially useful for multi-user
applications with simultaneous editing and multi-user games.

In this type of web application, HTTP is used only for the initial handshake. The server can
respond with HTTP status 101 (switching protocols) if it agrees – to the handshake request.
If the handshake succeeds, the TCP socket remains open, and both the client and server
can use it to send messages to each other.

When first accessed, WebSocket scoped beans are stored in the WebSocket session
attributes. The same bean instance is then returned during the entire WebSocket session.

Please note that websocket scoped beans are typically singleton and live longer than any
individual WebSocket session.

LECTURE-3
Autowiring in Spring
Autowiring in the Spring framework can inject dependencies automatically. The Spring
container detects those dependencies specified in the configuration file and the relationship
between the beans. This is referred to as Autowiring in Spring. To enable Autowiring in
the Spring application we should use @Autowired annotation. Autowiring in Spring internally
uses constructor injection. An autowired application requires fewer lines of code
comparatively but at the same time, it provides very little flexibility to the programmer.
Modes of Autowiring
Modes Description

This mode tells the framework that auto wiring is not supposed to
No
be done. It is the default mode used by Spring.

byName It uses the name of the bean for injecting dependencies.

byType It injects the dependency according to the type of bean.

Constructor It injects the required dependencies by invoking the constructor.

Autodetect The autodetect mode uses two other

Advantage of Autowiring
It requires the less code because we don't need to write the code to inject the dependency explicitly.

Disadvantage of Autowiring
No control of programmer.

Annotations
Annotations are a form of metadata that provides data about a program. Annotations are
used to provide supplemental information about a program. It does not have a direct effect
on the operation of the code they annotate. It does not change the action of the compiled
program. So in this article, we are going to discuss what are the main types of annotation
that are available in the spring framework with some examples.

Use of java annotations


Java annotations are mainly used for the following:

• Compiler instructions
• Build-time instructions
• Runtime instructions
Compiler instructions: Java provides the 3 in built annotations which are used
to give certain instructions to the compiler. Java in built annotation are
@Deprecated, @Override & @SuppressWarnings.

Build-time instructions: Java annotations can be used for build time or compile
time instructions. These instructions can be used by the build tools for generating
source code, compiling the source, generating XML files, packaging the compiled
code and files into a JAR file etc.

Runtime instructions: Normally, Java annotations are not present in your Java
code after compilation. However, we can define our own annotations that can be
available at runtime. These annotations can be accessed using Java Reflection.

Java annotations basics:


A java annotation always starts with the symbol @ and followed by the
annotation name. The @symbol signals the compiler that this is an annotation.

Syntax:

@AnnotationName
Example:

@Entity
Here @ symbol signals the compiler that this is an annotation and the Entity is
the name of this annotation.An annotation can contain zero, one or multiple
elements. We have to set values for these elements. Example:

@Entity(tableName = "USERS")

Where we can use annotations?


We can use java annotations above classes, interfaces, methods, fields and local
variables. Here is an example annotation added above a class definition:

@Entity
public class Users {
}

Spring Bean Life Cycle and Callbacks


The lifecycle of any object means when & how it is born, how it behaves throughout its life,
and when & how it dies. Similarly, the bean life cycle refers to when & how the bean is
instantiated, what action it performs until it lives, and when & how it is destroyed. In this article,
we will discuss the life cycle of the bean.
Bean life cycle is managed by the spring container. When we run the program then, first of
all, the spring container gets started. After that, the container creates the instance of a bean
as per the request, and then dependencies are injected. And finally, the bean is destroyed
when the spring container is closed. Therefore, if we want to execute some code on the bean
instantiation and just after closing the spring container, then we can write that code inside the
custom init() method and the destroy() method.
The following image shows the process flow of the bean life cycle.

Bean Life Cycle Process Flow

Note: We can choose a custom


method name instead
of init() and destroy(). Here, we will use init() method to execute all its code as the spring
container starts up and the bean is instantiated, and destroy() method to execute all its code
on closing the container.

1. Spring bean life cycle involves initialization and destruction callbacks and Spring bean
aware classes.
2. Initialization callback methods execute after dependency injection is completed.
Their purposes are to check the values that have been set in bean properties, perform
any custom initialization or provide a wrapper on original bean etc. Once the
initialization callbacks are completed, bean is ready to be used.
3. When IoC container is about to remove bean, destruction callback methods
execute. Their purposes are to release the resources held by bean or to perform any
other finalization tasks.
4. When more than one initialization and destructions callback methods have been
implemented by bean, then those methods execute in certain order.

SPRING CONFIGURATION STYLE


Spring Framework provides three ways to configure beans to be used in the application.

1. Annotation Based Configuration - By using @Service or @Component annotations. Scope


details can be provided with @Scope annotation.
2. XML Based Configuration - By creating Spring Configuration XML file to configure the
beans. If you are using Spring MVC framework, the xml based configuration can be loaded
automatically by writing some boiler plate code in web.xml file.
3. Java Based Configuration - Starting from Spring 3.0, we can configure Spring beans using java
programs. Some important annotations used for java based configuration
are @Configuration, @ComponentScan and @Bean.

LECTURE-4
Spring Boot

Spring Boot is most commonly used and contains all Spring Framework
features. Nowadays Spring Boot is becoming the best choice for Java developers
to build rapid Spring applications. When Java Developers use Spring Boot for
developing applications then they will focus on the logic instead of struggling with
the configuration setup environment of the application.

In Spring Boot, choosing a build system is an important task. We recommend


Maven or Gradle as they provide a good support for dependency management.
Spring does not support well other build systems.

Dependency Management
Spring Boot team provides a list of dependencies to support the Spring Boot
version for its every release. You do not need to provide a version for
dependencies in the build configuration file. Spring Boot automatically
configures the dependencies version based on the release. Remember that
when you upgrade the Spring Boot version, dependencies also will upgrade
automatically.

Note − If you want to specify the version for dependency, you can specify it in
your configuration file. However, the Spring Boot team highly recommends
that it is not needed to specify the version for dependency.

Maven Dependency
For Maven configuration, we should inherit the Spring Boot Starter parent
project to manage the Spring Boot Starters dependencies.

We should specify the version number for Spring Boot Parent Starter
dependency. Then for other starter dependencies, we do not need to specify
the Spring Boot version number.

Gradle Dependency
We can import the Spring Boot Starters dependencies directly
into build.gradle file. We do not need Spring Boot start Parent dependency like
Maven for Gradle.

SPRING BOOT CODE STRUCTURE

Spring Boot does not have any code layout to work with. However, there are
some best practices that will help us. This chapter talks about them in detail.
Default package
A class that does not have any package declaration is considered as a default
package. Note that generally a default package declaration is not
recommended. Spring Boot will cause issues such as malfunctioning of Auto
Configuration or Component Scan, when you use default package.

Note − Java's recommended naming convention for package declaration is


reversed domain name.

Spring Boot - Runners


Application Runner and Command Line Runner interfaces lets you to execute
the code after the Spring Boot application is started. You can use these
interfaces to perform any actions immediately after the application has
started. This chapter talks about them in detail.

Application Runner
Application Runner is an interface used to execute the code after the Spring
Boot application started.

Command Line Runner


Command Line Runner is an interface. It is used to execute the code after the
Spring Boot application started.

LOGGER
Logging in Spring Boot plays a vital role in Spring Boot applications for recording information,
actions, and events within the app. It is also used for monitoring the performance of an application,
understanding the behavior of the application, and recognizing the issues within the application. Spring
Boot offers flexible logging capabilities by providing various logging frameworks and also provides
ways to manage and configure the logs.
Why to use Spring Boot – Logging?
A good logging infrastructure is necessary for any software project as it not only helps in
understanding what’s going on with the application but also to trace any unusual incident or error
present in the project. This article covers several ways in which logging can be enabled in a spring boot
project through easy and simple configurations. Let’s first do the initial setup to explore each option in
more depth.
Elements of Logging Framework
• Logger: It captures the messages.
• Formatter: It formats the messages which are captured by loggers.
• Handler: It prints messages on the console, stores them in a file or sends an email, etc.
Java provides several logging frameworks, some of which are:
1. Logback Configuration logging
2. Log4j2 Configuration logging

Introduction to RESTful Web Services


REST stands for REpresentational State Transfer. It is developed by Roy Thomas Fielding, who also
developed HTTP. The main goal of RESTful web services is to make web services more effective. RESTful
web services try to define services using the different concepts that are already present in HTTP. REST
is an architectural approach, not a protocol.

It does not define the standard message exchange format. We can build REST services with both XML
and JSON. JSON is more popular format with REST. The key abstraction is a resource in REST. A
resource can be anything. It can be accessed through a Uniform Resource Identifier (URI). For
example:

The resource has representations like XML, HTML, and JSON. The current state capture by
representational resource. When we request a resource, we provide the representation of the resource.
The important methods of HTTP are:

o GET: It reads a resource.


o PUT: It updates an existing resource.
o POST: It creates a new resource.
o DELETE: It deletes the resource.

For example, if we want to perform the following actions in the social media application, we get the
corresponding results.

POST /users: It creates a user.

GET /users/{id}: It retrieves the detail of a user.


GET /users: It retrieves the detail of all users.

DELETE /users: It deletes all users.

DELETE /users/{id}: It deletes a user.

GET /users/{id}/posts/post_id: It retrieve the detail of a specific post.

POST / users/{id}/ posts: It creates a post of the user.

Further, we will implement these URI in our project.

HTTP also defines the following standard status code:

o 404: RESOURCE NOT FOUND


o 200: SUCCESS
o 201: CREATED
o 401: UNAUTHORIZED
o 500: SERVER ERROR

RESTful Service Constraints


o There must be a service producer and service consumer.
o The service is stateless.
o The service result must be cacheable.
o The interface is uniform and exposing resources.
o The service should assume a layered architecture.

Advantages of RESTful web services


o RESTful web services are platform-independent.
o It can be written in any programming language and can be executed on any platform.
o It provides different data format like JSON, text, HTML, and XML.
o It is fast in comparison to SOAP because there is no strict specification like SOAP.
o These are reusable.
o They are language neutral.

Lecture-7
Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring
RestController takes care of mapping request data to the defined request handler method. Once
response body is generated from the handler method, it converts it to JSON or XML response.3 Aug
2022
RestController: RestController is used for making restful web services with the help of the
@RestController annotation. This annotation is used at the class level and allows the class to handle
the requests made by the client. Let’s understand @RestController annotation using an example. The
RestController allows to handle all REST APIs such as GET, POST, Delete, PUT requests.
RestController is very useful when we are working on a real-time REST API
Spring Application. This Rest Controller class gives us JSON(JavaScript Object
Notation) response as the output. The normal class is annotated with
“@RestController” then that class is treated as Rest Controller class in the class.

Difference between @Controller and @RestController:


@Controller
@ResponseBody
class TestController{
----------------
----------------
}@RestController
class TestController{
----------------
----------------
}

A normal class annotated with “@Controller” then that class is treated as a


Controller class in Spring MVC.

Spring 2.5 introduced the @Controller annotation used for web application return
as a view in Spring MVC. This is the specialization of the “@Component”
annotation.

In @Controller we need to use @ReponseBody in every handler method for


response output without a view.

Spring 4.0 introduced the “@RestController” for the creation of the Restful web
services in the Spring Framework in a simple manner. It is a specialization of the
“@Controller” annotation.
In the “@RestController” annotation, we don’t need to use the “@ResponseBody”
annotation in the handler method. In this “@RestController” we cannot return a
view as output.

In this Project, we can use “@RestController” and “@GetMapping” annotations in


the POJO class.

@RestController: This combination of these annotations “@Controller” and


“@ResponseBody”.This will be used when we are making Rest Apis.

@GetMapping: It will handle requests from HTTP Get Method (Client).

Development Process:
1. Keep eclipse IDE ready
2. Create the Spring Boot Starter Project for this example of the RestController in
the Spring Boot(Select Spring Web dependency)
3. Create RestController class
4. Run the Project

Lecture-6

When building robust APIs, understanding and appropriately utilizing the HTTP methods GET, POST, PUT, and
DELETE is essential. Each method serves a specific purpose and has its own limitations. In this article, we will
explore these HTTP methods, their characteristics, and discuss their limitations in the context of building robust
APIs. Additionally, we will provide Java code examples to demonstrate their usage.

What Are HTTP Methods and Why Are They Important?


HTTP methods, also known as HTTP verbs, are a set of standardized actions that can be performed on a resource
using the Hypertext Transfer Protocol (HTTP). These methods define the intended operation to be performed on the
resource and provide a uniform way of interacting with web servers. The most commonly used HTTP methods are
GET, POST, PUT, and DELETE, but there are other methods as well, such as PATCH, HEAD, and OPTIONS.

HTTP methods are important for several reasons:

1. Resource Manipulation: HTTP methods allow clients to perform various operations on resources, such as
retrieving data, submitting data, updating data, or deleting data. Each method represents a specific action that
can be taken on a resource, enabling a wide range of interactions between clients and servers.
2. Uniform Interface: HTTP methods provide a uniform interface for interacting with web resources. By
adhering to the standard set of methods, clients and servers can communicate effectively, regardless of the
underlying technologies or platforms being used. This promotes interoperability and simplifies the
development and integration of web applications.
3. Intent and Semantics: Each HTTP method carries a specific intent and semantic meaning, making it easier
for developers to understand the purpose of an API endpoint by looking at the method used. For example, a
GET request is used to retrieve data, while a POST request is used to submit data for processing or storage.
By selecting the appropriate method, developers can convey the intended operation more accurately.
4. Idempotence and Safety: HTTP methods have different characteristics regarding idempotence and safety.
Idempotence means that making multiple identical requests should have the same outcome. Safe methods,
such as GET, should not cause any modifications or side effects on the server. Understanding these
characteristics helps developers design APIs that adhere to the expected behavior and minimize unintended
side effects or data inconsistencies.
5. RESTful Architecture: HTTP methods play a fundamental role in building RESTful APIs (Representational
State Transfer). REST is an architectural style that leverages HTTP methods to provide a scalable and flexible
approach to designing web services. Each resource in a RESTful API is typically associated with a specific
URL, and the appropriate HTTP method is used to interact with that resource.

By understanding and utilizing the appropriate HTTP methods, developers can build robust and well-designed APIs
that adhere to the principles of HTTP and REST. This ensures consistency, interoperability, and efficiency in the
communication between clients and servers.

Below we will elaborate more on the most commonly used HTTP methods.

GET Method:
The GET method is one of the fundamental HTTP methods used for retrieving data from a server. It is designed to
be safe, meaning it should not modify any data on the server. When using the GET method, the client requests a
representation of a resource from the server.
Here are some key points to consider when working with the GET method in API development:

1. Retrieving Data: The primary purpose of the GET method is to retrieve data from the server. It is
commonly used to fetch resources such as user profiles, product information, blog articles, and more. The
client sends a GET request to a specific URL, and the server responds with the requested data.
2. Request Parameters: GET requests can include parameters in the URL to provide additional information to
the server. These parameters are appended to the URL as query parameters, typically in the form of key-
value pairs. For example, a GET request to retrieve user information for a specific ID could look like: GET
/users?id=123. The server can use these parameters to filter or modify the returned data accordingly.
3. Idempotence: The GET method is considered idempotent, meaning that multiple identical GET requests
should have the same outcome. It implies that making multiple GET requests for the same resource should
not result in any unintended side effects or modifications on the server. It allows caching mechanisms to be
employed for efficient retrieval and reduces the risk of unintentional changes or inconsistencies.
4. Response Codes: The server responds to a GET request with an appropriate HTTP response code to indicate
the success or failure of the request. The most common response code is 200 (OK), indicating that the
request was successful, and the requested resource is returned in the response body. Other possible response
codes include 404 (Not Found) if the requested resource does not exist, or 500 (Internal Server Error) if there
was an error on the server while processing the request.
5. Limitations: While the GET method is crucial for retrieving data, it has certain limitations to consider:
o Data Length: GET requests have limitations on the length of the URL. Excessive data in the URL can
result in truncation, errors, or security vulnerabilities. It is recommended to keep the data size within
reasonable limits and consider alternative methods (e.g., POST) for large payloads.
o Security Considerations: Since GET requests expose the data in the URL, it is important to avoid
including sensitive information like passwords or authentication tokens in the query parameters. Instead,
consider using other secure methods such as headers or request bodies for transmitting sensitive data.
Java Code Example:

01 import java.net.HttpURLConnection;
import java.net.URL;
02 import java.io.BufferedReader;
03 import java.io.InputStreamReader;
04
05 public class GetExample {
06 public static void main(String[] args) {
07 try {
URL url = new URL("https://api.example.com/resource");
08 HttpURLConnection connection = (HttpURLConnection)
09 url.openConnection();
10 connection.setRequestMethod("GET");
11
12 int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
13 BufferedReader reader =
14 new BufferedReader(new
15 InputStreamReader(connection.getInputStream()));
16 String line;
17 StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
18 response.append(line);
19 }
20 reader.close();
21 System.out.println("Response: " + response.toString());
} else {
22 System.out.println("Error: " + responseCode);
23 }
24 connection.disconnect();
25 } catch (Exception e) {
26 e.printStackTrace();
}
27 }
28 }
29
30
31
In the given Java code example, the GET request is sent to https://api.example.com/resource. The response
from the server is then read and stored in a StringBuilder for further processing. If the response code is 200
(HTTP_OK), the response is printed to the console.

while the GET method is efficient for retrieving data, it should not be used for operations that modify the
server state. For such operations, other HTTP methods like POST, PUT, or DELETE should be employed.

POST Method:
The POST method is one of the HTTP methods used for submitting data to be processed by the server.
Unlike the GET method, which is used for retrieving data, the POST method is intended for data
submission and can cause modifications on the server. Here are some important points to consider when
working with the POST method:

1. Submitting Data: The primary purpose of the POST method is to submit data to the server for
processing or storage. This data can be in various formats such as form data, JSON, XML, or binary
data. The POST request typically includes a request body that contains the data being sent to the
server.
2. Idempotence: Unlike the GET method, the POST method is generally considered non-idempotent.
This means that multiple identical POST requests may have different outcomes or effects on the
server. For example, submitting the same POST request multiple times may result in the creation of
multiple resources or duplicate entries.
3. Request Headers: POST requests often include specific headers to provide additional information
about the request or the format of the data being sent. For example, the “Content-Type” header
specifies the format of the data in the request body, such as “application/json” or “application/x-www-
form-urlencoded”.
4. Response Codes: Similar to other HTTP methods, the server responds to a POST request with an
appropriate HTTP response code to indicate the success or failure of the request. The common
response code for a successful POST request is 201 (Created), indicating that the resource has been
successfully created on the server. Other possible response codes include 200 (OK) for general success
or 400 (Bad Request) for invalid or malformed requests.
5. Limitations: While the POST method is commonly used for data submission, it also has some
limitations to consider:
o Lack of Idempotence: As mentioned earlier, the non-idempotent nature of the POST method
means that repeated identical requests may lead to unintended side effects. It is important to design
APIs in a way that handles duplicate submissions appropriately and ensures data integrity.
o Lack of Caching: By default, POST requests are typically not cacheable. Caching is important for
improving performance and reducing the load on the server. If caching is required for POST
requests, additional measures such as Cache-Control headers or server-side caching strategies need
to be implemented.
Java Code Example:

import java.net.HttpURLConnection;
01
import java.net.URL;
02
import java.io.DataOutputStream;
03
public
04 class PostExample {
05 public static void main(String[] args) {
try {
06 URL url = new URL("https://api.example.com/resource");
07 HttpURLConnection connection = (HttpURLConnection)
08 url.openConnection();
09 connection.setRequestMethod("POST");
connection.setDoOutput(true);
10
11 String postData = "data=example";
12 DataOutputStream outputStream = new
13 DataOutputStream(connection.getOutputStream());
14 outputStream.writeBytes(postData);
15 outputStream.flush();
outputStream.close();
16
17 int responseCode = connection.getResponseCode();
18 if (responseCode == HttpURLConnection.HTTP_OK) {
19 // Process response
20 } else {
// Handle error
21
}
22 connection.disconnect();
23 } catch (Exception e) {
24 e.printStackTrace();
25 }
}
26
}
In the provided Java code example, a POST request is sent to https://api.example.com/resource with
a request body containing the data to be submitted. The data is written to the request output stream and
the response code is checked to handle the response accordingly.
When using the POST method, it is crucial to ensure proper authentication, authorization, and input
validation to prevent security vulnerabilities and protect the integrity of the server and data.
Remember to use the appropriate HTTP method based on the intended operation. While the GET method
is used for retrieving data, the POST method is suitable for submitting data for processing or creating new
resources on the server.

PUT Method:
The PUT method is an HTTP method used for updating or replacing a resource on the server. It is
idempotent, meaning that multiple identical PUT requests should have the same outcome. Here are some
important points to consider when working with the PUT method:

1. Updating Resources: The primary purpose of the PUT method is to update an existing resource on
the server. It replaces the entire resource with the new representation provided in the request. The
PUT request typically includes a request body containing the updated data for the resource.
2. Idempotence: As mentioned earlier, the PUT method is idempotent. It means that making multiple
identical PUT requests should have the same outcome. This property allows for safe retries of failed
requests without causing unintended side effects or data inconsistencies.
3. Resource Identification: To update a specific resource, the client must provide the unique identifier
or URL of the resource in the PUT request. The server uses this information to locate the resource and
perform the update operation. It is crucial to ensure the accuracy and integrity of the resource
identification mechanism to prevent unintended modifications to unrelated resources.
4. Partial Updates: By default, the PUT method replaces the entire resource with the new
representation provided in the request body. However, in some cases, it may be desirable to perform
partial updates, modifying only specific fields or properties of the resource. While the HTTP
specification does not directly support partial updates with the PUT method, some APIs implement
custom conventions or use additional operations (e.g., PATCH) to achieve partial updates.
5. Response Codes: Similar to other HTTP methods, the server responds to a PUT request with an
appropriate HTTP response code to indicate the success or failure of the request. The common
response code for a successful PUT request is 200 (OK), indicating that the resource has been
successfully updated. Alternatively, if the resource does not exist and a new resource is created, the
response code may be 201 (Created).
6. Limitations: While the PUT method is commonly used for resource updates, it also has some
limitations to consider:
o Lack of Partial Updates: As mentioned earlier, the PUT method typically replaces the entire
resource rather than allowing partial updates to specific fields. If partial updates are required,
alternative approaches like PATCH or custom conventions can be considered.
o Security Considerations: It is essential to implement proper authentication, authorization, and
validation mechanisms to ensure that only authorized clients can update the resources. Additionally,
input validation should be performed to prevent invalid or malicious data from being stored.
Java Code Example:

01 import java.net.HttpURLConnection;
import java.net.URL;
02 import java.io.DataOutputStream;
03
04 public class PutExample {
05 public static void main(String[] args) {
try {
06 URL url = new URL("https://api.example.com/resource");
07 HttpURLConnection connection = (HttpURLConnection)
08 url.openConnection();
09 connection.setRequestMethod("PUT");
10 connection.setDoOutput(true);
11
String putData = "data=updated";
12 DataOutputStream outputStream = new
13 DataOutputStream(connection.getOutputStream());
14 outputStream.writeBytes(putData);
15 outputStream.flush();
16 outputStream.close();
17
int responseCode = connection.getResponseCode();
18 if (responseCode == HttpURLConnection.HTTP_OK) {
19 // Process response
20 } else {
21 // Handle error
}
22 connection.disconnect();
23 } catch (Exception e) {
24 e.printStackTrace();
25 }
26 }
}
27
28
29
30
In the provided Java code example, a PUT request is sent to https://api.example.com/resource with a
request body containing the updated data. The data is written to the request output stream, and the
response code is checked to handle the response accordingly.
When using the PUT method, it is important to handle concurrency and data consistency issues
appropriately. For example, you may use optimistic locking mechanisms or versioning to ensure that
updates do not conflict with other concurrent modifications to the resource.

Remember to use the appropriate HTTP method based on the intended operation. While the GET method
is used for retrieving data and the POST method is used for submitting data, the PUT method is suitable
for updating existing resources on the server.

DELETE Method:
The DELETE method is an HTTP method used for deleting a specified resource on the server. It is used to
remove a resource permanently from the server. Here are some important points to consider when
working with the DELETE method:
1. Deleting Resources: The primary purpose of the DELETE method is to delete a specific resource on
the server. The client sends a DELETE request to the server, specifying the URL or identifier of the
resource to be deleted.
2. Idempotence: Similar to the PUT method, the DELETE method is also idempotent. Multiple identical
DELETE requests should have the same outcome. Making repeated DELETE requests for the same
resource should not result in any unintended side effects or modifications on the server.
3. Resource Identification: To delete a specific resource, the client must provide the unique identifier
or URL of the resource in the DELETE request. The server uses this information to locate and remove
the corresponding resource. It is crucial to ensure the accuracy and integrity of the resource
identification mechanism to prevent accidental deletions of unrelated resources.
4. Response Codes: The server responds to a DELETE request with an appropriate HTTP response code
to indicate the success or failure of the request. The common response code for a successful DELETE
request is 204 (No Content), indicating that the resource has been successfully deleted. Alternatively, if
the resource does not exist, the response code may be 404 (Not Found).
5. Limitations: While the DELETE method is commonly used for resource deletion, it is important to
consider the following limitations:
o Lack of Safety: Unlike the GET method, which is considered safe and should not modify any data
on the server, the DELETE method performs irreversible actions. Once a resource is deleted, it
cannot be easily recovered. Therefore, it is crucial to implement appropriate authorization and
authentication mechanisms to ensure that only authorized clients can initiate DELETE requests.
o Cascading Deletions: In some cases, deleting a resource may have cascading effects on related
resources. For example, deleting a user may require deleting associated records such as posts or
comments. It is essential to define the behavior and potential cascading actions in your API’s design
and documentation.
Java Code Example:

01 import java.net.HttpURLConnection;
02 import java.net.URL;
03
public class DeleteExample {
04 public static void main(String[] args) {
05 try {
06 URL url = new URL("https://api.example.com/resource/123");
07 HttpURLConnection connection = (HttpURLConnection)
08 url.openConnection();
connection.setRequestMethod("DELETE");
09
10 int responseCode = connection.getResponseCode();
11 if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
12 // Resource deleted successfully
13 } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND)
{
14 // Resource not found
15 } else {
16 // Handle other errors
17 }
18 connection.disconnect();
} catch (Exception e) {
19 e.printStackTrace();
20 }
21 }
22 }
23
24
In the provided Java code example, a DELETE request is sent
to https://api.example.com/resource/123, where “123” represents the identifier of the resource to be
deleted. The response code is checked to handle the success or failure of the deletion operation.
When using the DELETE method, it is important to implement proper authorization and authentication
mechanisms to prevent unauthorized deletions. Additionally, consider providing proper error handling and
feedback to the client in case of failures or errors during the deletion process.

Remember to use the appropriate HTTP method based on the intended operation. While the GET method
is used for retrieving data, the POST method is used for submitting data, the PUT method is used for
updating data, the DELETE method is specifically designed for resource deletion.

Use Cases and Examples of HTTP Methods


Here are some common use cases and examples of the HTTP methods GET, POST, PUT, and DELETE:

GET:
• Use Case: Retrieving Data
• Description: The GET method is used to retrieve data from a specified resource on the server.
• Example: Fetching a user’s profile information from an API endpoint:
1 URL url = new URL("https://api.example.com/users/123");
2 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
3 connection.setRequestMethod("GET");
4
// Process the response
5
POST:
• Use Case: Submitting Data
• Description: The POST method is used to submit data to be processed or stored by the server.
• Example: Creating a new user by sending data in the request body:
URL url = new URL("https://api.example.com/users");
01 HttpURLConnection connection = (HttpURLConnection)
02 url.openConnection();
03 connection.setRequestMethod("POST");
04 connection.setDoOutput(true);
05
// Set the request body with user data
06 DataOutputStream outputStream = new
07 DataOutputStream(connection.getOutputStream());
08 String userData = "name=John&[email protected]";
09 outputStream.writeBytes(userData);
outputStream.flush();
10 outputStream.close();
11
12 // Process the response
13
PUT:
• Use Case: Updating Data
• Description: The PUT method is used to update or replace a specified resource on the server.
• Example: Updating a user’s information by sending the updated data in the request body:
01 URL url = new URL("https://api.example.com/users/123");
02 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
03 connection.setRequestMethod("PUT");
04 connection.setDoOutput(true);
05
06 // Set the request body with updated user data
DataOutputStream outputStream = new
07 DataOutputStream(connection.getOutputStream());
08 String updatedUserData = "name=John Smith&[email protected]";
09 outputStream.writeBytes(updatedUserData);
10 outputStream.flush();
outputStream.close();
11
12 // Process the response
13
DELETE:
• Use Case: Deleting Data
• Description: The DELETE method is used to delete a specified resource from the server.
• Example: Deleting a user by sending a DELETE request to the corresponding API endpoint:
1 URL url = new URL("https://api.example.com/users/123");
2 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
3 connection.setRequestMethod("DELETE");
4
// Process the response
5
These examples demonstrate how the HTTP methods can be used in different scenarios to perform
common operations on resources. It’s important to note that these are just simplified examples, and in
real-world scenarios, you would typically handle error handling, authentication, and other considerations
to build robust and secure APIs.

Understanding the characteristics and limitations of the HTTP methods GET, POST, PUT, and DELETE is
crucial for building robust APIs. Each method serves a specific purpose and should be used appropriately
to ensure data integrity and consistent behavior. By leveraging these HTTP methods effectively,
developers can design APIs that are efficient, secure, and reliable.

RequestMapping
One of the most important annotations in spring is
the @RequestMapping Annotation which is used to map HTTP requests to handler
methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet
(Front Controller) is responsible for routing incoming HTTP requests to handler methods of
controllers. When configuring Spring MVC, you need to specify the mappings between the
requests and handler methods. To configure the mapping of web requests, we use
the @RequestMapping annotation. The @RequestMapping annotation can be applied to
class-level and/or method-level in a controller. The class-level annotation maps a specific
request path or pattern onto a controller. You can then apply additional method-level
annotations to make mappings more specific to handler methods. So let’s understand
@RequestMapping Annotation at Method-level and Class level by examples.
Requirements:
• Eclipse (EE version)/STS IDE
• Spring JAR Files
• Tomcat Apache latest version

@RequestMapping Annotation at Method-Level

Spring Boot is the most popular framework of Java for building enterprise-level web
applications and back-ends. Spring Boot has a handful of features that support quicker and
more efficient web app development. Some of them are Auto-configuration, Embedded
Server, opinionated defaults, and Annotation Support. In this article, we’ll be exploring the
core annotation of Spring Boot – @RequestMapping which is part of the set of
annotations that Spring Boot employs for defining URL endpoints and REST APIs.
@RequestMapping
This annotation is a versatile and flexible annotation that can be used with a controller
(class) as well as the methods to map specific web requests with the handler methods and
controllers. This annotation is part of a larger set of annotations provided by Spring
Framework to define URL endpoints and simplify the development of Spring Boot
applications.
It has the following features:
• Define several different endpoints to access a specific resource.
• Build REST APIs to serve web requests.
• Simplify the web development process by simply defining an annotation that offers a set
of functionalities for handling requests.
• Define multiple endpoints in a single @RequestMapping annotation.

What is Request Body?


Data sent over the request body can be of any format like json, XML, PDF, Http Forms, and many more.
The Content-Type header indicates the server's understanding type of request.
• Spring provides @RequestBody annotation to deserialize the incoming payload into java object or map.
• The request body goes along with content-type header for handler method to understand and deserialize
the payload.

How to Get the Body of Request in Spring Boot?


Java language is one of the most popular languages among all programming languages. There are
several advantages of using the Java programming language, whether for security purposes or building
large distribution projects. One of the advantages of using Java is that Java tries to connect every
concept in the language to the real world with the help of the concepts of classes, inheritance,
polymorphism, etc.
There are several other concepts present in Java that increase the user-friendly interaction between the
Java code and the programmer such as generic, Access specifiers, Annotations, etc. These features add
an extra property to the class as well as the method of the Java program. In this article, we will discuss
how to get the body of the incoming request in the spring boot.
@RequestBody: Annotation is used to get the request body in the incoming request.
Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring
Boot project. It also provides various features for the projects expressed in a metadata model. This
model allows us to configure the list of dependencies that are supported by JVM. Here, we will create
the structure of an application using a spring initializer and then use an IDE to create a sample GET
route. Therefore, to do this, the following steps are followed sequentially as follows:

@RequestBody Annotation in Spring and Spring Boot


The @RequestBody annotation is responsible for binding the HTTPRequest body to the body
of the web request. Depending on the content type of the request, the body of the request is
given through a HttpMessageConverter, which resolves the method argument.

We can also use the @Valid annotation to automatically validate the input.
In brief, the @RequestBody annotation is responsible for retrieving the request body and
automatically converting it to the Java object.

path variable in spring boot

The @PathVariable annotation is used to retrieve data from the URL path. By defining
placeholders in the request mapping URL, you can bind those placeholders to method
parameters annotated with @PathVariable. This allows you to access dynamic values
from the URL and use them in your code.

The @PathVariable annotation is used to retrieve data from the URL path. By defining
placeholders in the request mapping URL, you can bind those placeholders to method
parameters annotated with @PathVariable. This allows you to access dynamic values from
the URL and use them in your code.

Using @PathVariable
The @PathVariable annotation is used to extract data from the URL path. It allows you to
define placeholders in your request mapping URL and bind those placeholders to method
parameters. Let’s consider an example where you have a REST API endpoint for retrieving
a user’s details by their ID:
o RestController: RestController is used for making restful web services with the help
of the @RestController annotation. This annotation is used at the class level and
allows the class to handle the requests made by the client. Let’s understand
@RestController annotation using an example. The RestController allows to handle
all REST APIs such as GET, POST, Delete, PUT requests.
o Spring Initializr is a web-based tool using which we can easily generate the structure
of the Spring Boot project. It also provides various different features for the projects
expressed in a metadata model. This model allows us to configure the list of
dependencies that are supported by JVM. Here, we will create the structure of an
application using a spring initializer and then use an IDE to create a sample GET
route.
Lecture-7

How to build a Web Application Using Java


Java is one of the most used programming languages for developing dynamic web applications. A web
application is computer software that utilizes the web browser and technologies to perform tasks over the
internet. A web application is deployed on a web server.

Java provides some technologies like Servlet and JSP that allow us to develop and deploy a web application on
a server easily. It also provides some frameworks such as Spring, Spring Boot that simplify the work and
provide an efficient way to develop a web application. They reduce the effort of the developer.

We can create a website using static HTML pages and style them using CSS, but we need server-side
technology when we want to create a dynamic website.

In this section, we will see how to create a website using Java Servlets and HTML. Further, we will see how
these technologies are useful for developing a web application.

What is a Web Application


A web application is computer software that can be accessed using any web browser. Usually, the
frontend of a web application is created using the scripting languages such as HTML, CSS, and
JavaScript, supported by almost all web browsers. In contrast, the backend is created by any of the
programming languages such as Java, Python, Php, etc., and databases. Unlike the mobile application,
there is no specific tool for developing web applications; we can use any of the supported IDE for
developing the web application.

Web Server and Client


The web server is a process that handles the client's request and responds. It processes the request
made by the client by using the related protocols. The main function of the webserver is to store the
request and respond to them with web pages. It is a medium between client and server. For example,
Apache is a leading webserver.

A client is a software that allows users to request and assist them in communicating with the server. The
web browsers are the clients in a web application; some leading clients are Google Chrome, Firefox,
Safari, Internet Explorer, etc.
HTML and HTTP
The HTML stands for HyperText Markup Language; it is a common language for Web Server and Web
Client communication. Since both the web server and web client are two different software components
of the web, we need a language that communicates between them.

The HTTP stands for HyperText Transfer Protocol; it is a communication protocol between the client
and the server. It runs on top of the TCP/IP protocol.

Some of the integral components of an HTTP Request are as following:

HTTP Method: The HTTP method defines an action to be performed; usually, they are GET, POST, PUT,
etc.

URL: URL is a web address that is defined while developing a web application. It is used to access a
webpage.

Form Parameters: The form parameter is just like an argument in a Java method. It is passed to provide
the details such as user, password details on a login page.

What is URL
URL stands for Universal Resource Locator used to locate the server and resource. It is an address of a
web page. Every web page on a project must have a unique name.

A URL looks like as follows:

1. http://localhost:8080/SimpleWebApplication/

Where,

http or https: It is the starting point of the URL that specifies the protocol to be used for
communication.

Localhost: The localhost is the address of the server. When we run our application locally, it is called
localhost; if we deployed our project over the web, then it is accessed by using the domain name like
"javatpoint.com". The domain name maps the server to IP addresses.

8080: This is the port number for the local server; it is optional and may differ in different machines. If
we do not manually type the port number in the URL, then by default, the request goes to the default
port of the protocol. Usually, the port no between 0 to 1023 are reserved for some well-known services
such as HTTP, HTTPS, FTP, etc.
We have discussed all the major components of a web application. Let's move towards our main motive
How to build a web application in Java.

First, understand servlet:

What is Servlet
A Servlet is a Java program that runs within a web server; it receives the requests and responds to them
using related protocols (Usually HTTP). The Servlets are capable enough to respond to any type of
request; they are commonly used to make the application functional.

We can create a static website using only HTML and CSS, but when it comes to dynamic, we need a
server-side programming language. For these applications, Java provides Servlet technology, which
contains HTTP-specific servlet classes.

The javax.servlet and javax.servlet.http packages contain interfaces and classes for creating servlets.
All servlets should implement the Servlet interface, which defines life-cycle methods. To implement a
generic service, we can use the GenericServlet class by extending it. It
provides doGet and doPost methods to handle HTTP-specific services.

Why are the Servlets Useful?


Web servers are capable enough to serve static HTML requests, but they don't know how to deal with
dynamic requests and databases. So, we need a language for dynamic content; these languages are
PHP, Python, Java, Ruby on Rails, etc. In Java, there are two technologies Servlet and JSPs, that deals
with dynamic content and database. Java also provides frameworks such as Spring, Spring Boot,
Hibernate, and Struts to use the servlet and JSP easily.

The Servlets and JSPs are server-side technologies that extend the functionality of a web server. They
support dynamic response and data persistence. We can easily create a web application using these
technologies.

Let's create our first web applications:

First Web Application Using Java Servlet


To create a web application, we need the following tools:

Java

IDE ( Eclipse or Netbeans)

Database (Oracle or Mysql)


Server (Tomcat)

Before Creating any web application, ensure that all of the above tools are properly installed on your
system.

Now, follow the below steps to develop a web application:

Step1: Open Eclipse Create a Dynamic Web Project

Open the Eclipse IDE, navigate to File-> New-> Dynamic Web Project.

If the dynamic web project is not listed in your IDE, then go to the other option and search for it. Click
on it to continue.

Step2: Provide Project Name

Now, enter the project name and click Next to continue.

Follow the prompt and tick the generate web.xml deployment descriptor.

Now, our project is ready; the project structure will look as follows:

Step3: Create a Servlet

Now, create a servlet by right-clicking on the Java Resources/src folder. To create a servlet right click
on the src folder and navigate to the New-> Servlet menu. Here, provide the Servlet name:

Click on the Finish button. It will create a TestServlet as specified. You can choose any of your Servlet names.

Step4: Add the Servlet Jar file

We can see our Servlet is displaying lots of errors it is because we have not added the servlet-api jar
file yet. To add the jar file, right-click on the project and select the configuration option by navigating
to Build Path-> Configure Build Path option. Now, click on the Add External JARs option.

Navigate to the directory where you have installed your server and select the servlet-api.jar file.

Click Open to continue.


Now select Apply and Close option. It will add the jar file to our project.

Step5: Create a HTML or JSP file

Now, our first web application is almost ready. We can create HTML pages that we want to display on
our website.

To create an HTML page, right-click on the WebContent folder and select the New HTML file option
from the New-> HTML File menu with the name index.html.

Map the File

Now, map this file in the web.xml file. The web.xml is a deployment descriptor for the Servlet
applications. Since, Servlet 3.0, we can use annotations instead of the deployment descriptor.

We can also define our welcome file; a welcome file is the first file of the project that initiates the project,
also known as Home. We can define multiple welcome files.

Consider the below code:

From the above code, we can see by default the servlet defines several welcome files. If you want to use
any file other than the listed files, you can define that here.

Now, our first web application is ready.

Step7: Run the Application

To run the application, right-click on the project and run it on the server by selecting Run-> Run on
Server option.

It will take some time to load the application.

We can also test it on other browsers by entering the URL.

Now, we can design this by adding more web pages and styles.

In the above screen, we have updated our index.html file as follows:

Add the image file into WebContent fold

You might also like