AdvJava 09 Combined
AdvJava 09 Combined
Details: http://tutorials.jenkov.com/maven/maven-tutorial.html ,
① Central Repo •
ME
② Repo
jiff
Remote > 0
③ Local Repo
10cal repo
L •
ME
I
°
±
*
II I
(poojas
mzflocdoepomvnoepositooy.com
]Tj <
•
IT
°
✗
(organization remote a
)
class ( add deep in class path &
files)
Compile all src code .
-÷:É÷:
① ②
÷ -
2mn
:
Password
www.eus-e ,
-Bean
"" "" t
annexes ,
Been
-
to" '
tubridy ,
fekhtopicTutorials
ojs
>
index.jp loginjsp ④didakj5µ details .jp
7s
☐
Losihrtsaih oserr
0 . -
•""
.
""
Tsai .
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
Run Maven web application from Eclipse
Run application
(Same as Dynamic Web Project execution)
testing
unit
Spring Framework
.
deployment
- -
r
③
Carts ;
car ⇐ new
✓
Test driven development chap
C-
set Chassis (ch) ;
Obj
T
✓ Extensive but Flexible and modular Body (b) ;
c. set
_ - -
Of seats
c. doing ; done
✓
Smooth integration with existing technologies body , by
spring
n Eliminate boilerplate code
-
✓ Extendable
readable exceptions Engine Engine
/ ,
✓ Dependent
✓ ✓
is
✓ ✓ ✓ ✓
[y
to 2
b☐
spring container
Param
ctor
Spring Boot take an "opinionated view" of the Spring platform and third-party
libraries. So most of applications need minimum configuration. my
boot app
✓
my web app
""5
✓
tomcat java
✓ Managing versions of dependencies with starter projects. appln
✓ Provide lot of non-functional common features (e.g. security, servers, health checks, ...).
No extra code generation (provide lot of boilerplate code) and✗XML config.
= Easy deployment and containerisation with embedded Web Server.
- -
Recommended to use for new apps and not to port legacy Spring apps.
Sunbeam Infotech www.sunbeaminfo.com
Spring Boot
Spring Boot
Web
•
Database
•
Spring Framework AOP
✓
Messaging
•
Spring Boot = Spring framework + Embedded web-server + Auto-configuration - XML config - Jar conflicts
② Account smpl @
Logger
✓
property values D
"
< name __ lol
✓ Initializing collections z
<list>
↳ < [email protected] >
<
property name __
' -
logger
"
ref __
"
consolelosses
'
'I >
class Transaction E <set > <I been>
id time, amount, those <map>
,
-
< properties>
3 " "
Émmmm
'
< r r
"
= Elisa>
3
< Ipooperty >
dbeom>
ace
consolelosses
4 0R~
file logger
@Service
^
<
>
filehosegerzry.de
accountant >
✗
tosser cogohefilehggrzropnl
<
a
✓
>
logo {
cashless Usc ) ;
✗
-
ftelagser b- C) ;
-
j
C 3
consnheloggssnpnl
:
.
• → Testis
@Autowired: Find bean of corresponding field type and assign it.
If no bean is found of given type, it throws exception. → Test )
→ field will be null .
If multiple beans are found of given type, it try to attach bean of same name. and if such bean is
not found, then throw exception.→ Test Test 7
↳ Tests
4 →
If multiple beans are found of given type, programmer can use @Qualifier to choose expected
bean. @Qualifier can only be used to resolve conflict in case of @Autowired.
@ Autowired
@Resource (JSR 250) poi
① ② ③ low
@Resource: DI byName, byType, byQualifier ① by Type
>
✓
<bean id="..." class="..."
autowire="default|no|byType|byName|constructor" .../>
default / no: Auto-wiring is disabled.
byType: Dependency bean of property type will be assigned (via
setter).
If multiple beans of required type are available, then exception is
thrown.
→ molds
If no bean of required type is available, auto-wiring is not done.
byName: Dependency bean of property name will be assigned (via
setter).
→ mum
If no bean of required name is available, auto-wiring is not done.
constructor: Dependency bean of property type will be assigned via
single argument constructor (of bean type).
e-
}
.
@PreDestroy
-
@Autowired
@Qualifier
my
value="#{bean.field ← properties file
minimum
SPEL
value="${property-
MM
SpEL expressions are slower in execution due parsing. Spring 4.1 added SpEL compiler to
speed-up execution by creating a class for expression behaviour at runtime.
Spring container creates (singleton) spring bean objects when container is started.
Spring container controls creation and destruction of bean objects.
There are four options to control bean life cycle.
Mmm
Bean creation
✓1. Instantiation (Constructor)
✓2. Set properties (Field/setter based DI)
✓3. BeanNameAware.setBeanName()
4. ApplicationContextAware.setApplicationContext()
=5. Custom BeanPostProcessor.postProcessBeforeInitialization()
✓6. Custom init() (@PostConstructor)
✓7. InitializingBean.afterPropertiesSet() @ Been ( init
__
method ]
"
8. Custom BeanPostProcessor.postProcessAfterInitialization()
:
Bean destruction
1. Custom destroy() (@PreDestroy)
2. DisposableBean.destroy()
=3. Object.finalize()
]
.
Minimal Dependency injection features Class Path ton App Contest (Jeans and'D; .
Ctx .
; 4
Auto-wiring return pointer
to bl been
Create a singleton bean when it is accessed first time in the application. Cwhich is
created
No bean life cycle management earlier) .
demo#
✗theBean
Factory factory new
= Xml Beam Factory fed;
(Box) factory .9etBan( ]
" "
b) b' '
Bose =
→
sop ( bl.cdcvolume.CI) ;
b) been obj
'
is created .
: and Auto-wiring
Automatic BeanPostProcessor
registration i.e. Bean life cycle
management
absolute path of ✗and file
Convenient MessageSource access
§→"
✓
project
(Internationalization) dir
→ interface
"•
WebApplicationContext ← interface
& GApp6nfig.dass_ XmlWebApplicationContext
Application Context
-0 AnnotationConfigWebApplicationContext
type anon
scope .
Been f) >
Cbe
. get ,
b) a )
blbctse.setBe.nl b2b
5
java.gl DataSource
JDBC is specification given by Sun/Oracle.
← .
connection
↳ type 4 driver pool c
a
JDBC driver convert Java request to RDBMS understandable form and RDBMS
response to Java understandable form.
- JPBC <
>
>
§
✓
°
\ ↳ optional CJDBC
4+3
put data
into
get data
✓ Prepare JDBC statement. form
-
Driver Manager setcannech.gl )
}
Java
Crs.ne
.
→
object
° Execute query and process result.
can prepare statements
§
-
✓ Close all.
while
select start C) Resultset →
{
: .
execute
Query →
Im
,
select execute Update
non ' )
stand
-
: . .
JDBC functions
} catch(Exception e) {
con.setAutocommit(false);a discard
s
con.commit(); con.rollback();
←
con.rollback(); L }
Using JDBC we can avoid overheads of ORM tools. This is helpful in small jdbcTemplate
applications, report generation tools or running ad-hoc SQL queries.
Steps:
:
dataSource
oserdaozonplhasauserserviceznpl.tn
has " ↳a
DataSource JdbcTemplate
use a
↳ properties in
I ✓
has " Tutorial
application %PicDaotmP&
.
properties servicing
•
Url username password ^
, ,
usea
Topic Row
Mapper Irish
✓
Tutorial
Daotonpl has a
has -
a
Tutorial Row
Mapper Irish
✓
Sunbeam Infotech www.sunbeaminfo.com
Spring Web MVC
MVC is design-pattern.
Divide application code into multiple relevant components to make application
maintainable and extendable.
M: Model: Data of the application.
V: View: Appearance of data.
C: Controller: Interaction between models & views.
Typical MVC implementation using Servlets & JSP.
Model: Java beans
View: JSP pages
Controller: Servlet dispatching requests
→
forward C)
-
.
← pre
-
defined
Controller: Spring Front Controller i.e. DispatcherServlet by spring
User defined controller: Interact with front controller to collect/send data to appropriate
view, process with service layer. @ controller .
[email protected]
* → MhPÑB
class welcome↳to"" {
Dispatchersextet ↳
browser
③ ③ call 7 method
in :••1we" m e
②
> > string home( mod¥ > q
foggy
;§•¥;É*
① been
Date now __ new Dates ;
↳↳" "
④
mm
got r 3
,
I 3
Model
⑧
of v
object is wrapper
±¥É¥de×§÷→
p
on
request objeeh.to
add request attribute
⑥
.
✓
⑤ apply poefixd.se Hix
indexj→ GEr been
${Carine}
⑦ render
[
-
É
> find
@
¢
µ-_ Z
/wdcame_
> un
>
> < <
✓
✓
-
:*
n
•¥÷÷
E
} I
um
{ time -
jsP~
Sunbeam Infotech www.sunbeaminfo.com
Spring Web MVC
https://terasolunaorg.github.io/guideline/1.0.x/en/Overview/SpringMVCOverview.html
[
-
É
> find
@
¢
µ-_ Z
/wdcame_
> un
>
> < <
✓
✓
-
:*
n
•¥÷÷
E
} I
um
{ time -
jsP~
Sunbeam Infotech www.sunbeaminfo.com
Spring Boot Web MVC
Create new Spring Boot project with Spring Web starter.
In pom.xml add JSP & JSTL support
org.apache.tomcat.embed - tomcat-embed-jasper: provided
javax.servlet - jstl
Configure viewResolver in application.properties
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
Implement a controller with a request handler method returning view name (input).
Under src/main create directory structure webapp/WEB-INF/jsp.
Create input.jsp under webapp/WEB-INF/jsp to input user name and submit to server.
Add another request handler method in controller to accept request param and send
result to output page.
Create output.jsp under webapp/WEB-INF/jsp to display the result.
@RequestMapping attributes
value { /welcome
" " "
/ }
"
✓ url- = ,
¥
-
InputStream, OutputStream
HttpSession, @CookieValue, Locale
HttpEntity<>, @RequestBody.
Supported method return types
-
view String, View, Model or Map, ModelAndView
✓ ✓
✓
name
✓ HttpHeaders, void
✓
✓
HttpEntity<>, ResponseEntity<>, @ResponseBody.
✓
✓
⑨"Ñf
> sting resin {
✓
that >
-
f coed
n "
desh 'I
'
user
passed mn
Sissons
,
failed SP
coed>
✓ dao fond
~
.
ByEmail
aethacatecem ,PaDj
a- user service .
iHu==nuU) r Tn
z
failed
' "
return
; 7
✓ iffuioole ==
"
admin
'
)
'
Invalid return
"
manage
";
return "
topics
"
@fepÑtsy L
↳pnAsaM_ 3 ;
User Daoznpl {
fmdByEmaiN{
=
3
3
⑨"Ñaf
> sting resin {
actin-fvdidk.it#ddh );
✓ toed .addAtr( "
command's new Coed
←model
7
'
f coed
n "
desh 'I
'
return Usersevicetnpl
email login.jp 3
↳ view name
g
[email protected]
mm
user
pass;wd
Sissons
mm
tailed'j5P
coed>
✓ dao fond
~
.
ByEmail
usersenia.aethacate.fm/paDj
↳
iHu==nuU) r Tn
z
failed
' "
return
; 7
✓ ifuioole ==
"
admin
'
)
'
Invalid return
"
manage
";
return "
topics
"
@fepÑtsy L
↳pnAsaM_ 3 ;
User Daoznpl {
fmdByEmaiN{
=
3
3
[
b t
f Tutorial
browser I > > Tutorial
*
Service Dao
miles h
.
those those
Tutorial
authvsor.setrlo.me E- ) ;
''
Controller µ
Impel Auth
• > User -
-
-
Proxy
-
setmarre.CI
.
"
"
"
browser 2 isetrlarec )
"
"
"
"
"
'
"
Kiran
Httpsessiovytpufn ✓ Httpsessian
>
jpufn
User User
unit esh v. Kiran
nilesh Kiran
For web applications client side validations are preferred for better user experience
However client side validations can be bypassed/skipped by client.
To ensure only validity of data provide server side validations (as well).
Spring validation framework helps for server side validations.
Spring supports JSR-303 validations.
✓ @NotBlank, @NotEmpty, @Size, @Email, @Pattern, @DateTimeFormat, @Min, @Max
vdidatatian starter
"
Steps:
"
boot
spring -
Static resources like JS, CSS, images should be mapped to some location.
<mvc:resources location="/WEB-INF/static/css ="/css
↳ XML Cordis appto
Spring
Mvc
add under
For
Spring Boot folder
"
→
resources static" .
in boot . properties
messages -
Mr.
en
daj-III-r.FR
hi en -
GB
[
-
É
> find
@
¢
µ-_ Z
/wdcame_
> un
>
> < <
✓
✓
-
:*
n
•¥÷÷
E
} I
um
{ time -
jsP~
Sunbeam Infotech www.sunbeaminfo.com
Spring Web MVC Thymeleaf Views
②
@
①
①
⑧ ⑤
= ⑦
⑨ ④
=-
①
✓
0
①
£9 :iÉ
<
> >
fields
-
-
-
m
-
- -
Relational
object
mapping
Hibernate ORM frameworks
① Hibernate
§
^ ""
② "" " " """
③ iBatis
④ Torque
④ -
o s
✓
Converting Java objects into RDBMS
rows and vice-versa is done manually
in JDBC code.
✓This can be automated using Object
Relational Mapping.
✓
Class Table and Field Column
✓
✓
It also map table relations into entities
associations/inheritance and auto-
generates SQL queries.
✓Hibernate is most popular ORM tool.
get connection
/ <• • ☐ ° dsehoesult
✓
→ create query ←
a rdbms communication .
Java Application a
✓
CRUD
← SQL where
Session Cache
-
- delete c)
( JPA ) Criteria Query select &
DML Sgt .
H I B E R N A T E
- update c)
find C)
>
Session ←
call stored pooc .
p
where
clause in
open ProcedureCall Criteria select sqd
(deprecated)
> L
Query
mandatory Transaction ↳ → Commit]
Query Language
> SessionFactory for DML ops .
rollback] .
build
handle RDBMS differences MySQL5- Dialect MySQL 8 Dialect ,
✓ ✓
^
&
JTA
: JDBC JNDI ✗
✗
A Naming &
Directory Interface
'
Hot password
hibernate .
cfgseml
username dialect RDBMS
Sunbeam Infotech www.sunbeaminfo.com
Hibernate
SessionFactory
One SessionFactory per application (per db).
Heavy-weight object. Not recommended to
create multiple instances. →
singleton day
Thread-safe. Can be accessed from multiple
threads (synchronization is built-in). ]
Typical practice is to create singleton utility
class for that.
Session
Created by SessionFactory & it encapsulate
JDBC connection.
All hibernate operations are done on hibernate
sessions.
Is not thread-safe. Should not access same
session from multiple threads.
Light-weight. Can be created and destroyed as
per need.
Sunbeam Infotech www.sunbeaminfo.com
Hibernate
Transaction
In hibernate, autocommit is false by
default.
DML operations should be
performed using transaction.
session.beginTransaction()
to start new transaction.
tx.commit()
to commit transaction.
tx.rollback()
to rollback transaction.
Hibernate CRUD methods
get() / find C)
save() / persist C)
update()
delete()
Hibernate Configuration
hibernate.connection.driver_class
hibernate.connection.url
hibernate.connection.username
hibernate.connection.password
hibernate.dialect
hibernate.show_sql
Hibernate3 Bootstrapping
Create Configuration object.
Read hibernate.cfg.xml file using its
configure() method.
Create SessionFactory using its
buildSessionFactory() method.