Spring Boot by Nagoorbabu - Original
Spring Boot by Nagoorbabu - Original
Spring Boot by Nagoorbabu - Original
SPRING BOOT
BY
NAGOOR BABU
CONTACT US:
1
Page
SPRING BOOT:
Spring Boot is an open source Java-based framework developed by Pivotal Team.
--> Spring Boot makes it easy to create stand-alone, production-grade Spring based
Applications that you can "just run".
--> Spring Boot provides production-ready features such as metrics, health checks and
externalized configuration.
--> Spring Boot was designed on the top of existed Spring Framework to simplify and
speedup the spring based applications.
--> Spring Boot can be used to develop Spring based applications either by using JAVA or by
using Groovy.
--> Spring Boot Simplifies application development by having all configurations as defaults.
--> Spring Boot will provide very simple approach to integrate Spring Boot Application with
its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security etc.
CONTACT US:
2
Page
--> Spring Boot provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test
our web applications very easily.
--> Spring Boot provides CLI (Command Line Interface) tool to develop and test Spring Boot
Applications from command prompt very easily and quickly.
--> Spring Boot provides lots of plugins to develop and test Spring Boot Applications very
easily using Build Tools like Maven and Gradle
--> It provides lots of plugins to work with embedded and in-memory Databases very easily.
--> Where In-Memory databases are the databases, they will be created when application
startup and it will be destroyed when application terminated.
EX: H2 Database.
--> In simple words, Spring Boot is the Existed Spring Framework with Embedded Web
Servers like Tomcat and Jetty with No XMl configurations and less Annotations.
1.SpringApplication
2.Externalized Configuration
3. Profiles
CONTACT US:
3
Page
4. Logging
5. Internationalization
6. JSON
8. RSocket:
9.Security:
12. Cache:
13.Messaging:
15. Validations:
19.Admin features:
20.Properties Files
21.YAML Support:
CONTACT US:
4
Page
22.Type-safe Configuration:
1.SpringApplication:
SpringApplication is a class, it provides a convenient way to bootstrap a Spring application
that is started from a main() method. SpringApplication has a static method run() to
execute Spring application.
EX:
class MyApp{
When we run the above application then we will get the following output .
. ____ _ __ _ _
CONTACT US:
5
Page
=========|_|==============|___/=/_/_/_/
CONTACT US:
6
Page
***************************
***************************
Description:Embedded servlet container failed to start. Port 8080 was already in use.
Action:Identify and stop the process that's listening on port 8080 or configure this
application to listen on another port.
2.Externalized Configuration:
--------------------------------------
Spring Boot is giving an option to use like to externalize our application configurations so
that we can work with the same application code in different environments. To provide
Externalizable configurations we can use properties files, YAML files, environment
variables, and command-line arguments,..
CONTACT US:
7
Page
3. PROFILES:
-----------------
Spring Profiles provide a way to segregate parts of your application configuration and make
it be available only in certain environments.
IN SPring Boot applications, we are able to provide profiles configuration either through
@Profile() annotation or through properties file or through Command Line Arguments.
@Configuration(proxyBeanMethods = false)
@Profile("production")
CONTACT US:
8
Page
// ...
spring.profiles.active=dev,hsqldb
--spring.profiles.active=dev,hsqldb.
4. Logging
---------------
Spring Boot uses Commons Logging for all internal logging but leaves the underlying log
implementation open. Default configurations are provided for Java Util Logging, Log4J2,
and Logback. In each case, loggers are pre-configured to use console output with optional
file output also available.
5. Internationalization:
CONTACT US:
9
Page
--------------------------------
Spring Boot supports localized messages so that your application can provide services to
users of different languages . By default, Spring Boot looks for the presence of a messages
resource bundle at the root of the classpath.
spring.messages.basename=messages,config.i18n.messages
spring.messages.fallback-to-system-locale=false
6. JSON
------------
Spring Boot provides integration with three JSON mapping libraries
1. Gson
2. Jackson
3. JSON-B
CONTACT US:
Page
Most web applications use the spring-boot-starter-web module to get up and running
quickly.
8. RSocket:
---------------
RSocket is a binary protocol for use on byte stream transports. It enables symmetric
interaction models via async message passing over a single connection.
The spring-messaging module of the Spring Framework provides support for RSocket
requesters and responders, both on the client and on the server side.
9.Security:
--------------
If Spring Security is on the classpath, then web applications are secured by default. Spring
Boot relies on Spring Security’s content-negotiation strategy to determine whether to use
11
CONTACT US:
Page
httpBasic or formLogin. To add method-level security to a web application, you can also
add @EnableGlobalMethodSecurity with your desired settings
1.MongoDB
12
CONTACT US:
Page
2.Neo4J
3.Elasticsearch
4.Cassandra
5.Couchbase
6.LDAP
12. Cache:
----------------
--> The Spring Framework provides support for transparently adding caching to an
application. At its core, the abstraction applies caching to methods, thus reducing the
number of executions based on the information available in the cache.
--> The caching logic is applied transparently, without any interference to the invoker.
Spring Boot auto-configures the cache infrastructure as long as caching support is
enabled via the @EnableCaching annotation.
13.Messaging:
--------------------
13
CONTACT US:
Page
--> The Spring Framework provides extensive support for integrating with messaging
systems, from simplified use of the JMS API using JmsTemplate to a complete
infrastructure to receive messages asynchronously.
--> Spring AMQP provides a similar feature set for the Advanced Message Queuing
Protocol.
--> Spring Boot also provides auto-configuration options for RabbitTemplate and
RabbitMQ.
--> Spring WebSocket natively includes support for STOMP messaging, and Spring Boot has
support for that through starters and a small amount of auto-configuration. Spring Boot
also has support for Apache Kafka.
If we want to use Web Client to call remote Rest Services then we have to use WebFlux
module. 14
CONTACT US:
Page
15. Validations:
---------------------
Spring Boot is supporting Bean validations like Hibernate Bean Validations inorder to
validate data in bean objects.
CONTACT US:
Page
transactions. You can use standard Spring idioms, such as @Transactional, to participate in
a distributed transaction. If you are within a JTA environment and still want to use local
transactions, you can set the spring.jta.enabled property to false to disable the JTA auto-
configuration.
19.Admin features:
--------------------------
Spring Boot provides the facility to enable admin related features for the application. It is
used to access and manage application remotely. We can enable it by simply using
spring.application.admin.enabled property.
20.Properties Files:
--------------------------
16
CONTACT US:
Page
Spring Boot provides rich set of Application Properties. So, we can use that in properties file
of our project. Properties file is used to set properties like: server-port = 8082 and many
others. It helps to organize application properties.
21.YAML Support:
--------------------------
It provides convenient way for specifying hierarchical configuration. It is a superset of JSON.
The SpringApplication class automatically support YAML. It is successful alternative of
properties.
22.Type-safe Configuration:
--------------------------------------
Strong type-safe configuration is provided to govern and validate the configuration of
application. Application configuration is always a crucial task which should be type-safe.
We can also use annotation provided by this library.
17
CONTACT US:
Page
--> If we want to prepare any web application with tomcat server and with Database
interaction then we have to add the following JArs minimum to the project library.
CONTACT US:
Page
The above approach will increase no of dependencies in our build file, it will increase build
file size and it is very much difficult task to manage all these dependencies.
--> To overcome all the above problems, we have to use Spring Boot Starter Component.
--> Spring Boot Starter component combines all related jars into single jar file so that we
can add only jar file dependency to our build files instead of adding above jars files to
our build file, we need to add one and only one jar file like
--> When we add “spring-boot-starter-web” jar file dependency to our build file, then
Spring Boot Framework will automatically download all required jars and add to our
project classpath.
Spring-boot-starter-web dependency will provide the following jars to our project library.
19
CONTACT US:
Page
1. spring-boot-starter
a.spring-boot
b.spring-boot-autoconfiogure
c.spring-boot-starter-logging
2. spring-web
3. spring-webmvc
4. spring-boot-starter-tomcat
a. tomcat-embeded-core
b.tomcat-embeded-logging-juli
HandlerMapping Configuration
ViewResolver configurations
20
CONTACT US:
Page
To avoid all the above configurations Spring Boot has provided an autoConfigurator. Spring
Boot Autoconfigurator will come automatically when we add "spring-boot-starter-web"
dependency in build file, it will resolve views and Viewresolvers in Spring web MVC
applications with out having Spring configuration file and if we use @SpringBootApplication
annotation then it will avoid the explicit utilization of @Configuration, @ComponentScan
and @EnableAutoConfiguration and provide them all these annotations to the Java Class
internally.
--> When we run Spring Boot applications using CLI, then it internally uses Spring Boot
Starter and Spring Boot AutoConfigurator components to resolve all dependencies and
execute the application.
--> Spring Boot Command Line Interface has provided "spring" command to execute
"Groovy" scripts from Command Prompt, that is, we have to prepare Controller classes in
".groovy" file.
21
CONTACT US:
Page
--> When we run the above "spring" command on Command Line Interface then Spring
Boot will activate Groovyc[Groovy Compiler] and Groovy Grap to add all the
dependencies to project library and to execute and test Groovy script.
1. Spring Boot Actuator is providing environment to manage and monitor your application
by using HTTP endpoints or with JMX.
2. Spring Boot Actuators are providing Auditing, health, and metrics automatically to your
application.
--> When we run our Spring Boot Web Application using CLI, Spring Boot Actuator
automatically provides hostname as “localhost” and default port number as “8080”. We
can access this application using “http://localhost:8080/” end point.
22
CONTACT US:
Page
--> To activate Spring Boot Actuators we have to use the following dependecies in build file.
EX:
1. <dependency>
2. <groupId>org.springframework.boot</groupId>
3. <artifactId>spring-boot-starter-actuator</artifactId>
4. </dependency>
2. STS IDE
CONTACT US:
Page
---------------------------------------------------------------
1. Make Ready Setups for JDK1.8 and Eclipse IDE latest version.
4. Prepare Java Class With main() method and the required Spring Boot Annotations.
1. Make Ready Setups for JDK1.8 and Eclipse IDE latest version:
--------------------------------------------------------------------------------------
Already we have JDK and Eclipse in our system, no need to reinstall them seperately.
--------------------------------------------------------
2. Select "New".
2. Select "Others".
24
CONTACT US:
Page
--------------------------------------------------------------------------
<build>
<plugins>
25
CONTACT US:
Page
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Right CLick on Project, Select Maven and Select Update Project and Click on OK toget JAVA8
version in lib.
<parent>
<groupId>org.springframework.boot</groupId>
26
CONTACT US:
Page
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Observe all the dependent JARs under MAVEN Dependencies in MAVEN Project.
4. Prepare Java Class With main() method and the required Spring Boot Annotations:
--------------------------------------------------------------------------------------------------------------------
package com.durgasoft;
import org.springframework.boot.SpringApplication;
27
CONTACT US:
Page
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
Where SpringApplications provided run() method will start spring boot application.
If 8080 is busy in our system then Change Server port number from 8080 to 1111 [any
number] by providing properties file:
src/main/resources/application.properties
--------------------------------------
server.port = 1111
-------------------------------------------
CONTACT US:
Page
2. Select "RunAs"
4. Select "HelloWord"
. ____ _ __ _ _
=========|_|==============|___/=/_/_/_/
CONTACT US:
Page
CONTACT US:
Page
CONTACT US:
Page
CONTACT US:
Page
Note: If we want to access the same application through Web Client then we have to
prepare a Controller class , where we have to provide handler method with a particular
return value.
EX:
----
HelloController.java:
---------------------------
package com.durgasoft.controller;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
33
CONTACT US:
Page
@RequestMapping("/hello")
Access the above controller class by using the following URL at client browser after
executing HelloWorld standalone application.
http://localhost:1111/hello
2.Steps to prepare Spring Boot Application by using STS[Spring Tool Suit] IDE:
-------------------------------------------------------------------------------------------------------
c)
34
CONTACT US:
Page
--------------------------------------------------------
d)Find "sts-4.4.0.RELEASE" folder at C driver and open "sts-4.4.0.RELEASE" and double click
on "SpringToolSuite4" Application.
-----------------------------------------
a)Name: helloapp
35
CONTACT US:
Page
b)Group : com.durgasoft
c)Artifact: helloapp
e)package: com.durgasoft
e)Click on "Next".
If we do the above steps then we will get SpringBoot project at Project Explorer part.
EX: HelloApplication.java:
-----------------------------------
package com.durgasoft;
36
CONTACT US:
Page
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(HelloappApplication.class, args);
. ____ _ __ _ _
CONTACT US:
Page
=========|_|==============|___/=/_/_/_/
CONTACT US:
Page
Note: If 8080 port is busy in our system then change server port number by using key-value
pair "server.port=2222" in application.properties which is available under
"src\main\resources\application.properties".
e)If we want to execute through Web Client then prepare controller class with handler
method.
EX: HelloController.java
---------------------------------
package com.durgasoft.controller; 39
CONTACT US:
Page
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
f)Execute HelloApplication appliocation and open browser and use the following URL at
address bar.
http://localhost:2222/hello
------------------------------
40
CONTACT US:
Page
-->Spring Boot initializr is a web tool , it will provide option to generate Spring boot projects
directly as per the provided project details.
-->Spring Boot Initializr will give an option to download the project directly from web and
to execute through Eclipse IDE or some other.
Steps:
-------
---------------------------------------------------
b)Language : JAVA
d)Project Metadata :
group: com.durgasoft
41
CONTACT US:
Page
artifact: helloapp
Options:
Name: helloapp
Packaging : jar
JAVA: 8
------------------------------------------------------
1)Select "File" --> "import" --> "Maven" --> "Existed Maven Projects".
42
CONTACT US:
Page
EX: HelloappApplication.java
------------------------------
package com.durgasoft;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(HelloappApplication.class, args);
43
CONTACT US:
Page
Note: If 8080 port is busy in our system then change port number from 8080 to some other
by providing "server.port" in application.properties file which is existed in
"src\Main\resources\application.properties".
Output:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.9.RELEASE)
44
CONTACT US:
Page
CONTACT US:
Page
e)If we want to prepare Spring Boot application through Web Client then prepare
Controller class with handler method and execute that:
EX: HelloController.java
-------------------------
package com.durgasoft.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
CONTACT US:
Page
To run this , first we have to execute "HelloappApplication" then open browser and use the
following URL.
http://localhost:5555/hello
-------------------------------------------------------------
--> Spring Boot CLI(Command Line Interface) is a Spring Boot software to run and test
Spring Boot applications from command prompt. When we run Spring Boot applications
using CLI, then it internally uses Spring Boot Starter and Spring Boot AutoConfigurate
components to resolve all dependencies and execute the application
--> Spring Boot internally contains Groovy and Grape (JAR Dependency Manager) to add
Spring Boot Defaults and resolve all dependencies automatically.
--> To use Spring Boot CLI we have to use the following steps.
CONTACT US:
Page
-----------------------------------------
set path=%path%;C:\spring-2.1.9.RELEASE\bin;
CONTACT US:
Page
--------------------------------
It is almost all same as JAVA code only, but, the file extension should be .groovy.
EX: D:\spring_boot_practice\cli\HelloController.groovy
--------------------------------------------------------
@RestController
@RequestMapping("/hello")
3. If 8080 is busy then change tomcat port number from 8080 to 1234 by providing
application.properties file at the same location:
-------------------------------------------------------------------------------------------------------------------------
---------
49
CONTACT US:
Page
D:\spring_boot_practice\cli\application.properties
--------------------------------------------------
server.port=1234
---------------------------------------------------
http://localhost:1234/hello
Postman:
--------
Postman is a web tool, it can be used to send different types of request like GET, POST,
PUT, OPTIONS,......, but, it required HttpServer environment.
Steps:
------
50
CONTACT US:
Page
2.Open Postman tool and send request to Spring boot Application which is running at
present.
---------------------------------------------------
With the above Postman tool will download with the setup file "Postman-win64-7.8.0-
Setup.exe.
CONTACT US:
Page
------------------------------------------------------------------------------------------------
EX:
---
application.properties
----------------------
server.port=1234
HelloappApplication.java
-------------------------
package com.durgasoft;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
52
CONTACT US:
Page
@SpringBootApplication
SpringApplication.run(HelloappApplication.class, args);
HelloController.java
---------------------
package com.durgasoft.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
CONTACT US:
Page
@RequestMapping(value="/hello",method = RequestMethod.GET )
@RequestMapping(value="/hello",method = RequestMethod.POST )
pom.xml:
-----------
CONTACT US:
Page
10. </parent>
11. <groupId>com.durgasoft</groupId>
12. <artifactId>helloapp</artifactId>
13. <version>0.0.1-SNAPSHOT</version>
14. <name>helloapp</name>
15. <description>helloapp for Spring Boot</description>
16.
17. <properties>
18. <java.version>1.8</java.version>
19. </properties>
20.
21. <dependencies>
22. <dependency>
23. <groupId>org.springframework.boot</groupId>
24. <artifactId>spring-boot-starter-web</artifactId>
25. </dependency>
26.
27. <dependency>
28. <groupId>org.springframework.boot</groupId>
29. <artifactId>spring-boot-starter-test</artifactId>
30. <scope>test</scope>
31. </dependency>
32. </dependencies>
33.
34. <build>
35. <plugins>
36. <plugin>
37. <groupId>org.springframework.boot</groupId>
38. <artifactId>spring-boot-maven-plugin</artifactId>
39. </plugin>
40. </plugins>
41. </build>
42. </project>
In Postman.
55
CONTACT US:
Page
If we send GET request with the url "http://localhost:1234/hello" then we will get "Hello
User!" response.
If we send POST request with the url "http://localhost:1234/hello" then we will get
"Welcome User!" response.
--------------------------------------------------------------------
2. Prepare "webapp/WEB-INF" folders under "src/main" folders to provide JSP and html
pages.
5. Prepare Controller classes as per Spring WEB MVC and as per the requirement.
EX:
56
CONTACT US:
Page
---
1. helloapp
2. |---/src/main/java
3. | |---com.durgasoft
4. | |-----HelloappApplication.java
5. |---com.durgasoft.controller
6. | |HelloController.java
7. |---/src/main/resources
8. | |---static
9. | |---templates
10. | |---application.properties
11. |---/src/test/java
12. |---src
13. | |---main
14. | |----webapp
15. | |----WEB-INF
16. | |---hellopage.jsp
17. | |---wishpage.jsp
18. |---/src/test
19. |---target
20. |---HELP.md
21. |---mvnw
22. |---mvnw.cmd
23. |---pom.xml
hellopage.jsp
---------------
CONTACT US:
Page
9. <body>
10. <h2 style="color: red;" align="center">Durga Software Solutions</h2>
11. <h3 style="color: blue;" align="center">User Hello Form</h3>
12. <form method="post" action="wish">
13. <table align="center">
14. <tr>
15. <td>User Name</td>
16. <td><input type="text" name="username"></td>
17. </tr>
18. <tr>
19. <td><input type="submit" value="SayHello"/></td>
20. </tr>
21. </table>
22. </form>
23. </body>
24. </html>
wishpage.jsp:
------------------
CONTACT US:
Page
HelloController.java:
----------------------------
package com.durgasoft.controller;
1. import org.springframework.stereotype.Controller;
2. import org.springframework.ui.ModelMap;
3. import org.springframework.web.bind.annotation.RequestMapping;
4. import org.springframework.web.bind.annotation.RequestMethod;
5. import org.springframework.web.bind.annotation.RequestParam;
6.
7. @Controller
8. public class HelloController {
9.
10. @RequestMapping(value="/hellopage",method = RequestMethod.GET )
11. public String sayHello() {
12. return "hellopage";
13. }
14.
15. @RequestMapping(value="/wish",method = RequestMethod.POST )
16. public String wish(@RequestParam String username, ModelMap map) {
17. map.addAttribute("username", username);
18. return "wishpage";
19. }
20. }
HelloappApplication.java:
--------------------------------
package com.durgasoft;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
59
CONTACT US:
Page
@SpringBootApplication
SpringApplication.run(HelloappApplication.class, args);
Application.properties:
------------------------------
server.port=1234
spring.mvc.view.prefix = /WEB-INF/
spring.mvc.view.suffix = .jsp
pom.xml:
-----------
CONTACT US:
Page
4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/x
sd/maven-4.0.0.xsd">
5. <modelVersion>4.0.0</modelVersion>
6. <parent>
7. <groupId>org.springframework.boot</groupId>
8. <artifactId>spring-boot-starter-parent</artifactId>
9. <version>2.1.9.RELEASE</version>
10. <relativePath /> <!-- lookup parent from repository -->
11. </parent>
12. <groupId>com.durgasoft</groupId>
13. <artifactId>helloapp</artifactId>
14. <version>0.0.1-SNAPSHOT</version>
15. <name>helloapp</name>
16. <description>helloapp for Spring Boot</description>
17.
18. <properties>
19. <java.version>1.8</java.version>
20. </properties>
21.
22. <dependencies>
23. <dependency>
24. <groupId>org.springframework.boot</groupId>
25. <artifactId>spring-boot-starter-web</artifactId>
26. </dependency>
27.
28.
29. <dependency>
30. <groupId>org.apache.tomcat</groupId>
31. <artifactId>tomcat-jasper</artifactId>
32. <version>9.0.26</version>
33. </dependency>
34.
35. <dependency>
36. <groupId>org.springframework.boot</groupId>
37. <artifactId>spring-boot-starter-test</artifactId>
38. <scope>test</scope>
39. </dependency>
40. </dependencies>
41.
42. <build>
43. <plugins>
61
CONTACT US:
Page
44. <plugin>
45. <groupId>org.springframework.boot</groupId>
46. <artifactId>spring-boot-maven-plugin</artifactId>
47. </plugin>
48. </plugins>
49. </build>
50. </project>
EX:
---
loginapp
|---/src/main/java
| |---com.durgasoft
| |-----LoginappApplication.java
|---com.durgasoft.controller
| |LoginController.java
|---/src/main/resources
| |---static
| |---templates
| |---application.properties
|---/src/test/java
|---src
62
CONTACT US:
Page
| |---main
| |----webapp
| |----WEB-INF
| |---failure.jsp
| |---loginform.jsp
| |---success.jsp
|---/src/test
|---target
|---HELP.md
|---mvnw
|---mvnw.cmd
|---pom.xml
loginform.jsp:
------------------
CONTACT US:
Page
success.jsp
---------------
CONTACT US:
Page
13. </h2>
14. </body>
15. </html>
failure.jsp
--------------
LoginController.java
---------------------------
1. package com.durgasoft.controller;
2.
3. import org.springframework.stereotype.Controller;
4. import org.springframework.web.bind.annotation.RequestMapping;
5. import org.springframework.web.bind.annotation.RequestMethod;
6. import org.springframework.web.bind.annotation.RequestParam;
7.
8. @Controller
9. public class LoginController {
10.
11. @RequestMapping(value="/loginpage", method = RequestMethod.GET)
12. public String showLoginPage() {
13. return "loginform";
65
CONTACT US:
Page
14. }
15.
16. @RequestMapping(value="/login", method = RequestMethod.POST)
17. public String login(@RequestParam String uname, @RequestParam String upwd) {
18. String status = "";
19. if(uname.equals("durga") && upwd.equals("durga")) {
20. status = "success";
21. }else {
22. status = "failure";
23. }
24. return status;
25. }
26. }
LoginappApplication.java
--------------------------
package com.durgasoft;
1. import org.springframework.boot.SpringApplication;
2. import org.springframework.boot.autoconfigure.SpringBootApplication;
3.
4. @SpringBootApplication
5. public class LoginappApplication {
6.
7. public static void main(String[] args) {
8. SpringApplication.run(LoginappApplication.class, args);
9. }
10.
11. }
Application.properties
------------------------
server.port = 1234
66
CONTACT US:
Page
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
pom.xml
-----------
CONTACT US:
Page
29. <dependency>
30. <groupId>org.apache.tomcat</groupId>
31. <artifactId>tomcat-jasper</artifactId>
32. <version>9.0.26</version>
33. </dependency>
34.
35.
36. <dependency>
37. <groupId>org.springframework.boot</groupId>
38. <artifactId>spring-boot-starter-test</artifactId>
39. <scope>test</scope>
40. </dependency>
41. </dependencies>
42.
43. <build>
44. <plugins>
45. <plugin>
46. <groupId>org.springframework.boot</groupId>
47. <artifactId>spring-boot-maven-plugin</artifactId>
48. </plugin>
49. </plugins>
50. </build>
51.
52. </project>
First Execute LoginappApplication as standalone application then open browser and access
the application by using the following URL.
http://localhost:1234/loginpage.
------------------------------------------------------------------------
68
CONTACT US:
Page
To prepare Spring Boot Application with Spring-JDBC , we have to use the following Steps.
set path=C:\apache-maven-3.6.2\bin;
D:\>mvn install:install-file -
Dfile=C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar -
DgroupId=com.oracle - DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar 69
CONTACT US:
Page
groupid: com.oracle
artifactid: ojdbc6
version:11.2.0
3. Prepare Spring boot Starter project in STS with Spring Web and JDBC API in SQL part.
1. <project>
2. ----
3. <dependencies>
4. <dependency>
5. <groupId>com.oracle</groupId>
6. <artifactId>ojdbc6</artifactId>
7. <version>11.2.0</version>
8. </dependency>
9. <dependency>
10. <groupId>org.apache.tomcat</groupId>
11. <artifactId>tomcat-jasper</artifactId>
12. <version>9.0.26</version>
13. </dependency>
14. -----
15. </dependencies>
16. ----
17. </project>
70
CONTACT US:
Page
server.port=1234
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=system
spring.datasource.password=durga
Note: datasource name is not required, because, Spring boot is using Apache's "Hikary
Connection pooling Mechanism" bydefault.
EX:
----
71
CONTACT US:
Page
application.properties:
------------------------------
server.port=1234
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=system
spring.datasource.password=durga
welcome.jsp:
-----------------
CONTACT US:
Page
Addform.jsp
----------------
CONTACT US:
Page
26. </tr>
27. <tr>
28. <td><input type="submit" value="ADD"/></td>
29. </tr>
30. </table>
31. </form>
32. </body>
33. </html>
searchform.jsp:
-------------------
CONTACT US:
Page
25. </body>
26. </html>
updateform.jsp:
---------------------
Editform.jsp
----------------
CONTACT US:
Page
2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-
//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7. <title>Insert title here</title>
8. </head>
9. <body>
10. <jsp:include page="/WEB-INF/welcome.jsp"/>
11. <br><br><br><br><br>
12. <form method="post" action="update">
13. <table align="center">
14. <tr>
15. <td>Student Id</td>
16. <td>${std.sid}</td>
17. </tr>
18. <tr>
19. <td>Student Name</td>
20. <td><input type="text" name="sname" value="${std.sname}"></td>
21. </tr>
22. <tr>
23. <td>Student Address</td>
24. <td><input type="text" name="saddr" value="${std.saddr}"></td>
25. </tr>
26. <tr>
27. <td><input type="submit" value="Update"></td>
28. </tr>
29.
30. </table>
31. <input type="hidden" name="sid" value="${std.sid}">
32. </form>
33. </body>
34. </html>
Deleteform.jsp:
--------------------
76
CONTACT US:
Page
studentdetails.jsp:
------------------------
CONTACT US:
Page
8. </head>
9. <body>
10. <jsp:include page="/WEB-INF/welcome.jsp"/>
11. <br><br><br><br><br>
12. <table align="center" border="1">
13. <tr>
14. <td>Student Id</td>
15. <td>${std.sid}</td>
16. </tr>
17. <tr>
18. <td>Student Name</td>
19. <td>${std.sname}</td>
20. </tr>
21. <tr>
22. <td>Student Address</td>
23. <td>${std.saddr}</td>
24. </tr>
25. </table>
26. </body>
27. </html>
success.jsp:
---------------
CONTACT US:
Page
failure.jsp
------------
existed.jsp
-------------
CONTACT US:
Page
Notexisted.jsp
-------------------
StudentController.java:
------------------------------
1. package com.durgasoft.controller;
2.
3. import org.springframework.beans.factory.annotation.Autowired;
4. import org.springframework.stereotype.Controller;
5. import org.springframework.ui.ModelMap;
6. import org.springframework.web.bind.annotation.RequestMapping;
7. import org.springframework.web.bind.annotation.RequestMethod;
8. import org.springframework.web.bind.annotation.RequestParam;
9.
10. import com.durgasoft.dto.Student;
11. import com.durgasoft.service.StudentService;
12.
13. @Controller
14. public class StudentController {
15.
80
CONTACT US:
Page
16. @Autowired
17. StudentService studentService;
18.
19. @RequestMapping("/welcomepage")
20. public String showWelcomePage() {
21. return "welcome";
22. }
23. @RequestMapping("/addform")
24. public String showAddPage() {
25. return "addform";
26. }
27. @RequestMapping("/searchform")
28. public String showSearchPage() {
29. return "searchform";
30. }
31. @RequestMapping("/updateform")
32. public String showUpdatePage() {
33. return "updateform";
34. }
35. @RequestMapping("/editformform")
36. public String showEditPage() {
37. return "editform";
38. }
39. @RequestMapping("/deleteform")
40. public String showDeletePage() {
41. return "deleteform";
42. }
43.
44. @RequestMapping(value="/add", method = RequestMethod.POST)
45. public String add(ModelMap map, @RequestParam String sid, @RequestParam String s
name,@RequestParam String saddr) {
46. map.addAttribute("operation", "Student Insertion");
47. Student std = new Student();
48. std.setSid(sid);
49. std.setSname(sname);
50. std.setSaddr(saddr);
51.
52. String status = studentService.addStudent(std);
53.
54. return status;
55. }
81
CONTACT US:
Page
56.
57. @RequestMapping(value="/search", method=RequestMethod.POST)
58. public String search(ModelMap map, @RequestParam String sid) {
59. String status = "";
60. Student std = studentService.searchStudent(sid);
61. if(std == null) {
62. status = "notexisted";
63. }else {
64. map.addAttribute("std", std);
65. status = "studentdetails";
66. }
67. return status;
68. }
69.
70. @RequestMapping(value="editform", method = RequestMethod.POST)
71. public String getEditForm(ModelMap map, @RequestParam String sid) {
72. String status = "";
73. Student std = studentService.searchStudent(sid);
74. if(std == null) {
75. status = "notexisted";
76. }else {
77. map.addAttribute("std", std);
78. status="editform";
79. }
80. return status;
81. }
82.
83. @RequestMapping(value="update", method = RequestMethod.POST)
84. public String update(ModelMap map,@RequestParam String sid, @RequestParam String
sname, @RequestParam String saddr) {
85. String status = "";
86. map.addAttribute("operation", "Student Updation");
87. Student std = new Student();
88. std.setSid(sid);
89. std.setSname(sname);
90. std.setSaddr(saddr);
91.
92. status = studentService.updateStudent(std);
93. return status;
94. }
95.
82
CONTACT US:
Page
StudentService.java:
---------------------------
1. package com.durgasoft.service;
2.
3. import com.durgasoft.dto.Student;
4.
5. public interface StudentService {
6. public String addStudent(Student std);
7. public Student searchStudent(String sid);
8. public String updateStudent(Student std);
9. public String deleteStudent(String sid);
10. }
StudentServiceImpl.java:
----------------------------------
1. package com.durgasoft.service;
2.
3. import org.springframework.beans.factory.annotation.Autowired;
4. import org.springframework.stereotype.Service;
5.
6. import com.durgasoft.dao.StudentDao;
7. import com.durgasoft.dto.Student;
8.
9. @Service
10. public class StudentServiceImpl implements StudentService {
11.
12. @Autowired
83
CONTACT US:
Page
StudentDao.java
----------------------
package com.durgasoft.dao;
import com.durgasoft.dto.Student;
84
CONTACT US:
Page
StudentDaoImpl.java:
----------------------------
package com.durgasoft.dao;
1. import java.util.List;
2.
3. import org.springframework.beans.factory.annotation.Autowired;
4. import org.springframework.jdbc.core.JdbcTemplate;
5. import org.springframework.stereotype.Repository;
6.
7. import com.durgasoft.dto.Student;
8.
9. @Repository
10. public class StudentDaoImpl implements StudentDao {
11.
12. @Autowired
13. JdbcTemplate jdbcTemplate;
85
CONTACT US:
Page
14. @Override
15. public String add(Student std) {
16. String status = "";
17. Student student = search(std.getSid());
18. if(student == null) {
19. int rowCount = jdbcTemplate.update("insert into student values('"+std.ge
tSid()+"','"+std.getSname()+"','"+std.getSaddr()+"')");
20. if(rowCount ==1) {
21. status = "success";
22. }else {
23. status = "failure";
24. }
25. }else {
26. status = "existed";
27. }
28. return status;
29. }
30.
31. @Override
32. public Student search(String sid) {
33. Student std = null;
34. List<Student> studentsList = jdbcTemplate.query("select * from student where
SID = '"+sid+"'", (rs, rowNum) ->{
35. Student s = new Student();
36. s.setSid(rs.getString("SID"));
37. s.setSname(rs.getString("SNAME"));
38. s.setSaddr(rs.getString("SADDR"));
39. return s;
40. });
41. if(studentsList.isEmpty() == true) {
42. std = null;
43. }else {
44. std = studentsList.get(0);
45. }
46. return std;
47. }
48.
49. @Override
50. public String update(Student std) {
51. String status = "";
86
CONTACT US:
Page
StudentApplication.java
---------------------------------
package com.durgasoft;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
87
CONTACT US:
Page
@SpringBootApplication
SpringApplication.run(StudentappApplication.class, args);
pom.xml:
------------
CONTACT US:
Page
20. </properties>
21.
22. <dependencies>
23. <dependency>
24. <groupId>org.springframework.boot</groupId>
25. <artifactId>spring-boot-starter-jdbc</artifactId>
26. </dependency>
27. <dependency>
28. <groupId>com.oracle</groupId>
29. <artifactId>ojdbc6</artifactId>
30. <version>11.2.0</version>
31. </dependency>
32. <dependency>
33. <groupId>org.apache.tomcat</groupId>
34. <artifactId>tomcat-jasper</artifactId>
35. <version>9.0.26</version>
36. </dependency>
37.
38. <dependency>
39. <groupId>org.springframework.boot</groupId>
40. <artifactId>spring-boot-starter-web</artifactId>
41. </dependency>
42.
43. <dependency>
44. <groupId>org.springframework.boot</groupId>
45. <artifactId>spring-boot-starter-test</artifactId>
46. <scope>test</scope>
47. </dependency>
48. </dependencies>
49.
50. <build>
51. <plugins>
52. <plugin>
53. <groupId>org.springframework.boot</groupId>
54. <artifactId>spring-boot-maven-plugin</artifactId>
55. </plugin>
56. </plugins>
57. </build>
58. </project>
89
CONTACT US:
Page
-----------------------------------
Spring Boot will follow an algorithm to find Connection pooling mechanism internally.
2. If Hikary Connection pooling is not existed then Spring boot will search for Tomcat
Pooling DataSource.
3. If both Hikary and Tomcat Pooling DataSource are not existed then Spring boot will
search for Commons DBCP2 mechanism if it is existed.
To check the above algorithm then we have to use the following Steps:
package com.durgasoft;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
90
CONTACT US:
Page
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan
@Autowired
SpringApplication.run(StudentappApplication.class, args);
@Override
}
91
CONTACT US:
Page
a)case-1: only Hikary Connection Pooling, No Tomcat JDBC and No Apache DBCP2
In pom.xml
-------------
Bydefault, Spring boot will search for Hikary Connection pooling mechanism.
----
CONTACT US:
Page
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>9.0.10</version>
</dependency>
93
CONTACT US:
Page
------
</dependencies>
----
EX:
---
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
94
CONTACT US:
Page
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1</version>
</dependency>
95
CONTACT US:
Page
-------
</dependencies>
----
For all the above cases we have to use the following content in application.properties file.
application.properties
------------------------
server.port=1234
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=system
spring.datasource.password=durga
96
CONTACT US:
Page
If we want to use any other Connection Pooling Mechanisms like C3PO or proxool in Spring
boot applications then we have to use the following steps.
----------------------------------------
c3p0.properties
----------------
c3p0.initialPoolSize = 10
c3p0.maxPoolSize = 10
c3p0.maxStatements = 20
c3p0.maxIdleTime = 20000
application.properties
97
CONTACT US:
Page
-----------------------
spring.datasource.type = com.mchange.v2.c3p0.ComboPooledDataSource
----
----
pom.xml
------
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</exclusion>
</exclusions>
98
CONTACT US:
Page
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
-----
</dependecies>
EX:
----
c3p0.properties
-----------------
c3p0.initialPoolSize = 10
c3p0.maxPoolSize = 10
c3p0.maxStatements = 20
c3p0.maxIdleTime = 20000
application.properties
99
CONTACT US:
Page
------------------------
server.port=1234
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url==jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=system
spring.datasource.password=durga
spring.datasource.type = com.mchange.v2.c3p0.ComboPooledDataSource
CustomConnectionPoolingApplication.java
----------------------------------------
package com.durgasoft;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
100
CONTACT US:
Page
@SpringBootApplication
@Autowired
SpringApplication.run(CustomconnectionpoolingApplication.class, args);
@Override
pom.xml:
------------
101
CONTACT US:
Page
CONTACT US:
Page
40. <artifactId>ojdbc6</artifactId>
41. <version>11.2.0</version>
42. </dependency>
43.
44. <dependency>
45. <groupId>c3p0</groupId>
46. <artifactId>c3p0</artifactId>
47. <version>0.9.1.2</version>
48. </dependency>
49. <dependency>
50. <groupId>org.springframework.boot</groupId>
51. <artifactId>spring-boot-starter-web</artifactId>
52. </dependency>
53.
54. <dependency>
55. <groupId>org.springframework.boot</groupId>
56. <artifactId>spring-boot-starter-test</artifactId>
57. <scope>test</scope>
58. </dependency>
59. </dependencies>
60.
61. <build>
62. <plugins>
63. <plugin>
64. <groupId>org.springframework.boot</groupId>
65. <artifactId>spring-boot-maven-plugin</artifactId>
66. </plugin>
67. </plugins>
68. </build>
69.
70. </project>
------------------------------------
CONTACT US:
Page
1. Install Database
3. Create Schema
4. Create table
5. Populating Data.
-----
-----
Zero Configuration
Zero Maintainance
CONTACT US:
Page
Spring Boot provides Simple Configuration to switch between a real database and an in
memory database like H2
In general, In Memory databases are started when application is started and destroyed
when application is stopped.
EX: H2
If we want to use H2 Im Memory Database for our applications then we have to use the
following steps.
1. Prepare Spring boot starter project with "web, JDBC" "h2" Dependencies in STS.
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
105
CONTACT US:
Page
spring.datasource.password=
schema.sql
-------------
create table emp1(ENO number(5) primary key, ENAME varchar2(10), ESAL float(5),
EADDR varchar2(10));
data.sql
--------
CONTACT US:
Page
Spring boot application will load and execute these sql scripting files.
EX:
----
schema.sql
-----------
create table emp1(ENO number(5) primary key, ENAME varchar2(10), ESAL float(5), EADDR
varchar2(10));
data.sql
----------
CONTACT US:
Page
application.properties
-----------------------
server.port=1234
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
H2DatabaseApplication.java
---------------------------
package com.durgasoft;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
108
CONTACT US:
Page
@SpringBootApplication
SpringApplication.run(H2databaseApplication.class, args);
EmployeeController.java
------------------------
package com.durgasoft.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
109
CONTACT US:
Page
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.durgasoft.dao.EmployeeDao;
import com.durgasoft.dto.Employee;
@Controller
@Autowired
@RequestMapping("getallemployees")
map.addAttribute("allEmployees", allEmployees);
return "employeesdetails";
}
110
CONTACT US:
Page
EmployeeDao.java
-----------------
package com.durgasoft.dao;
import java.util.List;
import com.durgasoft.dto.Employee;
Employee.java:
-------------------
package com.durgasoft.dto;
111
CONTACT US:
Page
EmployeeDaoImpl.java
---------------------
package com.durgasoft.dao;
112
CONTACT US:
Page
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.durgasoft.dto.Employee;
@Repository
@Autowired
@Override
emp.setEno(rs.getInt("ENO"));
113
CONTACT US:
Page
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
return emp;
});
return list;
employeedetails.jsp:
--------------------------
pageEncoding="ISO-8859-1"%>
<html>
114
CONTACT US:
Page
<head>
</head>
<body>
<tr><th>ENO</th><th>ENAME</th><th>ESAL</th><th>EADDR</th></tr>
<tr>
<td>${emp.eno}</td>
<td>${emp.ename}</td>
<td>${emp.esal}</td>
<td>${emp.eaddr}</td>
</tr>
</c:forEach>
</table>
</body>
115
CONTACT US:
Page
</html>
pom.xml
-----------
CONTACT US:
Page
31. <artifactId>tomcat-jasper</artifactId>
32. <version>9.0.26</version>
33. </dependency>
34.
35. <dependency>
36. <groupId>javax.servlet</groupId>
37. <artifactId>jstl</artifactId>
38. <version>1.2</version>
39. </dependency>
40.
41.
42. <dependency>
43. <groupId>org.springframework.boot</groupId>
44. <artifactId>spring-boot-starter-jdbc</artifactId>
45. </dependency>
46.
47. <dependency>
48. <groupId>com.h2database</groupId>
49. <artifactId>h2</artifactId>
50. <scope>runtime</scope>
51. </dependency>
52. <dependency>
53. <groupId>org.springframework.boot</groupId>
54. <artifactId>spring-boot-starter-test</artifactId>
55. <scope>test</scope>
56. </dependency>
57. </dependencies>
58.
59. <build>
60. <plugins>
61. <plugin>
62. <groupId>org.springframework.boot</groupId>
63. <artifactId>spring-boot-maven-plugin</artifactId>
64. </plugin>
65. </plugins>
66. </build>
67.
68. </project>
CONTACT US:
Page
http://localhost:1234/getallemployees
118
CONTACT US:
Page