0% found this document useful (0 votes)
16 views

Spring Framework

Spring framework note

Uploaded by

sourabhsuman425
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Spring Framework

Spring framework note

Uploaded by

sourabhsuman425
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Spring Content:

 Spring Core
 Spring Containers
 Type of Spring Configuration
 Dependency Injection
 IOC
 Spring Web
 MVC architecture

Web service:

 Restful Web service

Integration of spring and Hibernate

Spring:

 Spring efficiently manages objects or components for applications


 Spring is an open source enterprise(Web) application framework
 Spring is an integration technology( connect to other technology like hibernate)
 Spring is a configuration framework.
 Spring is an implementation of IOC.

Spring Module:

A J Spring
JDBC Web
O E /
P ORM E MVC

Spring Core / Spring IOC

IOC: Inversion of control

AOP: Accept Oriented Programming

ORM: Object Relational Mapping

JDBC: Java Database Connectivity

JEE: Java Enterprise Edition (Servlet base)

MVC: Model View Controller


How to get information about Spring?
Ans. https://spring.io/

Application (Developed by developer)

Integration-Service

Uses
Uses

Inbuilt Class: Custom (Developer) class:


String Movie
Collection User
System Employee
File etc
Thread and etc

This all are Managed by Spring Framework

Spring is a configuration framework. :

Spring Framework can be configured in two ways:

1. XML file Configuration


2. Java Configuration ( Annotation Based)

Spring 3 and below: we uses only XML configuration

Spring 4 and above: we use Java Configuration (Annotation Based)


Spring Module: Spring Core
Spring Core:

 Spring Core Module is used to manage the Components for an Applications

Information
Spring Core
/
Configuration

C – Create
Components Management
/ I – Initialize
Objects Management
D -- Destroy

Application
Object Reference

Container:

 Container is object/Components which manages life cycle of other objects


 Example: Servlet container, ejb container, jms container, Spring container etc..............

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.

1. Bean Factory Container/ Bean Factory (Interface):

 Bean Factory is not suitable for web application


 Bean Factory does not support Accept Oriented Programming (AOP)

2. ApplicationContext Container/ ApplicationContext (Interface):

 ApplicationContext is suitable for web application


 ApplicationContext supports Accept Oriented Programming (AOP)

3. WebApplicationContext Container/ WebApplicationContext (Interface):


How to create Maven Project in eclipse?

Ans. Ctrl+N -------write on Wizards: Maven---------select--------Maven Project--------Next>------Next>---------in Filter: -----search----

------org.apache.maven.archetypes---------Select ArtifactId---(maven-archetypes-quickstart) version-1.4--------

-----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>

9. paste in pom.xml file between <dependencies> </dependencies>


--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Create Maven Project: makemytrip

View of the Project


Create: spring-web.xml file

How to create spring-web.xml file ?

Select---src/main/java----right click----New----Other----Wizards: XML File-----select-----XML File-----Next>---

------File name: spring-web.xml------Finish

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">

<bean id ="bookticket" class="com.jspider.makemytrip.BookTicket"></bean>


</beans>

Here configuration is done under tag <beans></beans>

Here Object is created of class in <bean id="bookticket" class="com.jspider.makemytrip.BookTicket"></bean>

BookTicket.java

package com.jspider.makemytrip;

public class BookTicket {

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

<dependencies> <dependency> </dependency> </dependencies>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-dao -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</version>
</dependency>

App.java
package com.jspider.makemytrip;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App


{
public static void main( String[] args )
{
//BookTicket bookTicket = new BookTicket();
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-web.xml");
BookTicket bookTicket = context.getBean(BookTicket.class);
bookTicket.book();
}
}

ClassPathXmlApplicationContext: It will load the configuration file i.e. spring-web.xml

getBean(BookTicket.class): It get object reference of the particular class that is mentioned in spring-web.xml

Run As---1JavaApplication

Console:

May 26, 2023 5:29:23 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh


INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4bf558aa: startup date
[Fri May 26 17:29:23 IST 2023]; root of context hierarchy
May 26, 2023 5:29:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-web.xml]
BookTicket Object Created
Ticket booked
ClassPathXmlApplicationContext:

 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

5 type of scope in Spring framework:


1. singleton: It give only one Object Reference and it is default scope
2. prototype: It give multiple Object Reference
3. request: used in servlet base application
4. session: used in servlet base application
5. global: portal application Example: Naukari.com, Linkdine.com
Create Maven Project or update makemytrip project

Add dependency in 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>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-dao -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</version>
</dependency>
View of the Project

BookTicket.java
package com.jspider.makemytrip;

