Spring Framework
Spring Framework
Spring Core
Spring Containers
Type of Spring Configuration
Dependency Injection
IOC
Spring Web
MVC architecture
Web service:
Spring:
Spring Module:
A J Spring
JDBC Web
O E /
P ORM E MVC
Integration-Service
Uses
Uses
Information
Spring Core
/
Configuration
C – Create
Components Management
/ I – Initialize
Objects Management
D -- Destroy
Application
Object Reference
Container:
Spring Container:
This 3 Container are use to manage the life cycle of the object
1. Bean Factory Container(Interface)
2. ApplicationContext Container(Interface) This 3 Container are have their own functionality according to
3. WebApplicationContext Container(Interface) usage we chose Container.
-----Next>------- fill GroupId: example-com.jspider Artifactid: makemytrip Package:this will auto generate i.e
com.jspider.makemytrip------Finish
For creating any Maven Project ------ Internet Connection must be there
Project Name
How to get dependency?
1. Connect to Internet
2. Go to www.google.com
3. Search for Maven Central Repository.
4. Click on searched list: Central Repository or Paste URL : https://mvnrepository.com/repos/central
5. Search in MVN Repository page : example : Hibernate Core
6. Go to : example: Hibernate Core Relocation
7. click the version which you want to add the dependency : example: 5.4.0.Final
8. copy the written part in <dependency> </dependency>
Example: <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.Final</version>
</dependency>
spring-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-
context.xsd">
BookTicket.java
package com.jspider.makemytrip;
public BookTicket() {
// TODO Auto-generated constructor stub-- ctrl+space
System.out.println(this.getClass().getSimpleName()+" Object Created");
}
public void book() {
System.out.println("Ticket booked");
}
} For Knowing Class Name
Add dependency in: pom.xml
App.java
package com.jspider.makemytrip;
import org.springframework.context.support.ClassPathXmlApplicationContext;
getBean(BookTicket.class): It get object reference of the particular class that is mentioned in spring-web.xml
Run As---1JavaApplication
Console:
It is one of implementation class of Spring Container (ApplicationContext), which is use to load Spring Configuration file
from the class path(other name of class path : src folder).
Example: ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-web.xml");
getBean():
This method is use to get the reference of an object from the Spring Container
Example: BookTicket bookTicket = context.getBean(BookTicket.class);
bookTicket.book();
We have given Control to Spring framework for manage the Object of BookTicket class
class BookTicket{
………………….
……………..
…………………
………………..
To manage the Object of a BookTicket class or Number of Object to be created by Spring framework : scope
BookTicket.java
package com.jspider.makemytrip;
public BookTicket() {
// TODO Auto-generated constructor stub-- ctrl+space
System.out.println(this.getClass().getSimpleName()+" Object Created");
}
public void book() {
System.out.println("Ticket booked");
}
1. By Constructor initialization
2. By Setter Method initialization
import java.util.List;
public PassengerDetails() {
// TODO Auto-generated constructor stub---ctrl+space
System.out.println(this.getClass().getSimpleName()+" object created");
}
public PassengerDetails(int id, String name, String city, List<String> idProofList, String idNumber) {
super();
this.id = id;
this.name = name;
this.city = city;
this.idProofList = idProofList;
this.idNumber = idNumber;
}
@Override
public String toString() {
return "PassengerDetails [id=" + id + ", name=" + name + ", city=" + city + ", idProofList=" +
idProofList+ ", idNumber=" + idNumber + "]";
}
}
spring-web.xml
<?xml version="1.0" encoding="UTF-8"?> scope:
1. singleton (default): gives one Object reference
<beans xmlns="http://www.springframework.org/schema/beans" 2. prototype: gives Multiple Object Reference
xmlns:context="http://www.springframework.org/schema/context" 3. request: used in servlet base application
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4. session: used in servlet base application
xsi:schemaLocation="http://www.springframework.org/schema/beans 5. global: portal application like Naukari.com
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-
context.xsd">
import org.springframework.context.support.ClassPathXmlApplicationContext;
Here only one time “BookTicket Object Created” printed in console because of scope: default value is singleton so singleton
give only one object reference.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
bean:
bean is an object which is managed by Spring Container
bean can be declared in spring configuration file i.e spring-web.xml
bean tag is used to declare a Bean class
bean tag as two attribute: 1. id attribute
2. class attribute
id attribute must have unique name for the bean
class attribute should have fully Qualified class name of the Bean class
Setter initialization:
Initialising the properties using setter method or set by property
<property name="ticketNumber" value="IND1234"></property>
scope:
scope is used to configure number of objects to be created by Spring Container
Types of scope:
1. Singleton: It is the default scope of Spring bean
Container will create only one Object for each bean declaration
4. Session: session scope will create an Object for each Http session
5. Global: global scope can be configured only in portal application like Naukari.com
Note: request and session scope can be configured only in Servlet application
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Create Maven Project: makemytrip1
<context:component-scan base-package="com.jsp.makemytrip1"></context:component-scan>
</beans>
AppConfiguration.java
package com.jsp.makemytrip1;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages= "com.jsp.makemytrip1")
public class AppConfiguration {
This both work in similar way: It will Scan the @Component annotation class which will create Object of that class
base-package="com.jsp.makemytrip1": this will scan the entire project which is matching with package:
com.jsp.makemytrip1 and wherever @Component is written in that class it will create the Object for that class.
Hotel.java
package com.jsp.makemytrip1.javaconfiguration;
import org.springframework.stereotype.Component;
@Component /*@Component: it is use create the object of that class which is manage by spring conatiner */
public class Hotel {
public Hotel() {
// TODO Auto-generated constructor stub ctrl+space
System.out.println(this.getClass().getSimpleName()+" Object Created");
}
}
Payment.java
package com.jsp.makemytrip1.javaconfiguration;
import org.springframework.stereotype.Component;
@Component /* @Component:it is use create the object of this class and manage by spring container*/
public class Payment {
public Payment() {
// TODO Auto-generated constructor stub ctrl+space
System.out.println(this.getClass().getSimpleName()+" object created");
}
Run As ----1JavaApplication
App.java(do changes)
This will execute “spring-web.xml”
package com.jsp.makemytrip1;
file
//import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
Console:
May 27, 2023 11:33:10 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4bf558aa: startup date
[Sat May 27 23:33:10 IST 2023]; root of context hierarchy
May 27, 2023 11:33:11 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-web.xml]
Hotel Object Created
Payment object created
Run As ----1JavaApplication:
package com.jsp.makemytrip1;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
//import org.springframework.context.support.ClassPathXmlApplicationContext;
Console:
AppConfiguration.java(Changes)
package com.jsp.makemytrip1;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.jsp.makemytrip1.javaconfiguration.Payment;
@Bean: this will specify the Spring framework that returns
@Configuration type of this method is object which is manage by spring
@ComponentScan(basePackages= "com.jsp.makemytrip1") container.
public class AppConfiguration { If we remove @Bean then Spring framework will not
understand that return type is Object and it will not manage by
@Bean spring container and it will act as normal method only
public Payment getPayement() { Same as
return new Payment(); @Component: it is use create the object of that class which is
} managing by spring container.
}
Payment.java(Changes)
package com.jsp.makemytrip1.javaconfiguration;
//import org.springframework.stereotype.Component;
//@Component
public class Payment {
public Payment() {
// TODO Auto-generated constructor stub ctrl+space
System.out.println(this.getClass().getSimpleName()+" object created");
}
}
Run As -----JavaApplication
View makemytrip1
package com.jsp.makemytrip1.javaconfiguration;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component /*it is use create the object of that class by the spring framework */
public class Hotel {
@Value(value = "Taj")
private String name;
public Hotel() {
// TODO Auto-generated constructor stub ctrl+space
System.out.println(this.getClass().getSimpleName()+" Object Created");
}
@PostConstruct : It is used to execute the method after
@PostConstruct
public void intialize() { the constructor is executed of that class
System.out.println("Executing intialize()...!");
} This method is executed without calling method
public String getName() {
return name;
}
@Override
public String toString() {
return "Hotel [name=" + name + ", city=" + city + ", country=" + country + ", pincode=" + pincode + ", payment="
+ payment + "]";
}
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//@Component /*it is use to create the object of that class by spring framework */
public class Payment {
@Value(value = "12345")
private int id;
@Value(value = "2500")
private Double amount;
@Value(value = "success")
private String status;
public Payment() {
// TODO Auto-generated constructor stub ctrl+space
System.out.println(this.getClass().getSimpleName()+" object created");
}
@Override
public String toString() {
return "Payment [id=" + id + ", amount=" + amount + ", modeOfPayement=" + modeOfPayement + ",
status=" + status + "]";
}
}
AppConfiguration.java
package com.jsp.makemytrip1;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.jsp.makemytrip1.javaconfiguration.Payment;
@Configuration /*it will specify the spring that there is certain configuration or method is present in this class which processed by certain
Container */
@ComponentScan(basePackages= "com.jsp.makemytrip1")
public class AppConfiguration {
@Bean //this will specify the spring that return type of this method is object and manage by spring container
public Payment getPayement() {
return new Payment();
}
}
App.java
package com.jsp.makemytrip1;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.jsp.makemytrip1.javaconfiguration.Hotel;
//import org.springframework.context.support.ClassPathXmlApplicationContext;
<context:component-scan base-package="com.jsp.makemytrip1"></context:component-scan>
<!-- base package means common name for all the package in the project -->
</beans>
Run As---1JavaApplication
Console:
Spring Core
Information
/
Configuration
Object Reference
Application
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
It is a process of injecting the required contain into a class is known as Dependency Injection.
@Configuration: This annotation indicate the class declares one or more bean method and has to processed by Spring Container
@PostConstruct: Annotated method will be invoked after Object has been created
(Internet)
2.
3.
4.
5.
6.
7.
8.
After Controller
How to create Spring MVC Project in Maven:
Ctrl+N-----select------Maven Project-------Next>-----Next>-------Filter: org.apache.maven.archetype -------select--------
Group Id : org.apache.maven.archetype Artifact Id: maven-archetype-webapp Version: 1.4---------Next>------------
Group Id: com.jspider Artifact Id: springweb1 Version: 0.0.1-SNAPSHOT Package: com.jspider.springweb1 (This will automatic
generate the package when writing Group Id and Artifact Id) ----------Finish
Note: If src/main/java---- is not created or missing in Spring MVC maven project then:-
Select(Project)-----Right click -------Properties-------select------Java Build path-----Libraries---select----JRE System Library[ JavaSE-1.7]
----Edit....----- Select-----Execution environment: JavaSE-1.8(jdk 1.8.0_341) Enviroments......--------Finish----Apply----Apply and Close
This will create src/main/java folder
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Create Maven Spring MVC project----- springframeworks
<welcome-file-list>
<welcome-file>register.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-web.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<meta charset="ISO-8859-1">
<title>Register | Page</title>
</head>
<body>
<form action="saveRegisterDetails" method="post">
<div class="form-group">
<label for="name">Name</label> <input
type="text" class="form-control" name="name"
aria-describedby="emailHelp" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email</label> <input
type="email" class="form-control" name="email"
aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="mobileNumber">Mobile Number</label> <input
type="tel" class="form-control" name="mobileNumber"
aria-describedby="emailHelp" placeholder="Enter Mobile Number">
</div>
<div class="form-group">
<label for="country">Country</label> <input
type="text" class="form-control" name="country"
aria-describedby="emailHelp" placeholder="Enter Country">
</div>
<div class="form-group">
<label for="password">Password</label> <input
type="password" class="form-control" name="password"
placeholder="Password">
</div>
<div class="form-group">
<label for="dateofbirth">DOB</label> <input
type="date" class="form-control" name="dateOfBirth"
aria-describedby="emailHelp" placeholder="Enter DOB">
</div>
<input type="submit" value="Register" class="btn btn-primary">
</form>
</body>
</html>
Add dependency on: pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<context:component-scan base-package="com.sourabhsuman.springframeworks"></context:component-scan>
<!-- base package means common name for all the package in the project -->
</beans>
RegisterController.java
package com.sourabhsuman.springframeworks.controller;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.sourabhsuman.springframeworks.dto.RegisterDto;
@Component
@RequestMapping(value = "/")
public class RegisterController {
public RegisterController() {
// TODO Auto-generated constructor stub
System.out.println(this.getClass().getSimpleName()+" object created");
}
import java.io.Serializable;
@Override
public String toString() {
return "RegisterDto [name=" + name + ", email=" + email + ", mobileNumber=" + mobileNumber + ", country="
+ country + ", password=" + password + ", dateOfBirth=" + dateOfBirth + "]";
}
}
home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h6> Welcome User</h6>
</body>
</html>
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
Select the Project (springframeworks) ---Right Click----Run As---Run on Server---select---Tomcat v9.0 Server at localhost----Finish
Console
Spring web Module:
It is used to develop enterprise application.
It implements MVC architecture
Spring web provide solution for common problem based using Servlet
FrontController:
According to FrontControl design pattern application will have one Servlet which will be mapped all the actions.
In Spring Web DispatcherServlet is an implementation of front Controller
DispatcherServlet:
DispatcherServlet is an implementation of FrontController design pattern
DispatcherServlet is an entry and exit point for an application
contextConfigLocation:
It is a parameter of DispatcherServlet
This parameter is used to pass Spring Configuration file
Component of DispatcherServlet:
Handler Mapping
Controller
ViewResolver
Handler Mapping:
It is use to scan @RequestMapping annotation
Example: @RequestMapping(value="/saveRegisterDetails", method = RequestMethod.POST)
public ModelAndView saveRegisterDetails(RegisterDto registerDto) {
System.out.println(registerDto);
return new ModelAndView("home.jsp");
}
Is a map where the Key- URL and value -Controller Class Name
Handler Mapping takes URL and returns Controller Name to DispatcherServlet
Controller:
Controller is used for processing the request.
Controller takes request and returns ModelAndView to DispatcherServlet
View Resolver:
View Resolver takes name and returns Page to DispatcherServlet
JQUERY etc.
@Component create the object of that class exactly do the same work if we use @Controller, @Service and @Repository
There is some standard we have to follow for Controller Class we use @Controller for Service class we use @Service and
for Repository Class we use @Repository
Execution process: After Servlet file goes to @Controller class then goes to @Service class then go to @Repository
Create Spring MVC Maven Project: springframeworks
<welcome-file-list>
<welcome-file>register.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-web.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Register | Page</title>
</head>
<body>
<form action="saveRegisterDetails" method="post">
<div class="form-group">
<label for="name">Name</label> <input
type="text" class="form-control" name="name"
aria-describedby="emailHelp" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email</label> <input
type="email" class="form-control" name="email"
aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="mobileNumber">Mobile Number</label> <input
type="tel" class="form-control" name="mobileNumber"
aria-describedby="emailHelp" placeholder="Enter Mobile Number">
</div>
<div class="form-group">
<label for="country">Country</label> <input
type="text" class="form-control" name="country"
aria-describedby="emailHelp" placeholder="Enter Country">
</div>
<div class="form-group">
<label for="password">Password</label> <input
type="password" class="form-control" name="password"
placeholder="Password">
</div>
<div class="form-group">
<label for="dateofbirth">DOB</label> <input
type="date" class="form-control" name="dateOfBirth"
aria-describedby="emailHelp" placeholder="Enter DOB">
</div>
<input type="submit" value="Register" class="btn btn-primary">
</form>
</body>
</html>
spring-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-
context.xsd">
<context:component-scan base-package="com.sourabhsuman.springframeworks"></context:component-scan>
<!-- base package means common name for all the package in the project -->
</beans>
RegisterController.java
package com.sourabhsuman.springframeworks.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.sourabhsuman.springframeworks.entity.RegisterDto;
import com.sourabhsuman.springframeworks.service.RegisterService;
@Controller
@RequestMapping(value = "/")
public class RegisterController {
@Autowired
private RegisterService registerService;
public RegisterController() {
// TODO Auto-generated constructor stub ctrl+Space
System.out.println(this.getClass().getSimpleName()+" object created");
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sourabhsuman.springframeworks.entity.RegisterDto;
import com.sourabhsuman.springframeworks.repository.RegisterDao;
@Service
public class RegisterService {
@Autowired
private RegisterDao registerDao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
//import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sourabhsuman.springframeworks.entity.RegisterDto;
@Repository
public class RegisterDao {
@Autowired
private SessionFactory sessionFactory;
RegisterDto.java
package com.sourabhsuman.springframeworks.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="user_register")
public class RegisterDto implements Serializable {
@Id
@GenericGenerator(name="user_auto", strategy="increment")
@GeneratedValue(generator = "user_auto")
@Column(name="id")
private Long id;
@Column(name="name")
private String name;
@Column(name="email")
private String email;
@Column(name="mobile_number")
private String mobileNumber;
@Column(name="country")
private String country;
@Column(name="password")
private String password;
@Column(name="date_of_birth")
private String dateOfBirth;
<mapping class="com.sourabhsuman.springframeworks.entity.RegisterDto"></mapping>
</session-factory>
</hibernate-configuration>
home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h6> Welcome User</h6>
</body>
</html>
Create Database in HeideSQL : springframeworks and table name : user_register and column as below:
Select the Project : springframeworks---right click---Run As---1 Run on Server
In Console
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
-----------------------------------------------------------------------------------------------------------------------------------------------
The above project(springframeworks) Execution step:
1. web.xml , spring-web.xml, hibernate.cfg.xml
2. register.jsp
3. RegisterDto.java
4. RegisterController.java
5. RegisterService.java
6. RegisterDao.java
7. hibernate.cfg.xml
8. Then it returns back to RegisterController.java where in ModelAndView returns: home.jsp
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Flow of Spring MVC project
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
HDFC ATM
SBI ATM
Suppose you have SBI Account and SBI ATM and you went to HDFC ATM for withdraw money if you have entered correct
information in ATM then it will give you Money from HDFC ATM internally HDFC ATM will connect to HDFC server and that server
will give the data to SBI server and it will check and return response to HDFC server based on that we can withdraw the amount.
Suppose HDFC Server uses .NET and SBI Server uses Java then How both (HDFC and SBI) Server Connect with each other?
We have Common Programming Language to connect that is JSON, XML, TEXT format.
JSON : is the widely used language
XML : give More Security
REST:
REST is an architectural type
It is a set of guideline or principal while developing an application
It is used widely in Market
It uses Http protocol
It less secure compare to SOAP
SOAP:
By using SOAP we can exchange the data in .xml format
Its implementation is difficult because it uses own protocol
It is highly secure
SOAP performance is less
SOAP has its own framework, so Security is more
Guideline of REST:
Resource based URI
Uniform or Common Interface
Metadata
Statelessness: It will send only raw data
For OPERATION:
CREATE-------POST
READ---------GET
UPDATE-----PUT
DELETE-----DELETE
<context:component-scan base-package="com.sourabhsuman.springframeworks"></context:component-scan>
<!-- base package means common name for all the package in the project -->
</beans>
web.xml
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-web.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
login.jsp
<html>
<body>
<form action="login">
<div>
<label>Email</label> <input type="email" name="email">
</div>
<div>
<label>Password</label> <input type="password" name="password">
</div>
<div>
<input type="submit" name="login"> <a href="register.jsp"></a>
</div>
</form>
</body>
</html>
RegisterController.java
package com.sourabhsuman.springframeworks.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.sourabhsuman.springframeworks.dto.Login;
import com.sourabhsuman.springframeworks.entity.Register;
import com.sourabhsuman.springframeworks.service.RegisterService;
@Controller
@RequestMapping(value = "/")
public class RegisterController {
@Autowired
private RegisterService registerService;
public RegisterController() {
// TODO Auto-generated constructor stub ctrl+Space
System.out.println(this.getClass().getSimpleName()+" object created");
}
@RequestMapping(value="/login")
public ModelAndView login(Login login) {
boolean loginValidation = registerService.loginValidation(login);
if(loginValidation) {
return new ModelAndView("home.jsp");
}
else {
return new ModelAndView("register.jsp");
}
}
}
UserController.java(This class for Restful services)
package com.sourabhsuman.springframeworks.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpMethod;
//import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.sourabhsuman.springframeworks.entity.Register;
import com.sourabhsuman.springframeworks.service.RegisterService;
//@Controller
//@ResponseBody
//@Controller + @ResponseBody = @RestController
@RestController
@RequestMapping(value="/")
public class UserController {
@Autowired
private RegisterService registerService;
@PostMapping(value="/saveUserDetails")
public void saveUserDetails(@RequestBody Register register) {
registerService.saveRegisterDetailsservice(register); If URI value is dynamic
} then we should give it in
this {}
@GetMapping(value="/getUserById/{Id}")
public @ResponseBody Register getUserById(@PathVariable("Id") long id) {
return registerService.getRegisterDetailsById(id);
}
}
UserController.java is class which work for REST web services Like POSTMAN we use it.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sourabhsuman.springframeworks.dto.Login;
import com.sourabhsuman.springframeworks.entity.Register;
import com.sourabhsuman.springframeworks.repository.RegisterDao;
@Service
public class RegisterService {
@Autowired
private RegisterDao registerDao;
if(register!=null) {
if(login.getEmail().equals(register.getEmail()) &&
login.getPassword().equals(register.getPassword())){
return true;
}
return false;
}
else {
return false;
}
}
}
RegisterDao.java
package com.sourabhsuman.springframeworks.repository;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
//import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.sourabhsuman.springframeworks.entity.Register;
@Repository
public class RegisterDao {
@Autowired
private SessionFactory sessionFactory;
}
Register.java
package com.sourabhsuman.springframeworks.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="user_register")
public class Register implements Serializable {
@Id
@GenericGenerator(name="user_auto", strategy="increment")
@GeneratedValue(generator = "user_auto")
@Column(name="id")
private Long id;
@Column(name="name")
private String name;
@Column(name="email")
private String email;
@Column(name="mobile_number")
private String mobileNumber;
@Column(name="country")
private String country;
@Column(name="password")
private String password;
@Column(name="date_of_birth")
private String dateOfBirth;
@Override
public String toString() {
return "Register [id=" + id + ", name=" + name + ", email=" + email + ", mobileNumber=" +
mobileNumber + ", country=" + country + ", password=" + password + ", dateOfBirth=" + dateOfBirth + "]";
}
}
Login.java
package com.sourabhsuman.springframeworks.dto;
import java.io.Serializable;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
public class AppConfiguration {
}
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/springframeworks</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.sourabhsuman.springframeworks.entity.Register"></mapping>
</session-factory>
</hibernate-configuration>
home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h6> Welcome User</h6>
</body>
</html>
register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Register | Page</title>
</head>
<body>
<form action="saveRegisterDetails" method="post">
<div class="form-group">
<label for="name">Name</label> <input
type="text" class="form-control" name="name"
aria-describedby="emailHelp" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email</label> <input
type="email" class="form-control" name="email"
aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="mobileNumber">Mobile Number</label> <input
type="tel" class="form-control" name="mobileNumber"
aria-describedby="emailHelp" placeholder="Enter Mobile Number">
</div>
<div class="form-group">
<label for="country">Country</label> <input
type="text" class="form-control" name="country"
aria-describedby="emailHelp" placeholder="Enter Country">
</div>
<div class="form-group">
<label for="password">Password</label> <input
type="password" class="form-control" name="password"
placeholder="Password">
</div>
<div class="form-group">
<label for="dateofbirth">DOB</label> <input
type="date" class="form-control" name="dateOfBirth"
aria-describedby="emailHelp" placeholder="Enter DOB">
</div>
<input type="submit" value="Register" class="btn btn-primary">
</form>
</body>
</html>
pom.xml
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
config.register(AppConfiguration.class);
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
version="3.1">
<display-name>Sling Launchpad Web Application Archetype</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-web.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
AppConfiguration.java
package com.sourabhsuman.springframeworks1.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@EnableWebMvc
@Configuration
@ComponentScan("com.sourabhsuman.springframeworks")
public class AppConfiguration {
@Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(getDataSource());
sessionFactory.setPackagesToScan("com.sourabhsuman.springframeworks.entity");
sessionFactory.setHibernateProperties(getConnectionProperties());
return sessionFactory;
@Bean
public DataSource getDataSource() {
@Bean
public static Properties getConnectionProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.hbm2ddl.auto", "update");
return properties;
@Bean
public ModelMapper getModelMapper() {
return new ModelMapper();
}
}
We can add AppConfiguration.java and ServletIntializer.java in springframeworks (MVC Maven Porject) project where it will
remove spring-web.xml and hibernate.cfg.xml and <servlet></servlet> and <servlet-mapping></servlet-mapping> in web.xml file