Spring Part 3
Spring Part 3
RAGHU [PART-3]
SPRING
FRAMEWORK
by
Mr. RAGHU
[PART-III]
Spring Email API supports MIME Type Email Sending (Multipurpose Internet
Mail Extension). It means “Any kind of file as attachment”,
EX: Video, Audio, Text, Document, Images etc…
I.e shown as :
<dependency>
<groupId>org.springframework</groupId>
<artifectId>spring-context</artifectId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifectId>spring-context-support</artifectId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifectId>mail</artifectId>
<version>1.4</version>
</dependency>
EXAMPLE PROGRAM:-
CODE:
package com.app.config;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;
@Configuration
@ComponentScan(basePackages="com.app")
publicclass AppConfig {
//JavaMail Sender Impl
@Bean
public JavaMailSenderImpl mail() {
JavaMailSenderImpl mail = new JavaMailSenderImpl();
mail.setHost("smtp.gmail.com");
mail.setPort(587);
mail.setUsername("abc@gamil.com");//enter your
emailId.
mail.setPassword("12345");//enter ur password.
mail.setJavaMailProperties(props());
returnmail;
}
package com.app.util;
import javax.mail.internet.MimeMessage;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
@Component
publicclass AppMailSender {
@Autowired
private JavaMailSender mailsender;
3. Test Class:-
package com.app.test;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigAppli
cationContext;
import org.springframework.core.io.FileSystemResource;
import com.app.config.AppConfig;
import com.app.util.AppMailSender;
publicclass Test {
publicstaticvoid main(String[] args) {
//ApplicationContext ac = new
ClassPathXmlApplicationContext(AppConfig.class);
ApplicationContext act = new
AnnotationConfigApplicationContext(AppConfig.class);
AppMailSender mail = act.getBean("appMailSender",
AppMailSender.class);
FileSystemResource file = new
FileSystemResource("C:/Users/Ishaan/Desktop/ashu.jpg");
booleanflag = mail.sendEmail("ashuptn92@gmail.com",
"Hello", "Welcome To Spring Email", file);
if(flag) {
System.out.println("Done!!!");
}else {
System.out.println("Sorry!!!!");
}
}
}
4. pom.xml:-
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="
http://www.w3.org/2001/XMLSchema-
instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0
.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>Spring5JavaEmailAppEx</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-
support</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
OUTPUT:-
Successfully done….
NOTE:-
Example Code:-
(a) fixedDelay:-
It works based on period of time . Input must be milli seconds[1000mili sec = 1
sec]
On spring container startup, it will call method one , after completing method
execution , container wait for give delay then calls one more time. This process
is repeated until container is stopped.
Example:-
Consider above method takes 3 sec time to finish work then” time line” is
shown below,
(b)fixedRate:-
We can write code is
@Scheduled(fixedRate=1000) over method then max waiting time including
method execution time is 1sec.
If limit is crossed ,then once last method call is complete then next method call is
made without any gap[gap time=0].
If method has taken less time then given fixedRate wait
time is =fixedRate-method execution time.
CRON:-
It is an expression used to specify “Point of Time” or “Period of Time”, provided
by Unix Operating System and followed by spring scheduler also.
Formate is:-
0-59 0-59 0- 23 1-31 1-12 SUN-SAT
Sec min hrs day month weak
* * * * * *
Possible symbol used in expression are:-
* = any Symbol
? =any day/week
- = range
,=Possible values
/= Period of time
Ex#1 0 0 9 * * *
>> Every day morning 9 AM
Ex#2 0 0 9,21 * * *
>> Every day morning 9:00am and 9:00pm
Ex#3 0 30 8-10 * * *
>> Every day morning 8:30 AM ,10:30
Ex#4 0 0/15 16 * * *
>> Every day 4:00PM, with 15 gaps
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 12 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
Ex#5 15 * * * * *
>> every minute 15 sec only
>> like 9:10:15, next 9:11:15
Ex#6 */15 * * *
>> like 9:10:15, next 9:10:30>9:10:45
Ex#7 0 * 6,7 * * *
>> invalid expression
Ex#8 0 0 9 19 *
th st
>>Sep(9 month) 1 - 9:00:00am
Ex#9 59 59 23 31 12 ?
>> 31 DEC mid-night 11:59:59PM
Ex10 9 9 9 ? 6 ?
th
>> 6 month every day 09:09:09AM
Ex#11 0 0 6,19 * * *
>> 6:00AM and 7:00PM every day
Ex#12 0 0/30 8-10 * * *
>> 8:00, 8:30 , 9:00, 9:30, 10:00 and 10:30 every day
Ex#13 0 0 9-17 * * MON-FRI
>> on the hour nine-to-five week-days
EXAMPLE PROGRAM:-
Folder Structure:-
-----------------------------------CODE------------------------------------
1. AppConfig.java
package com.app.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import
org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@ComponentScan(basePackages="com.app")
publicclass AppConfig {
2. EmployeeReportGen.java
package com.app.bean.erport;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
publicclass EmployeeReportGen {
// 1000 milli Second = 1 Second
@Scheduled(fixedDelay=5000)
publicvoid genReport() {
System.out.println(new Date());
}
}
3. TestClass.java
package com.app.test;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigAppli
cationContext;
import com.app.config.AppConfig;
publicclass Test {
}
}
EXAMPLE DESIGN:-
4> After Returning:- This is after advice type but it is only called on
successful execution of b.method () only.
Execution order:-
b. method (); (if execution succesfully)
Advice- method ();
5> AfterThrowing Advices:This is after advice type but it is only called on
fail/exception execution of b.method () only.
Execution order:-
b. method (); (if throw execution)
Advice- method ();
Example:-
Folder Structure :-
CODE :-
1. LoggingAspect.java:-
package com.app.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
publicclass LoggingAspect {
@Before("point1()")
publicvoid showLog() {
System.out.println("I m from Before Advice()");
}
}
2. EmployeeService.java:-
package com.app.component;
import org.springframework.stereotype.Service;
@Service
publicclass EmployeeService {
publicvoid showMsg() {
System.out.println("Hello I m from Business
Methos()");
}
}
3. AppConfig.java:-
package com.app.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import
org.springframework.context.annotation.EnableAspectJAutoProx
y;
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages="com.app")
publicclass AppConfig {
4. Test.java:-
package com.app.test;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.annotation.AnnotationConfigAppli
cationContext;
import com.app.component.EmployeeService;
import com.app.config.AppConfig;
publicclass Test {
RT(Return type)
PMTRS(Parameters)
Consider below business class method
1. +getData(int): void
2. +get(): void
3. +get(double): String
4. +getModel():String
5. +getFormate(int): void
6. +set(): void
7. +setData(int): void
8. +set (double): String
9. +setModel():String
10. +setFormat(int): void
-------------------Point Cut Expression------------
1>>Public * get(..)
Result:Here two dots(..) indicates any number of parameters in any
order and * in place of return type indicates any return type is
accepted.
Selected method:-- 2,3
2>> public void * t*()
Result :-- method name should contain one letter ’t’ nay place
(starting/ending/middle ) and must have zero param and void type method
Selected method :------> 5,6,7,2
3>> public * *()
Selected method:--> 2,4,7,9
4>> public String *Data(..)
Selected method--> No method selected
5>> public * get *()
Selected method-->2,4
6>> public * get(..)
Selected method-->2
Selected method-->2,3
7>> public int *et(..)
Selected method-->not matched
8>>public void *o*()
Selected method-->
9>>public String *(..)
Selected method-->3,4,8,9
10>>public * *(..)
Selected method-->All method are selected.
#3: Define Spring Configuration file (XML / JAVA) To Enable AOP Program.
#4: Write one Test class to call only Business Method .
***Expected output :Advice must be called automatically.
# EXAMPLE CODE :-
#1:Create one simple maven project.
Details:
Group-Id : org.sathyatech
Artifect-Id : Spring5AOPEx1
Version : 1.0
#2:AddSpring and Aspects Dependencies for jars download.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
#3:Update Maven Project (alt+F5)
#4: Create one java config file under src/main/java folder.
----------------AppConfig.java------------------
Package com.app.config;
//ctrl+shift+o(imports)
@EnableAspectJAutoProxy
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 24 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
@Configuration
@ComponentScan(basePackages="com.app")
publicclass AppConfig { }
publicvoid showMsg() {
System.out.println("Hello I M from Business
Method...");
}
}
@Before("point1()")
publicvoid showLogA() {
System.out.println("From Before Advice");
}
@After("point1()")
publicvoid showLogB() {
System.out.println("From After Advice");
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 25 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
}
}
}
}
Example #2:- Types of Advices Example
All files are same as above example only aspect is different.
package com.app.aspect;
// ctrl+shift+o(imports)
@Aspect
@Component
Public class LoggingAspectC {
@Pointcut (“execution(public * s*(..))”)
public void point1() { }
@AfterReturning(pointcut=”point1()”, returning=”ob”)
3. For last level package if we provide two dots “pack..” then it indicates current
package and all it’s sub package classes are selected.
EX: com.app..*.*()
Here app package classes and all it’s sub package classes. (not super package)
4. Symbol ‘*’indicates any (package, class,method or return type).
5. Symbol ‘ .. ’ (dot dot) can be used for current and sub package classes and
any parameter type.
## Consider above all classes having below all methods (methods in every
classes).
1. +getData(int):void
2. +get():void
3. +getModel():String
4. +getCode():String
5. +get(double):int
6. +getModel(int):int
7. +set():void
8. +setModel():String
9. +setCode(int):String
10.+set(double):int
#1. Expression
public * com.*.*.*.*()
classes(4) X method(4)
W,D,E,G | 2,3,7,8
Total = 16.
#2. Expression
#3. Expression
#4. Expression
public int com.*.*..*.set()
classes (8) X method (0)
W,D,E,F,R,S,K,L | 0
Total = 0.
#5. Expression
public * com.*.*.*.*.*.*et()
classes (3) X method (2)
K,L,R | 2,7
Total = 6.
#7. Expression
public void com..*.set()
classes (13) X method (1)
All classes | 7
Total = 13.
#8. Expression
public * *..*.*(..)
classes (13) X method (10)
All classes | 10
Total = 130;
# Pointcut Joins:-
One advice can be connected to multiple pointcuts using AND AND(&&) OR OR
(||) symbols.
EX#1:-
@Pointcut (“execution (_________)”)
public void p1() { }
@Pointcut(“execution (_________)”)
Public void p2() { }
Here p1, p2 are two Pointcuts then we can write as p1() && p2().
P1() || p2() for a JoinPoint (Advice)
EX#2:-
P1() ----- within (com.app..*)
P2() ----- args(int)
Advice -- p1() && p2()
A method which exist in class that is available in app package and method
must have int param is selected and connected with advice.
GET @GetMapping
POST @PostMapping
PUT @PutMapping
DELETE @DeleteMapping
PATCH @PatchMapping
NOTE :-
1. @RestController :- [Spring 4.x]
It is a 5th StereoType Annotation ie which detect the class and creates the
object in Spring Container.
It must be applied on class level.
It internally follows @Controller and @RestController
2. ResponseEntity<T> :-
It is a class provide by spring ReST API. It is used as method return type which
should contain body (GenericType) and HttpStatus (enum).
3. @RequestMapping :-
It is used to provide path(URL) at class / method level. class level it is optional.
4. Method Level,
Path and HttpMethod Type can be provided using HttpType Annotations using
@XXXMapping,
Ex :- @GetMapping, @PostMapping … etc.
Step#4:-
Update maven project (alt+F5)
>Right click on project > maven
>update project.
Step#5:-
Write code in below order under src/main/java folder, also delete web.xml and
index.jsp file.
-------------------------------Folder Structure-----------------------------
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-
xml</artifactId>
<version>2.9.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-
plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. AppConfig.java:-
package com.app.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import
org.springframework.web.servlet.config.annotation.EnableWebM
vc;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.app")
publicclass AppConfig {
3. AppInit.java:-
package com.app.init;
import
org.springframework.web.servlet.support.AbstractAnnotationCo
nfigDispatcherServletInitializer;
import com.app.config.AppConfig;
@Override
protected Class<?>[] getRootConfigClasses() {
returnnew Class[] {AppConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
returnnull;
}
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 41 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
@Override
protected String[] getServletMappings() {
returnnew String[] {"/*"};
}}
4. EmployeeRestController.java:-
package com.app.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/employee") // Optional
publicclass EmployeeRestController {
// Method
// HttpMethod + Method URL
@GetMapping("/show")
public ResponseEntity<String> showMsgA(){
String body = "Welcome To GET Method Spring Rest Appication!!";
HttpStatus status = HttpStatus.OK;
ResponseEntity<String>entity = new
ResponseEntity<String>(body,status);
returnentity;
}
@PostMapping("/show")
public ResponseEntity<String> showMsgB(){
String body = "Welcome To POST Method Spring Rest Appication!!";
HttpStatus status = HttpStatus.OK;
ResponseEntity<String>entity = new
ResponseEntity<String>(body,status);
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 42 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
returnentity;
}
@PutMapping("/show")
public ResponseEntity<String> showMsgC(){
String body = "Welcome To PUT Method Spring Rest Appication!!";
HttpStatus status = HttpStatus.OK;
ResponseEntity<String>entity = new
ResponseEntity<String>(body,status);
returnentity;
}
@DeleteMapping("/show")
public ResponseEntity<String> showMsgD(){
String body = "Welcome To DELETE Method Spring Rest
Appication!!";
HttpStatus status = HttpStatus.OK;
ResponseEntity<String>entity = new
ResponseEntity<String>(body,status);
returnentity;
}
}
# Running on server:
Run as > run on server
http://localhost:2022/Spring5RestConsumerAppPart1/employee/show
OUTPUT ON BROWSER:-
-------------------------POSTMAN SCREEN----------------------------------
version : 1.0
>Finish.
2. Open pom.xml and provide jars and build plugins.
3. Update Maven Project (alt+F5)
> Right click on project > Maven
> update project.
4. Create one class “ClientTest” under src/main/java Folder.
Coding Steps are:-
a. Create object to RestTemplate
b. Create String (Provider) URL
c. Make call (as HTTPRequest)
d. Get Response in ResponseEntity
e. Print or use result (body / status)
FOLDER STRUCTURE:-
Example Code:
1. pom.xml
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 45 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
<projectxmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech.app</groupId>
<artifactId>Spring5ConsumerApp</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-
xml</artifactId>
<version>2.9.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-
plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<finalName>SpringRestProvider</finalName>
</build>
</project>
2. ConsumerTest.java
package com.app.test;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
publicclass ConsumerTest {
OUTPUT:-
Welcome To GET Method Spring Rest Appication!!
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 47 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
OK
200
<web-app>
<servlet>
<servlet-name>sample</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
a. Activation of annotations
Request Header should also have Header key “Accept” (with JSON/XML) which
indicates what type of response Body is expected by consumer.
To enable JSON conversion in ReST in pom.xml
Add dependency :
Artifect-Id : Jackson-databind
(or any it’s equal )
To enable XML conversion in ReST,
In pom.xml add dependency :
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 49 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
Artifect-Id : Jackson-dataformat-xml
(or any it’s equal)
CASE#3:-
Provider supports JSON only Request Body JSON. Then HttpStatus 200 OK.
Example Code:-
1. Pom.xml
<projectxmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech.app</groupId>
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 51 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
<artifactId>Spring5RestProviderUsingXMLConPart-II</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>Spring5RestProviderUsingXMLConPart-II MavenWebapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.app.model;
publicclass Employee {
privateintempId;
private String empName;
privatedoubleempSal;
public Employee() {
super();
}
publicint getEmpId() {
returnempId;
}
publicvoid setEmpId(intempId) {
this.empId = empId;
}
publicdouble getEmpSal() {
returnempSal;
}
publicvoid setEmpSal(doubleempSal) {
this.empSal = empSal;
}
@Override
public String toString() {
return"Employee [empId=" + empId + ", empName=" +
empName + ", empSal=" + empSal + "]";
}
3. EmployeeRestController class:
package com.app.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;
import com.app.model.Employee;
@RestController
@RequestMapping("/employee")
public class EmployeeRestController {
@PostMapping("/data")
public ResponseEntity<Employee> processData(@RequestBody Employee emp){
emp.setEmpSal(emp.getEmpSal()*4);
ResponseEntity<Employee> entity = new ResponseEntity<Employee>(emp,
HttpStatus.OK);
return entity;
}
4. Web.xml file:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns: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"id="WebApp_ID"version="3.1">
<servlet>
<servlet-name>sample</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</ser
vlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sample</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
5. Sample-servlet.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/con
text"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schem
a/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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
</beans>
Code Sample :-
HttpHeaders headers = new HttpHeaders();
Headers.add(“Content-Type”, “__________”);
Headers.add(“Accept”, “__________”);
2. Create HttpEntity with two parts Body(String) and headers(HttpHeaders).
Code Sample :-
HttpEntity<String> entity = new HttpEntity<String>();
--------------------------------DESIGN----------------------------------
Example Program :-
Folder Structure :-
CODE :-
1. Pom.xml :-
<projectxmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech.app</groupId>
<artifactId>Spring5ConsumerPart-II</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-
xml</artifactId>
<version>2.9.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-
plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<finalName>Spring5RestProviderUsingXMLConPart-
II</finalName>
</build>
</project>
2. ConsumerTest.java :-
package com.app.test;
import org.springframework.http.HttpEntity;
importorg.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
publicclass ConsumerTest {
// 1. Add Header
HttpHeadersheaders = newHttpHeaders();
//headers.add("Content-Type", "application/json");
headers.add("Content-Type", "application/xml");
headers.add("Accept", "application/json");
// 2. Entity
HttpEntity<String>he = new HttpEntity<String>(body,
headers);
##Destination :-
It is a memory created in MOM to hold messages. It is two types based
on Communications.
#) Queue :-
It is used to hold message in case of P2P Communication. It must be
identified using one name Ex: myqueue12.
#) Topic :-
It is used to hold message given by Producer, this message will be
broadcasted to (given to multiple) Consumers . one message multiple
copies are created in memory.
---------------------------Coding Steps------------------------------------------------
# Spring JMS :-
Spring JMS reduces coding lines provided by SUN JMS, using Template
Design Pattern given as JMSTemplate.
# JmsTemplate :-
This Template supports for both Consumer and Producer but mainly
used for Producer.
#2:in pom.xml add dependencies for spring context, spring jms, spring ActiveMQ
and build plugins for maven compiler.
Folder System:-
CODE :-
1. Pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>Spring5JMSProvider</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-spring</artifactId>
<version>5.15.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. AppConfig:-
package org.sathyatech.app.config;
import javax.jms.ConnectionFactory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsTemplate;
@Configuration
@Bean
public ConnectionFactory connectionFactory() {
ActiveMQConnectionFactory cf=new
ActiveMQConnectionFactory();
cf.setBrokerURL("tcp://localhost:61616");
return cf;
}
@Bean
public JmsTemplate jmsTemplate() {
JmsTemplate jt=new JmsTemplate();
jt.setConnectionFactory(connectionFactory());
return jt;
}
3. Test class:-
package org.sathyatech.app.test;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import org.sathyatech.app.config.AppConfig;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
@Override
public Message createMessage(Session ses) throws
JMSException {
return ses.createTextMessage("SAMPLE ONE");
}
});
c.close();
}
}
Here (Client) Consumer Application make call to MOM (using schedulers with
gap of 5000 mili sec = 5 sec by default).
--------------------------------------Execution Flow-----------------------------------
Example Program :-
1. Pom.xml:-
<projectxmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech.app</groupId>
<artifactId>Spring5JMSMavenProviderConsumer</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.15.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-
plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. AppConfig.java:-
package com.app.config;
import javax.jms.ConnectionFactory;
import javax.jms.MessageListener;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 75 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.jms.listener.MessageListenerContainer;
@Configuration
@EnableJms
@ComponentScan(basePackages="com.app")
publicclass AppConfig {
@Autowired
private MessageListener messageListener;
@Bean
public ConnectionFactory connectionFactory() {
ActiveMQConnectionFactory c=new ActiveMQConnectionFactory();
c.setBrokerURL("tcp://localhost:61616");
returnc;
}
@Bean
public MessageListenerContainer listenerContainer() {
DefaultMessageListenerContainer m=new
DefaultMessageListenerContainer();
m.setConnectionFactory(connectionFactory());
m.setDestinationName("my-test-spring");
m.setMessageListener(messageListener);
returnm;
}
}
3. MyMessageListener.java:-
package com.app.listener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 76 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
import org.springframework.stereotype.Component;
@Component
publicclass MyMessageListener implements MessageListener{
@Override
publicvoid onMessage(Message message) {
TextMessage tm=(TextMessage) message;
try {
System.out.println(tm.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
4. Test.java:-
package com.app.test;
import
org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.app.config.AppConfig;
import com.app.listener.MyMessageListener;
publicclass Test {
# EXECUTION STEPS #:
Authentication :
Work on store and retrieve use identity details like username , password , role it
will compare only name and password not role with end user input.
Authorization :
It will security work on login and role management of application using JAAS.
Spring security works on login and role management of application using
JAAS.
Security is provided to URL using managers.
a. Authentication Manager.
b. Authorization Manager.
a) Authentication Manager:
It will store details of user in RAM on DB and verifies when user try to login.
Types of Authentication
1. InMemoryAuthentication
Storing details in RAM.
2. JdbcAuthentication
Storing details (un ,pwd , role) in DB using JDBC.
3. UserDetailsService:
Storing details (un ,pwd , role) in DB using ORM.
b) AuthorizationManager:
It will provide details of URL’s “who can access what URL? “ provided types
as:
1. permitAll
Step 1:write one web application using WEB-MVC with multiple URL method.
Step 2:write on spring config file to provide authentication and authorization
manager details
EX:SpringSecurity which should extends class WebSecurityConfigurerAdapter and
Override 2 method.
Step 3:use any password encoder for securing password
a. NoOperationPwdEncoder
b. BCryptPasswordEncoder. (Binary Cryptography) etc.
Step 4:Enable security filter by writing one class. That extends
“AbstractSecurityWebApplicationInitializer”
1. InMemoryAuthentication
It will store data in RAM , it is used only for testing process , if DB is not
installed in system. This is best way to test application.
SETUP
1. pom.xml
<projectxmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sathyatech</groupId>
<artifactId>SpringSecurityInMemoryAthentication</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringSecurityInMemoryAthenticationMavenWebapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.ComponentScan;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.Import;
import
org.springframework.security.crypto.bcrypt.BCryptPasswordEnc
oder;
importorg.springframework.web.servlet.config.annotation.Enab
leWebMvc;
import
org.springframework.web.servlet.view.InternalResourceViewRes
olver;
@Configuration
@ComponentScan(basePackages = "com.app")
@Import(SecurityConfig.class)
@EnableWebMvc
publicclassAppConfig {
@Bean
publicBCryptPasswordEncoderpwdEncoder() {
returnnewBCryptPasswordEncoder();
}
@Bean
publicInternalResourceViewResolverivr() {
InternalResourceViewResolverivr =
newInternalResourceViewResolver();
ivr.setPrefix("/WEB-INF/views/");
ivr.setSuffix(".jsp");
returnivr;
}
}
importorg.springframework.beans.factory.annotation.Autowired
;
importorg.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authenticatio
n.builders.AuthenticationManagerBuilder;
import
org.springframework.security.config.annotation.web.builders.
HttpSecurity;
import
org.springframework.security.config.annotation.web.configura
tion.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configura
tion.WebSecurityConfigurerAdapter;
import
org.springframework.security.crypto.bcrypt.BCryptPasswordEnc
oder;
import
org.springframework.security.web.util.matcher.AntPathRequest
Matcher;
@EnableWebSecurity
@Configuration
publicclassSecurityConfigextendsWebSecurityConfigurerAdapter
{
@Autowired
privateBCryptPasswordEncoderpwdEnc;
@Override
protectedvoid
configure(AuthenticationManagerBuilderauth) throws Exception
{
auth.inMemoryAuthentication().withUser("Sam")
.password(pwdEnc.encode("Sam")).authorities("EMP");
auth.inMemoryAuthentication().withUser("Ram")
.password(pwdEnc.encode("Ram")).authorities("ADMIN");
auth.inMemoryAuthentication().withUser("Vicky")
.password(pwdEnc.encode("Vicky")).authorities("STUDENT" ,
"MGR");
}
protectedvoidconfigur(HttpSecurityhttp) throws Exception {
http.authorizeRequests()
.antMatchers("/all").permitAll()
.antMatchers("/emp").hasAuthority("EMP")
.antMatchers("/admin").hasAuthority("/ADMIN")
.anyRequest().authenticated()
.and().formLogin().defaultSuccessUrl("/view")
.and().logout().logoutRequestMatcher
(newAntPathRequestMatcher("/logout"))
.and().exceptionHandling().accessDeniedPage("/denied");
}
}
4. Init File (AppInit.java)
packagecom.app.init;
import
org.springframework.web.servlet.support.AbstractAnnotationCo
nfigDispatcherServletInitializer;
importcom.app.config.AppConfig;
publicclassAppInitextendsAbstractAnnotationConfigDispatcherS
ervletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
returnnew Class[] {AppConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
returnnull;
}
@Override
protected String[] getServletMappings() {
returnnew String[] {"/"};
}
}
packagecom.app.init;
import
org.springframework.security.web.context.AbstractSecurityWeb
ApplicationInitializer;
publicclassSecurityInitextendsAbstractSecurityWebApplication
Initializer{ }
6. HomeController.java
packagecom.app.controller;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping
;
@Controller
publicclassHomeController {
@RequestMapping("/all")
public String all() {
return"CommonPage";
}
@RequestMapping("/emp")
public String emp() {
return"EmployeePage";
}
@RequestMapping("/view")
public String view() {
return"ViewPage";
}
@RequestMapping("/admin")
public String admin() {
return"AdminPage";
}
@RequestMapping("/denied")
public String denied() {
return"AccessDenied";
}
}
7. JSP Files
a) AccessDenied.jsp
<%@pagelanguage="java"contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Youcan not access this URL!!</h1>
<ahref="logout">Goto Home</a>
</body>
</html>
b) AdminPage.jsp
<%@pagelanguage="java"contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>welcome to Admin page!!</h1>
<ahref="logout">Goto Home</a>
</body>
</html>
c) CommonPage.jsp
<%@pagelanguage="java"contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome to All!!</h1>
</body>
</html>
d) EmployeePage.jsp
<%@pagelanguage="java"contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>welcome to Employee Page!!</h1>
<ahref="logout">Goto Home</a>
</body>
</html>
e) ViewPage.jsp
<%@pagelanguage="java"contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=ISO-8859-1">
antMatchers(“/urlPattern”):
This method is used to provide URL-Patterns and their security levels.
Design:--
Coding Steps:--
#1>Configure DataSource(I) any one Impl class object in AppConfig. Example use
DriverManagerDataSource, BasicDataSource etc…
#2>Define two SQL Queries which will be executed on click login button. These
SQLs gets data from 2 DB tables one is “users” based on username and other one
is “authorities’ based on username.
Ex:-- SQL>select username, password, enable from users where username=?
SQL>select username, authority from authorities where username=?
#3>use passwordEncoder and app.properties (Environment) [optional].
#4>Create two table tables as given in Database also insert few rows I both tables.
#5>Configure JDBC Authentication Manager using userSQL, AuthoritiesSQL,
DataSource and Password Encoder. Code looks like.
{
auth.jdbcAuthentication()
.usersByUsernameQuery(“SQL_1”)
.authoritiesByUsernameQuery(“SQL_2”)
.dataSource(ds)
.passwordEncoder(pwdEncoder);
}
Folder Structure:--
Code:--
1>app.properties:--
dc=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
un=root
pwd=root
prefix=/WEB-INF/views/
suffix=.jsp
usernameSQL=select username, password, enabled from users where
username=?
authSQL=select username, authority from authorities where username=?
2>AppInit:--
package com.app.init;
import org.springframework.web.servlet.support.
AbstractAnnotationConfigDispatcherServletInitializer;
import com.app.config.AppConfig;
3>AppConfig:--
package com.app.config;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan(basePackages="com.app")
@EnableWebMvc
@PropertySource("classpath:app.properties")
@Import({SecurityConfig.class})
public class AppConfig
{
@Autowired
private Environment env;
@Bean
public BCryptPasswordEncoder pwdEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public BasicDataSource ds() {
BasicDataSource ds=new BasicDataSource();
ds.setDriverClassName(env.getProperty("dc"));
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 97 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
ds.setUrl(env.getProperty("url"));
ds.setUsername(env.getProperty("un"));
ds.setPassword(env.getProperty("pwd"));
return ds;
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver v=new
InternalResourceViewResolver();
v.setPrefix(env.getProperty("prefix"));
v.setSuffix(env.getProperty("suffix"));
return v;
}
}
4>HomeController:--
package com.app.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController
{
@RequestMapping("/admin")
public String showAdmin() {
return "AdminPage";
}
@RequestMapping("/all")
public String showAll() {
return "CommonPage";
}
@RequestMapping("/emp")
public String showEmp() {
return "EmployeePage";
}
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 98 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
@RequestMapping("/view")
public String showView() {
return "ViewPage";
}
@RequestMapping("/denied")
public String showDenied() {
return "AccessDenied";
}
}
5>SecurityInit:--
package com.app.init;
import org.springframework.security.web.context.
AbstractSecurityWebApplicationInitializer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
@PropertySource("classpath:app.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private Environment env;
@Autowired
private BCryptPasswordEncoder pwdEncoder;
@Autowired
private DataSource dataSource;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(env.getProperty("usernameSQL"))
.authoritiesByUsernameQuery(env.getProperty("authSQL"))
.passwordEncoder(pwdEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/all").permitAll()
.antMatchers("/admin").hasAuthority("ADMIN")
.antMatchers("/emp").hasAuthority("EMP")
.anyRequest().authenticated()
.and()
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 100 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
.formLogin()
.defaultSuccessUrl("/view",true)
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.and()
.exceptionHandling()
.accessDeniedPage("/denied");
}
}
7>Test Class:--
package com.app.config;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
JSP Pages:--
1>AdminPage.jsp:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 101 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Welcome to Admin Page</title>
</head> <body>
Welcome to Admin Page
<br/>
<a href="logout">Logout</a>
</body> </html>
2>ViewPage.jsp:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Welcome to View Page</title>
</head> <body>
Welcome to All Page
</body> </html>
3>CommonPage.jsp:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Welcome to Common Page </title>
</head> <body>
Welcome to Common Page
<br/>
<a href="logout">Logout</a>
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 102 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
</body> </html>
4>EmployeePage.jsp:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Welcome to Employee Page</title>
</head><body>
Welcome to Employee Page
<br/>
<a href="logout">Logout</a>
</body></html>
5>AccessDenied.jsp:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome to AccesseDenied Page</title>
</head><body>
We are sorry!!
<br/>
<a href="logout">Go Home</a>
</body></html>
Execution Process:--
Step#1:--Create Bellow table and insert the value inside the following table.
##Tables##
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 103 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
SQL>create table users (username varchar (50) not null primary key,
password varchar (100) not null, enabled boolean not null);
SQL>create table authorities (username varchar(50) not null, authority
varchar(50) not null, constraint authusersFk foreign key(username) references
users(username));
SQL>create unique index usernameauthindex on authorities (username,
authority);
Step#2:--
##BASCI DATA##
SQL>insert into users (username, password, enabled) values ('admin',
'$2a$10$A.Gbvyy89BD7tJAa0Q8cxe8S/Zh5b8nrxWrJLk8IKmXEQB4UAvery',true);
##APP Queries##
SQL>select username, password, enabled from users where username=?
SQL>select username, authority from authorities where username=?
#a>User Module Implementation:--Here, define one JSP (UI) Page for User
Register process. This data should be stored in DB table using ORM (Model class).
=>Data inserted into two tables, user basic details are inserted into parent table
and roles (Authorities) are inserted into child table.
=>For this we need to define Layer design of USER Module using PL, SL and DAL.
------------------------------------------------Designs--------------------------------------------------
------
Layers Design:--
#b> User, define one Login.jsp page with basic input like username and password.
=>On click Login button, read user details from DB based on Username input
using “UserDetailsService”(I) impl class, which also converts Model class.
User (com.app.model) object to Spring f/w User
(org.springframework.security.core.userdetails).
=>Here roles are converted to Set of GranteAuthority. Implementation used
SimpleGrantedAuthority given by Spring F/W.
-------------------------------------------------------------------------------------------------------------
------
=>Here, we should write one impl class for Interface UserDetailsService having
one abstract method loadUserByUsername (String username) and return Spring
F/W User class object it uses our IService (SL) to fetch data from DB.
Folder Structure:--
Code:--
1>AppInit:--
package com.app.init;
import org.springframework.web.servlet.support.
AbstractAnnotationConfigDispatcherServletInitializer;
import com.app.config.AppConfig;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
2>AppConfig:--
package com.app.config;
import java.util.Properties;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import
org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.app.model.Product;
import com.app.model.User;
@Configuration
@EnableWebMvc //MVC
@EnableTransactionManagement//Tx
@PropertySource("classpath:app.properties")
@ComponentScan(basePackages="com.app")
@Import(SecurityConfig.class)
public class AppConfig implements WebMvcConfigurer
{
//load properties
@Autowired
private Environment env;
@Bean
public BCryptPasswordEncoder encoder()
{
return new BCryptPasswordEncoder();
}
//DataSource
@Bean
public BasicDataSource dsObj()
{
BasicDataSource ds=new BasicDataSource();
ds.setDriverClassName(env.getProperty("dc"));
ds.setUrl(env.getProperty("url"));
ds.setUsername(env.getProperty("un"));
ds.setPassword(env.getProperty("pwd"));
ds.setInitialSize(1);
ds.setMaxIdle(10);
ds.setMinIdle(5);
ds.setMaxTotal(10);
return ds;
}
//SessionFactory
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 111 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
@Bean
public LocalSessionFactoryBean sfObj()
{
LocalSessionFactoryBean sf=new LocalSessionFactoryBean();
sf.setDataSource(dsObj());
sf.setAnnotatedClasses(Product.class,User.class);
sf.setHibernateProperties(props());
return sf;
}
private Properties props()
{
Properties p=new Properties();
p.put("hibernate.dialect", env.getProperty("dialect"));
p.put("hibernate.show_sql", env.getProperty("showsql"));
p.put("hibernate.format_sql", env.getProperty("fmtsql"));
p.put("hibernate.hbm2ddl.auto", env.getProperty("ddlauto"));
return p;
}
//HT
@Bean
public HibernateTemplate htObj()
{
HibernateTemplate ht=new HibernateTemplate();
ht.setSessionFactory(sfObj().getObject());
return ht;
}
//Tx manager
@Bean
public HibernateTransactionManager httx() {
HibernateTransactionManager htm=new
HibernateTransactionManager();
htm.setSessionFactory(sfObj().getObject());
return htm;
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 112 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
}
//view resolver
@Bean
public InternalResourceViewResolver ivr() {
InternalResourceViewResolver v=new
InternalResourceViewResolver();
v.setPrefix("/WEB-INF/views/");
v.setSuffix(".jsp");
return v;
}
}
3>Product class:--
package com.app.model;
import java.lang.Integer;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "producttab")
public final class Product
{
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name="pname")
private String productName;
@Column(name="pcost")
private double productCost;
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 113 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
@Column(name="pdtls")
private String productDetails;
public Product() {
super();
}
public Product(Integer id) {
super();
this.id = id;
}
@Override
public String toString()
{
return "Product [id=" + id + ", productName=" + productName + ",
productCost=" + productCost + ", productDetails=" + productDetails + "]";
}
}
4>IProductDao:--
package com.app.dao;
import com.app.model.Product;
import java.lang.Integer;
import java.util.List;
5>ProductDaoImpl:--
package com.app.dao.impl;
import com.app.dao.IProductDao;
import com.app.model.Product;
import java.lang.Integer;
import java.lang.Override;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class ProductDaoImpl implements IProductDao
{
@Autowired
private HibernateTemplate ht;
@Override
public Integer saveProduct(Product product) {
return (Integer)ht.save(product);
}
@Override
public void updateProduct(Product product) {
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 116 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
ht.update(product);
}
@Override
public void deleteProduct(Integer id) {
ht.delete(new Product(id));
}
@Override
public Product getOneProduct(Integer id) {
return ht.get(Product.class,id);
}
@Override
public List<Product> getAllProducts() {
return ht.loadAll(Product.class);
}
}
6>IProductService:--
package com.app.service;
import com.app.model.Product;
import java.lang.Integer;
import java.util.List;
7>ProductValidator:--
package com.app.validator;
import com.app.model.Product;
import java.lang.Class;
import java.lang.Object;
import java.lang.Override;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class ProductValidator implements Validator
{
@Override
public boolean supports(Class<?> clazz)
{
return Product.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
} }
8>ProductController:--
package com.app.controller;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 118 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
import org.springframework.web.bind.annotation.RequestParam;
import com.app.model.Product;
import com.app.service.IProductService;
import com.app.validator.ProductValidator;
@Controller
@RequestMapping("/product")
public class ProductController
{
@Autowired
private IProductService service;
@Autowired
private ProductValidator validator;
@RequestMapping("/register")
public String regProduct(ModelMap map)
{
map.addAttribute("product",new Product());
return "ProductRegister";
}
return "ProductRegister";
}
@RequestMapping("/delete")
public String deleteProduct(@RequestParam Integer id,ModelMap map)
{
service.deleteProduct(id);
List<Product> prods=service.getAllProducts();
map.addAttribute("products", prods);
return "ProductData";
}
@RequestMapping("/edit")
public String editProduct(@RequestParam Integer id, ModelMap map)
{
Product ob=service.getOneProduct(id);
map.addAttribute("product",ob);
return "ProductEdit";
}
@RequestMapping("/getAll")
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 120 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
JSP Pages:--
1>ProductRegister:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head> <body>
<h2>Register Product Here</h2>
<form:form action="save" method="POST" modelAttribute="product">
<pre>
NAME : <form:input path="productName"/>
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 121 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
2>ProductData:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head> <body>
<h2>Welcome to Product Data</h2>
<table border="1">
<tr>
<th>ID</th>
<th>NAME</th>
<th>COST</th>
<th>NOTE</th>
<th colspan="2">OPERATIONS</th>
</tr>
<c:forEach items="${products}" var="p">
<tr>
<td><c:out value="${p.id}"/></td>
<td><c:out value="${p.productName}"/></td>
<td><c:out value="${p.productCost}"/></td>
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 122 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
<td><c:out value="${p.productDetails}"/></td>
<td>
<a href="delete?id=${p.id}">DELETE</a>
</td>
<td>
<a href="edit?id=${p.id}">EDIT</a>
</td>
</tr>
</c:forEach>
</table>
${message}</body></html>
3>ProductEdit:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head> <body>
<h2>Edit Product Here</h2>
<form:form action="update" method="POST" modelAttribute="product">
<pre>
ID : <form:input path="id" readonly="true"/>
NAME : <form:input path="productName"/>
COST : <form:input path="productCost"/>
DETAILS : <form:textarea path="productDetails"/>
<input type="submit" value="Modify"/>
</pre>
</form:form>
</body> </html>
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 123 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
1>UserRegister:--
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head> <body>
<h2>User Register Page</h2>
<form:form action="save" method="POST" modelAttribute="user">
<pre>
NAME : <form:input path="userName"/>
EMAIL : <form:input path="userEmail"/>
PASSWORD : <form:password path="userPwd"/>
ROLES :
<form:checkbox path="roles" value="ADMIN"/> ADMIN
<form:checkbox path="roles" value="EMPLOYEE"/> EMPLOYEE
<input type="submit" value="Create User"/>
</pre>
</form:form>
${message}
</body> </html>
2>SecurityConfig:--
package com.app.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.
AuthenticationManagerBuilder;
import
org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.
EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.
WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private UserDetailsService service;
@Autowired
private BCryptPasswordEncoder encoder;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(service).passwordEncoder(encoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/product/register","/product/getAll")
.hasAnyAuthority("ADMIN","EMPLOYEE")
.antMatchers("/product/delete","/product/update","/product/edit")
.hasAuthority("ADMIN")
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 125 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
.antMatchers("/user/*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.defaultSuccessUrl("/")
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("logout"))
.and()
.exceptionHandling()
.accessDeniedPage("/denied");
}
}
3>User class:--
package com.app.model;
import java.util.Set;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 126 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
@Table(name="usrtab")
public class User
{
@Id
@Column(name="uid")
@GeneratedValue(generator="ugen")
@GenericGenerator(name="ugen",strategy="increment")
private int userId;
@Column(name="uname")
private String userName;
@Column(name="uemail")
private String userEmail;
@Column(name="upwd")
private String userPwd;
@ElementCollection
@CollectionTable(name="usr_roles_tab",
joinColumns=@JoinColumn(name="uid"))
@Column(name="roles")
private Set<String> roles;
public User() {
super();
}
public User(int userId) {
super();
this.userId = userId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 127 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public Set<String> getRoles() {
return roles;
}
public void setRoles(Set<String> roles) {
this.roles = roles;
}
@Override
public String toString()
{
return "User [userId=" + userId + ", userName=" + userName + ",
userEmail=" + userEmail + ", userPwd=" + userPwd + ", roles=" + roles + "]";
}
}
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 128 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
4>IUserDao:--
package com.app.dao;
import com.app.model.User;
5>UserdaoImpl:--
package com.app.dao.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.app.dao.IUserDao;
import com.app.model.User;
@Repository
public class UserDaoImpl implements IUserDao
{
@Autowired
private HibernateTemplate ht;
@Override
public int saveUser(User user)
{
return (Integer)ht.save(user);
}
@SuppressWarnings("deprecation")
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 129 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
@Override
public User getUserByEmail(String userEmail)
{
User user=null;
String hql="from "+User.class.getName()+" where userEmail=?";
List<User> userList=(List<User>) ht.find(hql, userEmail);
if(userList!=null && userList.size()>0) {
user=userList.get(0);
}
return user;
}
}
6>IUserService:--
package com.app.service;
import com.app.model.User;
7>UserServiceImpl:--
package com.app.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.app.dao.IUserDao;
import com.app.model.User;
import com.app.service.IUserService;
@Service
public class UserServiceImpl implements IUserService
{
@Autowired
private IUserDao dao;
@Autowired
private BCryptPasswordEncoder encoder;
@Transactional
public int saveUser(User user) {
//read UI password
String pwd=user.getUserPwd();
//encode password
pwd=encoder.encode(pwd);
//set back to model object
user.setUserPwd(pwd);
//save user to DB
return dao.saveUser(user);
}
@Transactional(readOnly=true)
public User getUserByEmail(String userEmail) {
return dao.getUserByEmail(userEmail);
}
}
8>UserDetailsServiceImpl:--
package com.app.service.impl;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 131 | P a g e
Spring Framework by Mr. RAGHU [PART-3]
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import
org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.app.model.User;
import com.app.service.IUserService;
@Service
public class UserDetailsServiceImpl implements UserDetailsService{
@Autowired
private IUserService service;
@Transactional(readOnly=true)
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException
{
//take login username and get DB Model class obj
User user=service.getUserByEmail(username);
9>UserController:--
package com.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.app.model.User;
import com.app.service.IUserService;
@Controller
@RequestMapping("/user")
public class UserController
{
@Autowired
private IUserService service;
@RequestMapping("/register")
public String showReg(ModelMap map) {
map.addAttribute("user",new User());
return "UserRegister";
}
@RequestMapping(value="/save",method=RequestMethod.POST)
public String saveUser(@ModelAttribute User user,ModelMap map)
{
int userId=service.saveUser(user);
String msg="User '"+userId+"' create successfully ";
map.addAttribute("message",msg);
return "UserRegister";
}
}
https://sathyatech.com/ 9100920092|9100940094 info@sathyatech.com 133 | P a g e