public class BookTicket {

private String ticketNumber;


private String name;
private String from;
private String destination;
private PassengerDetails passengerDetails;

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");
}

public String getTicketNumber() {


return ticketNumber;
}
public void setTicketNumber(String ticketNumber) {
this.ticketNumber = ticketNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public PassengerDetails getPassengerDetails() {
return passengerDetails;
}
public void setPassengerDetails(PassengerDetails passengerDetails) {
this.passengerDetails = passengerDetails;
}
@Override
public String toString() {
return "BookTicket [ticketNumber=" + ticketNumber + ", name=" + name + ", from=" + from + ",
destination="+ destination + ", passengerDetails=" + passengerDetails + "]";
}
}

We can initialize properties (data members or data variable) in two ways:

1. By Constructor initialization
2. By Setter Method initialization

Setter Method initialization: the above program BookTicket.java

Constructor initialization: the below program PassengerDetails.java


PassengerDetails.java
package com.jspider.makemytrip;

import java.util.List;

public class PassengerDetails {


private int id;
private String name;
private String city;
private List<String> idProofList;
private String idNumber;

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">

<bean id="bookticket" class="com.jspider.makemytrip.BookTicket" scope="prototype">


<property name="ticketNumber" value="IND1234"></property>
<property name="name" value="kiran"></property> Initialization of object through
<property name="from" value="Banglore"></property> Setter method by passing a
<property name="destination" value="chennai"></property>
argument value
<property name="passengerDetails" ref="pDetails"></property>
</bean>

<bean id="pDetails" class="com.jspider.makemytrip.PassengerDetails">


<constructor-arg name="id" value="1234"></constructor-arg>
<constructor-arg name="name" value="ramesh"></constructor-arg>
<constructor-arg name="city" value="mysore"></constructor-arg>
<constructor-arg name="idProofList">
<list>
<value>Aadhar</value>
<value>Voter</value> Passing List type argument
<value>Passport</value>
</list>
</constructor-arg>
<constructor-arg name="idNumber" value="123456"></constructor-arg>
</bean>
</beans>

Initialisation of object through Constructor by


passing argument value
App.java
package com.jspider.makemytrip;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {


public static void main( String[] args ){

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-web.xml");


BookTicket bookTicket = context.getBean(BookTicket.class);
BookTicket bookTicket1 = context.getBean(BookTicket.class);
BookTicket bookTicket2 = context.getBean(BookTicket.class);
bookTicket.book();
System.out.println(bookTicket);

PassengerDetails passengerDetails = context.getBean(PassengerDetails.class);


System.out.println(passengerDetails);
}
}
Run As --- 1JavaApplication
Console:
May 27, 2023 10:20:11 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4bf558aa: startup date [Sat May 27 10:20:11 IST
2023]; root of context hierarchy
May 27, 2023 10:20:11 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-web.xml]
BookTicket Object Created
BookTicket Object Created
BookTicket Object Created
Ticket booked
BookTicket [ticketNumber=IND1234, name=kiran, from=Banglore, destination=chennai, passengerDetails=PassengerDetails [id=1234,
name=ramesh, city=mysore, idProofList=[Aadhar, Voter, Passport], idNumber=123456]]
PassengerDetails [id=1234, name=ramesh, city=mysore, idProofList=[Aadhar, Voter, Passport], idNumber=123456]

If remove the scope from spring-web.xml file then:


Run As --- 1JavaApplication
Console:
May 27, 2023 10:22:32 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4bf558aa: startup date [Sat May 27 10:22:32 IST
2023]; root of context hierarchy
May 27, 2023 10:22:32 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-web.xml]
BookTicket Object Created
Ticket booked
BookTicket [ticketNumber=IND1234, name=kiran, from=Banglore, destination=chennai, passengerDetails=PassengerDetails [id=1234,
name=ramesh, city=mysore, idProofList=[Aadhar, Voter, Passport], idNumber=123456]]
PassengerDetails [id=1234, name=ramesh, city=mysore, idProofList=[Aadhar, Voter, Passport], idNumber=123456]

 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

There are 2 ways to initialize a Bean class:


1. Constructor initialization
2. Setter Initialization
Constructor initialization:
If a Bean class is initialised using Constructor it is referred as Constructor initialization.
<constructor-arg name="id" value="1234"></constructor-arg>

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

2. Prototype: It will create multiple object of Spring bean

3. Request: It will create a bean Object for each Http request

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

View of the Project


Add dependency in 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>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-dao -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</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">

<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 {

<context:component-scan base-package="com.jsp.makemytrip1"></context:component-scan>:This is present in spring-


web.xml (i.e. Configuration file).

This both work in similar way: It will Scan the @Component annotation class which will create Object of that class

@ComponentScan(basePackages= "com.jsp.makemytrip1"):This is present in AppConfiguration.java (i.e. Configuration file in


java Configuration ). AppConfiguration is configuration class because of @Configuration

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;

public class App {


public static void main(String[] args) {

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-web.xml");


}
}

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;

public class App {


public static void main(String[] args) {

// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-web.xml");

// AnnotationConfigApplicationContext applicationContext =new AnnotationConfigApplicationContext(AppConfiguration.class);


// or
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(AppConfiguration.class);
applicationContext.refresh();
}
}
This will execute AppConfiguration class and it will not execute spring.web.xml

Console:

May 27, 2023 11:44:20 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh


INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7591083d:
startup date [Sat May 27 23:44:20 IST 2023]; root of context hierarchy
Hotel Object Created
Payment object created
Note: Always try to avoid or minimize .xml file in your project as much as possible

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

Console: same as pervious output.

May 28, 2023 10:27:24 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh


INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7591083d:
startup date [Sun May 28 22:27:24 IST 2023]; root of context hierarchy
Hotel Object Created
Payment object created
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Create Maven Project or Update ---- makemytrip1

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;

@Value(value = "Banglore") To achieve dependency injection we use @Autowired


private String city; What is dependency injection? ---dependency injection means if
@Value(value = "India") Hotel class required reference of Payement class then it is called
private String country; dependency Injection
@Value(value = "563007") Injection--- reference
private String pincode; To achieve we use @Autowired
@Autowired
private Payment payment;

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;
}

public void setName(String name) {


this.name = name;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public String getCountry() {


return country;
}

public void setCountry(String country) {


this.country = country;
}

public String getPincode() {


return pincode;
}

public void setPincode(String pincode) {


this.pincode = pincode;
}

@Override
public String toString() {
return "Hotel [name=" + name + ", city=" + city + ", country=" + country + ", pincode=" + pincode + ", payment="
+ payment + "]";
}

public Payment getPayment() {


return payment;
}

public void setPayment(Payment payment) {


this.payment = payment;
}
}
Payment.java
package com.jsp.makemytrip1.javaconfiguration;

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 = "debit card")


private String modeOfPayement;

@Value(value = "success")
private String status;

public Payment(int id, Double amount, String modeOfPayement, String status) {


super();
this.id = id;
this.amount = amount;
this.modeOfPayement = modeOfPayement;
this.status = 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;

public class App {


public static void main(String[] args) {

// ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-web.xml");

// AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfiguration.class);


// or
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(AppConfiguration.class);
applicationContext.refresh();

Hotel hotel = applicationContext.getBean(Hotel.class);


System.out.println(hotel);
}
}

spring-web.xml (This is not required for execution)

<?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.jsp.makemytrip1"></context:component-scan>
<!-- base package means common name for all the package in the project -->

</beans>

Add dependency on pom.xml file

Run As---1JavaApplication

Console:

May 29, 2023 10:30:00 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh


INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@7591083d:
startup date [Mon May 29 10:30:00 IST 2023]; root of context hierarchy
Hotel Object Created
Payment object created
Executing intialize()...!
Hotel [name=Taj, city=Banglore, country=India, pincode=563007, payment=Payment [id=12345, amount=2500.0,
modeOfPayement=debit card, status=success]]
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
IOC (Inversion of control):
Spring Container
Manages Component (Object):
C---Create
I---Initialise
D---Destroy

Spring Core
Information
/
Configuration

Object Reference

Application

IOC is a process of inverting a control to an External entity

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Dependency Injection (Required Reference):

 It is a process of injecting the required contain into a class is known as Dependency Injection.

IOC (Inversion of Control):

 IOC is a process of inverting a control to an external entity.


 Spring Framework is an implementation of IOC

@Component: This annotation is used to create an Object of a class

@Configuration: This annotation indicate the class declares one or more bean method and has to processed by Spring Container

@Bean: Annotated method tells Spring that method returns an Object

@PostConstruct: Annotated method will be invoked after Object has been created

@Scope: It is used to set a scope to a particular class


Spring Web Module:

 It is use to develop web application or enterprise application


 It is implementation MVC architecture
 It is a solution Servlet Web application

(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

View of the Project (spingframeworks)


Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>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>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-dao -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</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">

<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");
}

@RequestMapping(value="/saveRegisterDetails", method = RequestMethod.POST)


public ModelAndView saveRegisterDetails(RegisterDto registerDto) {
System.out.println(registerDto);
return new ModelAndView("home.jsp");
}
}
RegisterDto.java
package com.sourabhsuman.springframeworks.dto;

import java.io.Serializable;

public class RegisterDto implements Serializable {

private String name;

private String email;

private String mobileNumber;

private String country;

private String password;

private String dateOfBirth;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getMobileNumber() {


return mobileNumber;
}

public void setMobileNumber(String mobileNumber) {


this.mobileNumber = mobileNumber;
}

public String getCountry() {


return country;
}

public void setCountry(String country) {


this.country = country;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public String getDateOfBirth() {


return dateOfBirth;
}

public void setDateOfBirth(String dateOfBirth) {


this.dateOfBirth = dateOfBirth;
}

@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>

index.jsp(This not required in this project)

<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

Spring Web MVC Flow (By Teacher):


MVC (Model View Controller) ARCHITECTURE: (Why we use MVC ARCHITECHURE? Because it support lose coupling)

VIEW Controller Model


[UI Logic] [Request processing logic, navigation logic] Service Repository
[Validation logic, business logic] [Data Base Logic]

HTML Servlet JMS JDBC

CSS Spring Web Web Service JPA

JS Struts Validation Mongo DB

ANGULAR JSF EJB ORM etc

REACT Rabbit Mq etc...

JQUERY etc.

Controller layer @Controller

Service Layer @Component @Service

Repository Layer @Repository

 @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

Overview Of the Project(springframeworks)


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>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 -->

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">


<property name="configLocations" value="classpath:/hibernate.cfg.xml"></property>
</bean>
<!-- It provide the session factory -->

</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");
}

@RequestMapping(value="/saveRegisterDetails", method = RequestMethod.POST)


public ModelAndView saveRegisterDetails(RegisterDto registerDto) {
System.out.println(registerDto);
registerService.saveRegisterDetailsservice(registerDto);
return new ModelAndView("home.jsp");
}
}
RegisterService.java
package com.sourabhsuman.springframeworks.service;

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;

public void saveRegisterDetailsservice(RegisterDto dto) {


registerDao.saveRegisterDetailsDao(dto);
}
}
RegisterDao.java
package com.sourabhsuman.springframeworks.repository;

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;

public void saveRegisterDetailsDao(RegisterDto dto) {


// Configuration cfg = new Configuration();
// cfg.configure();
// SessionFactory sessionFactory=cfg.buildSessionFactory();

Session session = sessionFactory.openSession();


Transaction transaction = session.beginTransaction();
session.save(dto);
transaction.commit();
}
}

This code is reduced because of written in spring-web.xml:


<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocations" value="classpath:/hibernate.cfg.xml"></property>
</bean>

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;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getMobileNumber() {


return mobileNumber;
}

public void setMobileNumber(String mobileNumber) {


this.mobileNumber = mobileNumber;
}

public String getCountry() {


return country;
}

public void setCountry(String country) {


this.country = country;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public String getDateOfBirth() {


return dateOfBirth;
}

public void setDateOfBirth(String dateOfBirth) {


this.dateOfBirth = dateOfBirth;
}

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}
@Override
public String toString() {
return "RegisterDto [id=" + id + ", name=" + name + ", email=" + email + ", mobileNumber=" + mobileNumber
+ ", country=" + country + ", password=" + password + ", dateOfBirth=" + dateOfBirth + "]";
}
}
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.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>

index.jsp (Not required in this project)


<html>
<body>
<h2>Hello World!</h2>
</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

Add dependency in : pom.xml file


<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-dao -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</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 Server Raw Data SBI Server

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

All Rest web services are nothing but an API.

There are two Types of REST Web Services:


1. SOAP (Simple Object Access Protocol)
2. REST (REpresentational State Transfer)

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

Characteristics of Web service:


 Communication between two application over the Internet
 In order to communicate between two applications we make use of http method
 The Data which is exchanged between two application must be in a common format which is understandable for both
applications Example: JSON, XML etc
 For every request made in response we will be getting only raw data instead of entire HTML page

Guideline of REST:
 Resource based URI
 Uniform or Common Interface
 Metadata
 Statelessness: It will send only raw data

POSTMAN is used for REST WEB Services.


Search in Google—POSTMAN Chrome Plug-in

For OPERATION:
CREATE-------POST
READ---------GET
UPDATE-----PUT
DELETE-----DELETE

Status: if do operation i.e. Metadata


 200(series) --- success
 500(Series)----Server Error
 400(series)---- Resource not found
Create Spring MVC Maven Project or update the Maven project: springframeworks

Overview of the Project

Overview of the Project


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 -->

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">


<property name="configLocations" value="classpath:/hibernate.cfg.xml"></property>
</bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<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>
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="/saveRegisterDetails", method = RequestMethod.POST)


public ModelAndView saveRegisterDetails(Register registers) {
System.out.println(registers);
registerService.saveRegisterDetailsservice(registers);
return new ModelAndView("home.jsp");
}

@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;

//@RequestMapping(value="/getUsers", method = HttpMethod.GET)


@GetMapping(value="/getUsers")
public@ResponseBody List<Register> getUsers() {
return registerService.getRegisterDetails();
}

@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.

@RestController = @Controller + @ResponseBody


@ResponseBody ---- Annotation that indicates a method return value should be bound to the web response body.
@PathVariable------- Annotation which indicates that a method parameter should be bound to a URI template variable.
@GetMapping ----- Annotation for mapping HTTP GET requests onto specific handler methods.
@PostMapping----- Annotation for mapping HTTP POST requests onto specific handler methods.
RegisterService.java
package com.sourabhsuman.springframeworks.service;

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;

public void saveRegisterDetailsservice(Register register) {


registerDao.saveRegisterDetailsDao(register);
}

public List<Register> getRegisterDetails(){


return registerDao.getRegisterDetails();
}

public Register getRegisterDetailsById(Long id) {


return registerDao.getRegisterDetailsById(id);
}

public boolean loginValidation(Login login) {


String email = login.getEmail();
Register register = registerDao.getRegisterDetailsByEmail(email);

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;

public void saveRegisterDetailsDao(Register register){


// Configuration cfg = new Configuration();
// cfg.configure();
// SessionFactory sessionFactory=cfg.buildSessionFactory();

Session session = sessionFactory.openSession();


Transaction transaction = session.beginTransaction();
session.save(register);
transaction.commit();
}

public List<Register> getRegisterDetails() {


Session session = sessionFactory.openSession();
String hql = "from Register";
Query query = session.createQuery(hql);
return query.list();

public Register getRegisterDetailsById(Long id) {


Session session = sessionFactory.openSession();
String hql = "from Register where id=:i";
Query query = session.createQuery(hql);
query.setParameter("i",id);
return (Register) query.uniqueResult();
}

public Register getRegisterDetailsByEmail(String email) {


Session session = sessionFactory.openSession();
String hql = "from Register where email=:e";
Query query = session.createQuery(hql);
query.setParameter("e",email);
return (Register) query.uniqueResult();
}

}
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;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public String getMobileNumber() {


return mobileNumber;
}

public void setMobileNumber(String mobileNumber) {


this.mobileNumber = mobileNumber;
}
public String getCountry() {
return country;
}

public void setCountry(String country) {


this.country = country;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public String getDateOfBirth() {


return dateOfBirth;
}

public void setDateOfBirth(String dateOfBirth) {


this.dateOfBirth = dateOfBirth;
}

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

@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;

public class Login implements Serializable {

private String email;


private String password;
public Login() {
super();
// TODO Auto-generated constructor stub
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
AppConfiguration.java
package com.sourabhsuman.springframeworks.configuration;

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

<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->


<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-dao -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.32</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->


<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.8</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->


<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.8</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->


<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->


<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.modelmapper/modelmapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>3.1.0</version>
</dependency>
Create Database i.e. springframeworks and table name: user_register and Column name as given below:

Run As---Run on Server


If correct Email and Password is given then:

If incorrect Email or Password is given then:


Now through Postman(Through RESTFULL web Service or REST web services)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ServletIntializer.java
package com.sourabhsuman.springframeworks1.configuration;

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;

public class ServletIntializer implements WebApplicationInitializer{


@Override
public void onStartup(ServletContext servletContext) throws ServletException {

AnnotationConfigWebApplicationContext config=new AnnotationConfigWebApplicationContext();

config.register(AppConfiguration.class);

DispatcherServlet servlet = new DispatcherServlet(config);


Dynamic context = servletContext.addServlet("dispacther Servlet", servlet);
context.addMapping("/");
context.setLoadOnStartup(1);
}
}

ServletIntializer.java (The above Program) will remove <servlet></servlet> and <servlet-mapping></servlet-mapping> in


web.xml file

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<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() {

DriverManagerDataSource source = new DriverManagerDataSource();


source.setDriverClassName("com.mysql.cj.jdbc.Driver");
source.setUrl("jdbc:mysql://localhost:3306/movie");
source.setPassword("root");
source.setUsername("root");
return source;
}

@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();
}
}

AppConfiguration.java will remove spring-web.xml and hibernate.cfg.xml

Note: Always try to avoid .xml files as much as possible

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

You might also like