You are on page 1of 176

1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Framework: 1. It is a special software that is capable of developing applications based on ceratian architecture with the ability to generate common logics of the application. 2. It is given based on core technologies. 3. It provides an abstraction layer on core technologies. Struts: It is a framework to develop MVC-II architecture based web applications only. Hibernate: Its a ORM Framework which is used only for database operations. Spring: Its a framework software which can be used to develop any kind of Java/J2EE applications. Note: Spring framework provides abstraction layer on: 1. java & J2EE core technologies 2. ORM Tools like: 1. Hibernate 2. JDO 3. iBastis etc.., 3. AOP Framework etc.., Spring Info: Type: java-j2ee Framework software Version: 2.5[Compatible with jdk1.5+] Vendor: Interface21 Creator: Rod Johnson Open Source Download: www.springframework.org Online Tutorials: www.roseindia.net Articles: 1. www.javabeat.net 2. www.onjava.com 3. www.precisejava.com 4. www.devx.com FAQ's: www.forum.springframework.org Reference Books: 1. Spring Live 2. Spring in Action --> Manning Publishers Introduction: 1. Spring framework is developed to simplify the development of enterprise applications in Java technologies. 2. It is an open source framework begin developed by Interface21. 3. The Spring provides light weight IoC Container and AOP framework. 4. It provides support for JPA, Hibernate, Web services, Schedulers, Ajax, Struts, JSF and many other frameworks. 5. The Spring MVC components can be used to develop MVC based web applications. 6. The Spring 3.0 framework has been released with major enhancements and support for the Java 5 [JDK1.5]. 7. Spring can be used to configure declarative transaction management, remote access to your logic using RMI or web services, mailing facilities and various options in persisting your data to a database. 8. Spring framework can be used in modular fashion, it allows to use in parts and leave the other components which is not required by the application.

2 48 49 50 51 52 53 54 55 56 57

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Spring Architecture: Spring is well-organized architecture consisting of seven modules. Modules in the Spring framework are: Spring1.x: It has 7 modules. They are: 1. Core 2. DAO 3. ORM 4. JEE/Context 5. Web 6. MVC 7. AOP

58 59 60 61 62 63 64 65 66 67 68 69 70 71

Figure: The Spring framework is composed of several well-defined modules. Spring2.x: It has 6 modules only. Because Web & Web MVC modules were clubbed together & given as Web MVC module. Core Module: 1. It is base module for all modules. 2. Provides BeanFactory container which makes Spring as a container 3. Acts as a base module for other modules 4. provides the fundamental functionality of the Spring framework. 5. The Core package is the most import component of the Spring Framework. 6. This component provides the Dependency Injection [DI] features. DAO Module: 1. It provides abstraction layer on JDBC & allows us to do database operations. 2. Using it we can focus only on database operations instead of doing repeated work by writing common code again and again.

3 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

3. Here we can make use of JdbcTemplate class where we can call methods to do required database opeartion. 4. We can connect to database either by manual code same like jdbc or we can do easily by using JdbcTemplate class. 5. Using JdbcTemplate class we can retrieve data from database in the form of serializable objects. ORM Module: 1. It provides an abstraction layer on ORM Framework software's like Hibernate, iBatis, JDO etc.., 2. Spring doesnt attempt to implement its own ORM solution 3. Springs transaction management supports each of these ORM frameworks as well as JDBC. JEE/Application Context Module: 1. It provides abstraction layer on Java/J2EE technologies like Java Mail, JMS, EJB etc.., 2. The context module is what makes spring as a framework. 3. This module extends the concept of BeanFactory 4. Adds support for internationalization (I18N) messages, application life cycle events, and validation. 5. Supplies many enterprise services such as e-mail, JNDI access, EJB integration, remoting, and scheduling. AOP [Aspect Oriented Programming] Module: 1. One of the key components of Spring is the AOP framework. 2. It provides a methodology to configure middleware services or to perform any authentication, validations or to perform any pre processing logic or post processing logic on our business logic methods. 3. Without disturbing any kind of spring resources we can integrate our spring application with any kind of middleware service. 4. Spring provides a separate layer for middleware configuration. 5. This module serves as the basis for developing your own aspects for your Spring-enabled application. Web MVC Module: It is given for two operations: 1. To integrate spring application with any other web based framework like Struts, JSF etc.., 2. It provides its own web framework anmed as Spring MVC to develop MVC-II architecture based web applications. It provides the MVC implementations for the web applications. Note: We can develop a spring application either by using all modules or only by using few modules of spring. We can also integrate our spring module with any kind of ajava application. So spring is loosely coupled. Spring is a open source, light weight, loosely coupled, aspect oriented & dependency injection based framework software which can be used to develop any kind of java/j2ee application. Open Source: Spring software can be downloaded and used at free of cost. Spring developed source code can referred by any one who is interested. Container is a special software which can manage complete life cycle of a given resource.

4 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Loosely Coupled: Need not to inherit any class or interface as we do for our servlet programming. Instead of having "is-a" relationship here we can have "has-a" relationship. Lightweight: 1. Spring is lightweight in terms of both size and overhead. 2. The entire Spring framework can be distributed in a single JAR file that weighs in at just over 1 MB. 3. Spring is nonintrusive: objects in a Spring-enabled application typically have no dependencies on Spring specific classes. 4. Mainly spring is used for business logic. The same business logic if we try to develop using EJB, then its compulsory to have support of any application server like weblogic. But the same logic can be executed in Spring without help of any web server or application server. Because Spring provides its own containers in the form of pre defined classes. Note:Servlet Container & EJB Container are heavy weight because unless we start web server or application server we cannot activate either servlet container or EJB Container. Inversion of control: 1. Spring promotes loose coupling through a technique known as inversion of control (IoC). 2. When IoC is applied, objects are passively given their dependencies instead of creating or looking for dependent objects for themselves. 3. The container gives the dependencies to the object at instantiation without waiting to be asked. Aspect-oriented: 1. Spring comes with rich support for aspect-oriented programming. 2. It enables cohesive development by separating application business logic from system services (such as auditing and transaction management). 3. Application objects do what theyre supposed to doperform business logicand nothing more. They are not responsible for (or even aware of) other system concerns, such as logging or transactional support. Container: 1. Spring is a container in the sense that it contains and manages the life cycle and configuration of application objects. 2. We can configure how each of our beans should be createdeither create one single instance of bean or produce a new instance every time one is needed based on a configurable prototype. Enterprise Application: Its a large scale appliaiton with complex business logic & configured with middleware services like transaction management, security etc.., Eg: Banking Applications. Dependency Lookup: This concept is used to find required resource among multiple resources. It takes some time to look up waht we need. It performs "PULL" operation to get required values. Eg: Getting JDBC DataSource object from registry server. Note: Registry servers are used to provide global visibility [to access from any where through out the world]. Eg: RMI Registry

5 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Dependency Injection [IOC Inversion Of Control]: Container software will gather all the required values and injects into resources of application dynamically. Here Dependent values will be pushed to resources dynamically by underlying container. Ex: The way how JVM/JRE calls constgructor of a class to assign some values at the time of object creation. Note: Using spring we can develop any kind of Java/J2EE application. But mostly in industry we can find spring used for development of Businesss Logic. Installation of spring: Download software & extract "Spring-framework-2.5.1-with dependencies.zip" file. Spring Jars: To work with any kind of spring applicaiton we need to set the classpath for two jar files. They are: 1. spring.jar [main jar file] [Location: sping-home\dist\spring.jar] 2. commons-logging.jar [Dependency jar file] [Location:] Normal Spring Application: 1. Compilation: Set the classpath for main jar file 2. Execution: Set the classpath for both main & dependency jar file. Becuase at run time of program the control transfers from main jar file to dependency jar file. Spring Web Applicaiton: 1. Compilation: Set the classpath for main jar file 2. Execution: Place both main & dependency jar files inside "lib" folder of WEB-INF. Note: Spring programs will make use of classes and interfaces resideing inside "spring.jar" file and the classes which are residing inside "spring.jar" file can make use of classes & interfaces which resides in dependency jar file "commons-logging.jar". Classpath: So when ever we need to work with a spring applicaiton its compulsory to set the classpath for all related main jar files and also dependent jar files.

179 180 181

Process of classpath setting: My Computer icon -> advanced -> environment variables -> system variables -> [if classpath variable is existing -> edit, if classpath variable doesn't exist then create a new classpath variable] & specify c;asspath.

6 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Note: 1. When we need set the classpath for multiple jar files, every jar file need to be specified with absolute path and every jar file path should be separated with semiclon [;] 2. The classpath what we specify in environmental variables will not be reflected to any ide like netbeans or eclipse or myeclipse etc.., 3. When we configure the same variable in user variable & system variable then user variables will dominate system variable [for path or classpath] 4. If any jar file missed in middle of classpath then the rest of classpath will be ignored. So always we need to specify our classpath in beginning of the path. Features of Spring: 1. Supports POJO/POJI model programming. 2. Provides two light weight containers in the form of pre defined classes. 1. Bean Factory Container or Core Container or IOC Container -org.springframework.beans.factory.BeanFactory Interface 2. JEE Container or Application Context Container. -org.springframework.beans.factory.xml.ApplicationContext interface 3. Spring containers are activated from server side programs. 4. Can be used to develop any kind of java/j2ee applications 5. We can develop an applicaition only by sing spring or we can also integrate spring with any other framework. 6. Provides built in middleware services like connection pooling, transaction management, logging etc., 7. Supports to work with third party supplied and web server or application server supplied middleware services. 8. Supports nested transaction & distributed transaction management. 9. Supports AOP framework to integrate with middleware services. 10. Provides anootation based mapping as a alternative to xml configuration which increases performance of the application. 11. Transaction Management: 1. Spring framework provides a generic abstraction layer for transaction management. 2. This allows the developer to add the pluggable transaction managers, and making it easy to do transactions without dealing with low-level issues. 3. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments. 12. JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy Specific API: API which is used for development of only a particular kind of application. Eg: servlet-api is used only for the purpose of web application development. POJO Classes: The classes that are not API dependent are called as POJO [Plain Old Java Object] classes. POJO: [plain old java object] A pojo class is a class which should not extend any predefined class belongs to specific API and it should not implement any predefined interface belongs to specific api.

7 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Following are pojo classes: class C1 { } class C2 extends C1 { } class C3 extends java.lang.Thread { } Note: Thread is a predefined class but its not confined for development of any particular kind of application. In another words Thread class can be used for any kind of java application. So our class C3 is a pojo class. class C4 implements java.lang.Runnable { } Note: Runnable is an interface which can be used to create a thread. So it can be used for development of any kind of java application. class C5 implements java.io.Serializable { } Note: Serializable interface implementation class objects will become serializable objects. So that we can transfer from one location to another location over the network. Following are not POJO classes: class C6 extends GenericServlet { } Note: GenericServlet class is used only for the purpose of web application development. So our class is not a pojo class. class C7 implements Servlet { } Note: Our class is implementing Servlet interface which is confined for development of web applications. class C8 implements java.rmi.Remote { } Note: Remote interface is used only for development of Distributed Applications. So the above class is not a pojo class. POJI Interfaces: The interfaces that are not API dependent are called as POJI [Plain Old Java Interface] POJI: [Plain Old Java Interface] Poji is an interface which should not extend any predefined interface which belongs to specific API.

8 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Examples of POJI are: interface I1 { } interface I2 extends I1 { } interface I3 extends Runnable { } interface I4 extends Serializable { } Examples of non POJI are: interface I5 extends Remote { } interface I6 extends Servlet { } Note: The above interfaces are non poji because they are extending interfaces which are api specific. Server: A program which is providing service is called as server. Client: A program which is giving request to get some service is called as client program. Local Client:If server and client both are executing under same JVM [Java Virtual Machine] then that client program can be called as a Local Client and server can be called as Local Server. Remote Client: If server and client both are executing under different JVM's then we can consider client as Remote client to server and server as Remote Server to client program. Spring Containers: 1. Core container or IOC container or BeanFactroy container 1. Its an implementation class of an interface BeanFactory 2. It supports lazy loading. 1. It means container will not create objects of cofigured pojo classes immediately. 2. It waits till it recieves the first request. 3. Once the object is created the same object will be maintained till end of the application. 3. 4. 5. 6. 7. By default it considers all the configured classes as singleton classes. So that the same object will be given to all requests which belongs to same class. We cannot change singleton scope for core container. provides the fundamental functionality of the Spring framework. BeanFactory, the heart of any Spring-based application.

2. Advanced container or ApplicationContext container 1. It is advanced container. 2. By default it supports early loading. 1. It means without recieving any request from client program immediately it will create object for every singleton scoped class.

9 315 316 317 318 319 320 321 322 323

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

2. When ever the container gets acivated immediately it creates objects of all singleton classes. 3. Has many advantages over core container. Execution of java program using Edit Plus editor: Once we configure Edit Plus we can compile and execute java programs just by using short cut keys. So it provides a great flexibility to develop java programs. Configure Compilation process: Tools [menu bar] configure user tools add tool program give menu text as javac/compile [which ever is comfortable to you] for command click on button with 3 dots [browse button] and locate javac from bin folder of JDK software.

324 325 326 327 328 329

Argument File Name Initial Directory File Directory Select check box of capture output Apply ok. Configure Execution process: give menu text as java/Execute [which ever is comfortable to you] for command click on button with 3 dots [browse button] and locate java from bin folder of JDK software.

330 331 332 333

Argument File Name Without Extension Initial Directory File Directory Select check box of capture output Apply ok. Note: Click on tools it shows you short cut keys to execute our java programs.

10 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Resources of spring core module application: 1. Interface [POJI] 1. It is optional in all applications except distributed applications. 2. It can contain prototype of our business logic methods. 2. Spring Bean class [POJO class] 1. It can be implementation class of our interfacc 2. It contains definition for business logic methods 3. It can have properties and values can be injected by spring container through DI [Dependency Injection]. 4. It can have setters methods or constructors to support dependency injection. 5. It can have user defined methods which can act as life cycle methods. 6. Along with business logic methods we can also have helper methods. 3. Spring Configuration file [*.xml file] 1. We can give any name for this xml file 2. standard name is to give as "applicationContext.xml" 3. Initially we need to specify either DTD (Document Type Definition) or XSD (XML Schema Definition) 4. Xml file can be validated based up on either XSD or DTD. 5. Its compulsory to specify either DTD or XSD. [DTD is traditional & XSD is advanced] 6. We can configure all bean classes [business logic classes] here. 7. We can configure user dfined classes & also predefined classes. 8. Every class can have a unique identification name. 9. We can also configure bean class properties here. Through this we can pass instructions to spring container to inject values with dependency injection. 10. Spring container works based up on the instructions what we have given in spring configuration file. 4. Client Program [*.java] 1. Locates spring configuration file 1. To locate spring configuration file regulary we will be using either ClasPathResource or FileSystemResource 2. Resource is interface 3. ClasPathResource & FileSystemResource both are implementation classes or Resource interface. 4. If client program & spring configuration file both resides in same folder then we can use any implementation class without any problem. 5. FileSystemResource: 1. If it is required to specify either abosolute path [Eg: c:\folder-name\filename.xml] or relative path [Eg: sub-folder-name\file-name.xml] in those cases we need to use FileSystemResource class. 2. Drawback: If we modify location of spring configuration file then again we need to modify either aboslute path or relative path in our program. 6. ClasPathResource: 1. We can create a jar file containing our spring configuration file and we can place it in our classpath. 2. So that the spring configuration file can be any where. But still our client program can access it. 3. Drawback: If we change our spring configuration file then again we need to create a jar file freshly. 2. Activates spring container

11 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

1. Here we can use BeanFactory interface and allocate memory of XmlBeanFactory class which is an implementation class of BeanFactory interface. 3. Reads spring configuration file: Once the container is activated automatically it reads spring configuration file. 4. Requests spring container to give object of any bean class by using identification name of the bean class. 5. By using bean class object we can call business logic methods. Example: Simple Spring Application. //interface program //DemoInter.java public interface DemoInter { public String wish(String uname); } //Implementation class //DemoInterImpl.java public class DemoInterImpl implements DemoInter { private String message; public DemoInterImpl() { System.out.println("Constructor executed"); } public void setMessage(String message) { System.out.println("setter method executed"); this.message=message; } public String wish(String uname) { return message+" "+uname+" Have a great day"; } } Note: We can copy paste DTD or XSD int ospring configuration file by searching xml files provided by our spring software.

418 419 420 421 422 423

Spring Configuration file //spring.cfg.xml //Here we are specifying DTD (Document Type Definition) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

12 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<beans> <bean id = "ic" class="DemoInterImpl"> <property name="message"> <value>Hello</value> </property> </bean> </beans> (or) //Here we are specifying XSD (XML Schema Definition) <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id = "ic" class="DemoInterImpl"> <property name="message"> <value>Hello</value> </property> </bean> </beans> //Client Program //DemoClient.java import org.springframework.core.io.Resource; import org.springframework.core.io.ClassPathResource; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; public class DemoClient { public static void main(String args[]) { //location of spring configuration file Resource res=new ClassPathResource("spring.cfg.xml"); //activation of spring container & then it reads spring configuration file BeanFactory factory=new XmlBeanFactory(res); //requesting object of a bean class by using its identification name DemoInter d=(DemoInter)factory.getBean("ic"); //calling business logic method System.out.println(d.wish("Sai")); } } Note: To execute any spring program basically we need to have the following jar files in classpath.

13 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Main Jar file: spring-framework-2.5.1\dist\spring.jar Dependency Jar file: spring-framework-2.5.1\lib\jakarta-commons\commons-logging.jar Singleton Demo: Note: All resources are same as above program. Only change in client program. import org.springframework.core.io.Resource; import org.springframework.core.io.ClassPathResource; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; public class DemoClient { public static void main(String args[]) { Resource res=new ClassPathResource("Demo.xml"); BeanFactory factory=new XmlBeanFactory(res); DemoInter d1=(DemoInter)factory.getBean("ic"); DemoInterImpl d2=(DemoInterImpl)factory.getBean("ic"); DemoInter d3=(DemoInter)factory.getBean("ic"); System.out.println(d1.wish("Sai"));

Note: 1. getBean() is a method which returns us super class Object. So we can classcast it to either our interface or implementation class. 2. We have requested the same class object for 3 times. But container creates only one object & the3 same object will be given for every request. 3. We can have any number of business logic methods inside the same class. Example: Configuring a predefined class object as property of pojo class. //spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="dat" class="java.util.Date"> <property name="year"> <value>85</value> </property>

14 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<property name="month"> <value>10</value> </property> <property name="date"> <value>19</value> </property> </bean> <bean id="demo" class="DemoInterImpl" > <property name="message"> <value>Njoy Spring Programming :)</value> </property> <property name="dt" > <ref bean = "dat"/> </property> </bean> </beans> //DemoInter.java public interface DemoInter { public void show(); } //DemoInterImpl.java import java.util.Date; public class DemoInterImpl implements DemoInter { private String message; private Date dt = null; public DemoInterImpl() { System.out.println("DemoInterImpl zero argument constructor"); } public void setMessage(String s) { System.out.println("setMessage() of DemoInterImpl class"); message=s; } public void setDt(Date dt) { System.out.println("setDt() of DemoInterImpl class"); this.dt = dt; }

15 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public void show() { System.out.println("Mesage is: "+message); System.out.println("Date is: "+dt); } } Client.java import org.springframework.core.io.Resource; import org.springframework.core.io.ClassPathResource; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; public class DemoClient { public static void main(String args[]) { Resource res=new ClassPathResource("spring.cfg.xml"); BeanFactory factory=new XmlBeanFactory(res); DemoInter d1=(DemoInter)factory.getBean("demo"); d1.show(); } } //Example: Configuring a user defined class object as property of pojo class. //DemoInter.java public interface DemoInter { public void show(); } DemoInterImpl.java import java.util.Date; public class DemoInterImpl implements DemoInter { private int age; private Date dt = null; //pre defined class private TestBean tb = null; //user defined class public DemoInterImpl() { System.out.println("DemoInterImpl zero argument constructor"); } public void setAge(int age) { this.age = age; } public void setDt(Date dt) { this.dt = dt; }

16 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public void setTb(TestBean tb) { this.tb = tb; } public void show() { System.out.println("Age is: "+age); System.out.println("Date is: "+dt); System.out.println("Message is: "+tb); } } //spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="dat" class="java.util.Date"> <property name="year"> <value>85</value> </property> <property name="month"> <value>10</value> </property> <property name="date"> <value>19</value> </property> </bean> <bean id="tbean" class="TestBean" > <property name="message"> <value>Hello friends.... Njoy this beautiful n gifted life :)</value> </property> </bean> <bean id="demo" class="DemoInterImpl"> <property name="age"> <value>25</value> </property> <property name="dt"> <ref bean = "dat"/> </property> <property name="tb" ref = "tbean"/> <!-- <ref bean = "tbean"/> </property> --> </bean> </beans> //DemoClient.java public class DemoClient { public static void main(String args[]) {

17 638 639 640 641 642 643 644 645 646

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Resource res=new ClassPathResource("spring.cfg.xml"); BeanFactory factory=new XmlBeanFactory(res); DemoInter d1=(DemoInter)factory.getBean("demo"); d1.show(); } } //Example: Different Bean Property Types Note: In a bean class we can have any type of properties. For the following properties we have corresponding tags to be onfigured in our spring configuration file. Bean Property type Tag in spring configuration file Primitive (or) java.lang.String Other bean type [class/interface type] Java.util.List type [stack, linkedlist] Java.util.Set Java.util.Map Java.util.Property <value> <ref> <list> <set> <map> <props>

647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

Java.util.Array or arrays <list> //DemoInter.java public interface DemoInter { public String sayHello(); } //DemoImple.java import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class DemoImple implements DemoInter{ private float salary; private TestBean tb = null; private Date dt = null; private List fruits = null; private List veg = null; private Set phone_nos = null; private Set emails = null; private Map perDetails = null; private Map capitals = null; private Properties faculties = null; private String courses[]; private int runs[]; public String sayHello() { return "Hello Friends... Gmg. :) "+ " salary = "+salary+ " tb = "+tb.toString()+ " dt = "+dt.toString()+ " fruits = "+fruits.toString()+ " veg = "+veg.toString()+

18 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

" phones = "+phone_nos.toString()+ " emails = "+emails.toString()+ " perDetails = "+perDetails.toString()+ " capitals = "+capitals.toString()+ " faculties = "+faculties.toString()+ " courses = {"+courses[0]+" "+courses[1]+"}"+ " runs = {" + runs[0]+" "+runs[1]+"}"; } public void setSalary(float salary) { this.salary = salary; } public void setTb(TestBean tb) { this.tb = tb; } public void setDt(Date dt) { this.dt = dt; } public void setFruits(List fruits) { this.fruits = fruits; } public void setVeg(List veg) { this.veg = veg; } public void setPhone_nos(Set phone_nos) { this.phone_nos = phone_nos; } public void setEmails(Set emails) { this.emails = emails; } public void setPerDetails(Map perDetails) { this.perDetails = perDetails; } public void setCapitals(Map capitals) { this.capitals = capitals; } public void setFaculties(Properties faculties) { this.faculties = faculties; } public void setCourses(String[] courses) { this.courses = courses; } public void setRuns(int[] runs) { this.runs = runs; } } //Note: Set doesn't allows duplicates but List allows

19 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id ="dat" class = "java.util.Date"/> <bean id ="tbean" class = "TestBean"> <property name="msg"> <value>Hello</value> </property> </bean> <bean id = "db" class = "DemoImple"> <property name="salary"> <value>5000</value> </property> <property name="tb"> <ref bean = "tbean"/> </property> <property name="dt"> <ref bean = "dat" /> </property> <property name="fruits"> <list> <value>Apple</value> <value>Banana</value> <value>Orange</value> </list> </property> <property name="veg"> <list> <value>Carrot</value> <value>Potato</value> <value>Mushrooms</value> <!-- any objects can be stored in a List--> <ref bean = "dat"/> <ref bean = "tbean"/> <value>Tomato</value> </list> </property> <property name="phone_nos"> <set> <value>7569670669</value> <value>9502166767</value> </set> </property>

20 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<property name="emails"> <set> <value>kanakavaraprasad@gmail.com</value> <value>s.varaprasad@yahoo.co.in</value> </set> </property> <property name="perDetails"> <map> <entry> <key> <value>Sai</value> </key> <value>Universal King</value> </entry> <entry> <key> <value>Kanakadhar</value> </key> <value>Service Provider</value> </entry> </map> </property> <property name="capitals"> <map> <entry> <key> <value>Sathya</value> </key> <value>Boon for learners</value> </entry> <entry> <key> <ref bean = "dat"/> </key> <ref bean = "tbean"/> </entry> </map> </property> <property name="faculties"> <props> <prop key="Kanakadhar">Java Faculty</prop> <prop key="Mahesh">.net Faculty</prop> </props> </property>

21 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!--Following both properties courses & runs are array variables. So we made use of list tag-> <property name="courses"> <list> <value>Java</value> <value>.net</value> <value>Oracle</value> </list> </property> <property name="runs"> <list> <value>30</value> <value>40</value> </list> </property> </bean> </beans> Note: While configuring dependent values for collection framework type bean properties, we can configure one data structure object as the element value of another data structure. //TestBean .java public class TestBean { String msg; public void setMsg(String msg) { this.msg = msg; } public String toString() { return msg; } } //DemoClient.java import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class DemoClient { public static void main(String[] args) { ClassPathResource res = new ClassPathResource("spring.cfg.xml"); XmlBeanFactory factory = new XmlBeanFactory(res); DemoImple d1 = (DemoImple) factory.getBean("db"); System.out.print(d1.sayHello()); } } Constructor injection: 1. If spring containers uses parameterized constructor to create spring bean class object and to set values to bean properties as initial values then it is called as constructor injection. 2. Constructor injection supports injecting values to all types of bean properties.

22 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

3. If properties of bean class [few or all properties] are configured for constructor injection then spring bean container creates spring bean class object by using parameterised constructor. 4. If all properties of spring bean class are configured only for setter injection then spring container creates spring bean class object by using zero parameterized constructor. 5. Using <constructor-arg> tag in spring configuration file the container performs constructor injection on bean properties. 6. While configuring bean properteis for constructor injection we must configure them in spring configuration file in the same order or sequence as they are placed in the constructor parameters. 7. On the same bean property of bean class if we configure both setter and constructor injection then the value injected through setter injection gets activated because setter methods gets executed after execution of constructor. So that the values of constructor injection gets overridden with values of setter injection. 8. We can configure constructor argument values in 4 ways: 1. Sequentially as specified in order of constructor 2. By specifying dataype [here no two arguments should contain same data type] 3. Using index of constructor arguments. [index of arguments starts from 0 [zero]]. 4. Combination of above 3. 9. Based on no. of <constructor-arg> tags specified in the bean class the same no. of parameterised constructor will be called by spring container. Eg:- If <constructor-arg> tag is placed for three times then three parameterised constructor gets executed. 10. Constructor injection is quick than setter injection. Because constructor gets executed at the time of object creation and setter methods gets executed after object creation. Constructor vs. Setter injection: Use constructor injection when you have to inject one or few properties and prefer setter injection when you have to inject more proeprties. Note: 1. Its not mandatory that all the bean class properties to be configured for dependency injection. 2. Maximum predefined classes supplied by spring are designed to support Setter injection. //Example:Constructor Injection //Demo.java public class Demo { private String message; public Demo() {} //dummy constructor public Demo(String message) //one parameterised constructor { this.message = message; }

23 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943

Sathya Technologies public String toString() { return message; }

Spring

Kanakadhar Surapaneni :)

} spring.cfg.xml <bean id="demo" class="Demo" > <constructor-arg> <value>Hello</value> </constructor-arg> </bean> Note: 1. Here all the tags like <value>, <ref>. <props>, <list>, <set>, <map> will remain same. But instead of using <property> tag we are making use of <constructor-arg> tag. 2. Client program is as usual. 3. As we are passing only one constructor argument in <bean> tag it invokes one parameterized constructor. //Exmple: Invoking Multiple Parametersized constructor public class Bean { private int a; private float b; private String c; public Bean(){} public Bean(int a, float b, String c) { this.a = a; this.b = b; this.c = c; } public String toString() { return a +" "+b+" "+c; } } //spring.cfg.xml //arguments in sequence <bean id = "be" class = "Bean"> <constructor-arg> <value>1</value> </constructor-arg> <constructor-arg> <value>1.1</value> </constructor-arg>

24 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984

Sathya Technologies <constructor-arg> <value>Gmg</value> </constructor-arg>

Spring

Kanakadhar Surapaneni :)

</bean> //Note: 1. In above style we have passed all the values in the form of sequence. 2. It means first <constructor-arg> value "1" will be given to first paramter of constructor. 3. second <constructor-arg> value "1.1" will be given to second paramter of constructor. 4. third <constructor-arg> value "Gmg" will be given to third paramter of constructor. //spring.cfg.xml //constructor arguments by using data type <bean id = "be" class = "Bean"> <constructor-arg type = "float" > <value>1.1</value> </constructor-arg> <constructor-arg type = "java.lang.String" > <value>Gmg</value> </constructor-arg> <constructor-arg type = "int" > <value>1</value> </constructor-arg> </bean> Note: 1. 2. 3. 4. First argument of "float" data type will be given to float parameter of constructor Scond argument of "java.lang.String" type will be given to String parameter of constructor Third argument of "int" type will be given to int parameter of constructor. But if the constructor has more than one parameter with same data type it will create error message due to ambiguity [confusion].

//spring.cfg.xml //constructor arguments by using index <bean id = "be" class = "Bean"> <constructor-arg index = "1"> <value>1.1</value> </constructor-arg> <constructor-arg index = "2"> <value>Gmg</value> </constructor-arg> <constructor-arg index = "0"> <value>1</value> </constructor-arg> </bean>

25 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 Note: 1. 2. 3. 4.

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Index always starts with 0 [zero] 0th index argument value will be given to 1st parameter 1st index argument value will be given to 2nd parameter 2nd index argument value will be given to 3rd parameter

//spring.cfg.xml //constructor arguments by using sequence, data type & index combination <bean id = "be" class = "Bean"> <constructor-arg index = "0" type ="int" > <value>1</value> </constructor-arg> <constructor-arg index = "1" type = "float"> <value>1.1</value> </constructor-arg> <constructor-arg index = "2" type = "java.lang.String"> <value>Gmg</value> </constructor-arg> </bean> Note: 1. We can make use of any of the above 4 styles. 2. But combination of sequence, index & type is the best way of configuring parameters. It will avoid confusion & increases readability of program. Due to this maintenance of application will become easy. 3. Client program is asusual. Example: Constructor injection with different bean property types //DemoInter.java public interface DemoInter { public String sayHello(); } //DemoImple.java public class DemoImple implements DemoInter{ private float salary; private TestBean tb = null; private Date dt = null; private List fruits = null; private List veg = null; private Set phone_nos = null; private Set emails = null; private Map perDetails = null; private Map capitals = null; private Properties faculties = null; private String courses[]; private int runs[];

26 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074

Sathya Technologies public String sayHello() {

Spring

Kanakadhar Surapaneni :)

return "Hello Friends... Gmg. :) "+ " salary = "+salary+ " tb = "+tb.toString()+ " dt = "+dt.toString()+ " fruits = "+fruits.toString()+ " veg = "+veg.toString()+ " phones = "+phone_nos.toString()+ " emails = "+emails.toString()+ " perDetails = "+perDetails.toString()+ " capitals = "+capitals.toString()+ " faculties = "+faculties.toString()+ " courses = {"+courses[0]+" "+courses[1]+"}"+ " runs = {" + runs[0]+" "+runs[1]+"}"; } public DemoImple(float salary, TestBean tb, Date dt, List fruits, List veg, Set phone_nos, Set emails, Map perDetails, Map capitals, Properties faculties, String[] courses, int[] runs) { this.salary = salary; this.tb = tb; this.dt = dt; this.fruits = fruits; this.veg = veg; this.phone_nos = phone_nos; this.emails = emails; this.perDetails = perDetails; this.capitals = capitals; this.faculties = faculties; this.courses = courses; this.runs = runs; } public DemoImple() {} //dummy constructor } //Note: 1. Same as the example of different property types with setter injection. There we made use of <property> tag. Now we are making use of <constructor-arg> tag. Interanally body of the <property> tag or <constructor-arg> tag will remain same. The only change is with outer tag. 2. Here we are following sequence while passing arguments to constructor. //spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd">

27 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<bean id ="dat" class = "java.util.Date"/> <bean id ="tbean" class = "TestBean"> <property name="msg"> <value>Hello</value> </property> </bean> <bean id = "db" class = "DemoImple"> <constructor-arg> <value>99.9</value> </constructor-arg> <constructor-arg> <ref bean = "tbean"/> </constructor-arg> <constructor-arg> <ref bean = "dat" /> </constructor-arg> <constructor-arg> <list> <value>Apple</value> <value>Banana</value> <value>Orange</value> </list> </constructor-arg> <constructor-arg> <list> <value>Carrot</value> <value>Potato</value> <value>Mushrooms</value> <!-- any objects can be stored in a List--> <ref bean = "dat"/> <ref bean = "tbean"/> <value>Tomato</value> </list> </constructor-arg> <constructor-arg> <set> <value>7569670669</value> <value>9502166767</value> </set> </constructor-arg> <constructor-arg> <set> <value>kanakavaraprasad@gmail.com</value> <value>s.varaprasad@yahoo.co.in</value> </set> </constructor-arg>

28 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165

Sathya Technologies <constructor-arg> <map> <entry> <key>

Spring

Kanakadhar Surapaneni :)

<value>Sai</value> </key> <value>Universal King</value> </entry> <entry> <key> <value>Kanakadhar</value> </key> <value>Service Provider</value> </entry> </map> </constructor-arg> <constructor-arg> <map> <entry> <key> <value>Sathya</value> </key> <value>Boon for learners</value> </entry> <entry> <key> <ref bean = "dat"/> </key> <ref bean = "tbean"/> </entry> </map> </constructor-arg> <constructor-arg> <props> <prop key="Kanakadhar">Java Faculty</prop> <prop key="Mahesh">.net Faculty</prop> </props> </constructor-arg> <constructor-arg> <list> <value>Java</value> <value>.net</value> <value>Oracle</value> </list> </constructor-arg>

29 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<constructor-arg> <list> <value>30</value> <value>40</value> </list> </constructor-arg> </bean> </beans> Note: Client program is asusual. Factory method: A method of a java class which is capable of constructing and returns its own class object. When spring bean class has private constructor we cannot create its object from outside. Then we can give instructions to spring container to create the object of bean class by using factory method. Note: 1. Factory methods can be of static or not static [instance method] 2. Factory method internally calls constructor at the time of object creation. No problem will be there even with private constructors. Because private constructors can be accessed from inside the class. 3. Factory methods should be public methods. So that can be accessed from outside the class. Eg of static factory methods: 1. Class c = Class.forName(ClassName); 2. Thread t = Thread.currentThread(); 3. Calendar cl = Calendar.getInstance(); Eg. on not static factory method [insanmce method] String s = new String(OK); String s1 = s.concat(Hello); //instance factory method. Instructions to spring container to call factory method: 1. We should use factory-method attribute of <bean> tag to configure the factory method to be called to create the object. 2. If factory method expects any arguments then pass required arguments using <constructorarg> tag. Factory Class: A class method which can return you another class object is called as Factory Class. Eg: Intege i1 = new Integer(100); String s1= i1.toString(); Note: Here by using toString() of java.lang.Integer class we are getting java.lang.String. It is returning this object by creating immediately. So we can call Integer class as factory class.

30 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Approaches to create spring bean class objects: 1. zero or parameterized constructor 2. static factory method of bean class 3. instance factory method of factory bean class Example: Static Factory Method //DemoInter.java public interface DemoInter { public String sayHello(); } // DemoBean.java import java.util.Calendar; public class DemoBean implements DemoInter { private Calendar cl = null; private TestBean tb = null; public DemoBean() { } public void setCl(Calendar cl) { this.cl = cl; } public void setTb(TestBean tb) { this.tb = tb; } public String sayHello() { return "tb = "+tb.toString()+" cl = "+cl.toString(); } } //TestBean.java public class TestBean { String msg; public TestBean() {} private TestBean(String msg) { this.msg = msg; System.out.println("Private Constructor invoked"); }

31 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//static factory method public static TestBean getTestBean(String msg) { System.out.println("static factory method invoked"); return new TestBean(msg); } public String toString() //to dispaly results { return msg; } } //spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id = "cal" class = "java.util.Calendar" factory-method = "getInstance"/> <bean id = "t1" class = "TestBean" factory-method = "getTestBean"> <constructor-arg> <!-- passing argument to factory method --> <value>Gmg. my dear friends...</value> </constructor-arg> </bean> <bean id = "db" class = "DemoBean"> <property name = "cl"> <ref bean = "cal"/> </property> <property name = "tb"> <ref bean = "t1"/> </property> </bean> </beans> //DemoClient.java public class DemoClient { public static void main(String[] args) { ClassPathResource res = new ClassPathResource("spring.cfg.xml"); XmlBeanFactory factory = new XmlBeanFactory(res); DemoBean d1 = (DemoBean) factory.getBean("db"); System.out.print(d1.sayHello()); } }

32 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Note: 1. The spring container uses factory method getInstance() to create bean class object for java.util.Calendar. 2. Spring container uses "getTestBean(String)" as factory method to create test bean class object. 3. Spring container uses zero parameterised constructor to create DemoBean class object. //Example: Instance Factory Method //DemoInter .java public interface DemoInter { public String sayHello(); } // DemoBean.java public class DemoBean implements DemoInter{ private TestBean tb = null; public DemoBean() { System.out.println("zero parametrized constructor of DemoBean class"); } public void setTb(TestBean tb) { this.tb = tb; } public String sayHello() { return "tb = "+tb.toString(); } //instance factory method public TestBean getTestBean(String msg) { System.out.println("demo bean factory method of DemoBean class"); return new TestBean(msg); } } //TestBean.java public class TestBean { String msg; public TestBean() {} //dummy constructor TestBean(String msg) { this.msg = msg; System.out.println("Constructor of TestBean class invoked"); }

33 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public String toString() //to dispaly results { return msg; } } //spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id = "t1" factory-bean = "db" factory-method = "getTestBean"> <constructor-arg> <!-- passing argument to factory method --> <value>Gmg. my dear friends...</value> </constructor-arg> </bean> <bean id = "db" class = "DemoBean"> <property name = "tb"> <ref bean = "t1"/> </property> </bean> </beans> //DemoClient .java public class DemoClient { public static void main(String[] args) { ClassPathResource res = new ClassPathResource("spring.cfg.xml"); XmlBeanFactory factory = new XmlBeanFactory(res); DemoBean d1 = (DemoBean) factory.getBean("db"); System.out.print(d1.sayHello()); } } Note: 1. Making spring container to create spring bean class object through non static methods [instance methods]. 2. While configuring spring bean class if class attribute is not there and factory-bean, factorymethod attributes are there then spring container uses instance factory method of specified factory bean class to create spring bean class object. Application Context container is enhancement of bean factory container with some advantages. Its features are as follows: 1. Pre initialization of beans by default. [Early loading]. It means in our spring configuration file we may have any no. of bean tags. Objects will be created sequentially for each and every bean class as specified in the sequence of <bean> tags in xml file. 2. Ability to read values of bean properties from properties file.

34 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402

Sathya Technologies 3. supports Internationalization (I18n)

Spring

Kanakadhar Surapaneni :)

4. Gives the ability to work with events & listeners. 5. org.springframework.context.ApplicationContext interface is the sub interface of org.springframework.beans.factory.BeanFactory interface. 6. Activating application context interface is nothing but creating object of a class that implements org.springframework.context.ApplicationContext interface. 7. There are three regularly used implementation classes of application context interface. By creating object for any of these three classes we can activate ApplicationContext container. 8. This container is available in JEE module. 9. org.springframework.context.support.FileSystemXmlApplicationContext: It activates application context container by locating given spring configuration file in the specified path. Ex: FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext(c:\f1\spriong.cfg.xml) 10.org.springframework.context.support.ClassPathXmlApplicationContext: It activates application context container by locating spring configuration file in the same working directory or from jar files added in the classpath. Ex: ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(spring.cfg.xml); 11.org.springframework.context.support.XmlWebApplicationContext: this class activates application context container by locating spring configuration file in deployment directory structure of web application by default in WEB-INF folder. Ex: XmlWebApplicationContext ctx = new XmlWebApplicationContext(spring.cfg.xml); 12.In real time applications we can find regularly working with Application Context container rather than working with Bean Factory container. 13.Application context container can perform all modes of dependency injection like bean factory container. 14.Application context container performs pre instantiation on all singleton scoped on spring bean classes of spring configuration file at the moment of application context container gets activated. 15.Pre-instantiation means creating spring bean class objects immediately after the application context container activation. 16.BeanFactory cannot perform this pre instantiation on spring bean classes. 17.when we call factory.getBean(_) then bean factory container immediately creates the object and uses the same for further requests on same id-value. 18.When we call ctx.getBean(_) then application context container gives access to bean id related spring bean class object which is created at pre-instantiation process. 19.Application context container can perform pre-instantiation only on singleton scoped spring bean classes that are configured in spring configuration file. 20.If we give scope value as prototype then object will not be created for bean at the time of pre-instantiation.

35 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

21.If the object is not created at pre-instantiation then it will be created after receiving the call along with its dependent objects. 22.If singleton scope bean class property has prototype scoped bean class object as dependent value then the application context container also creates prototype scoped spring bean class object during pre instantiation process along with singleton scope bean class object. 23.It happens to satisfy dependency injection needs done on singleton scope bean class properties. Example: Creation of our own singleton java class. //Designing our own singleton java class //Test.java public class Test { private static Test t = null; //private constructor-so no one can create object from outside the class private Test() { System.out.println("Private constructor of Test class invoked"); //static factory method public static Test getTest() { //singleton logic if(t == null) t = new Test(); return t;

Note: Also override clone() method of super class Object and throw CloneNotSupportedException. //Client.java class Client { public static void main(String[] args) { Test t1 = Test.getTest();

36 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 } }

Sathya Technologies Test t2 = Test.getTest(); Test t3 = Test.getTest(); System.out.println(t1); System.out.println(t2); System.out.println(t3);

Spring

Kanakadhar Surapaneni :)

Note: We have requested the same class object 3 times. But only one object gets created & the same object will be given for all 3 times. Scopes of Bean class objects under ApplicationContext container: We can make spring container to keep the created spring bean objects in different scopes. They are: 1. singleton [default scope] 2. prototype 3. request 4. session 5. global session singleton: container makes spring bean class object as shared object for multiple calls given to factory.getBean() with bean id. Eg: <bean id = bd class = BeanDemo scope = singleton/> The client application may call factory.getBean(bd) for multiple times. Still the spring container creates and returns only one DemoBean class object. Singleton java class means the java class that allows to create only one object per jvm. It means the class has restriction related logic. Note: In the above example BeanDemo class need not to be designed as singleton java class. But container creates only one object for DemoBean class. Here its the responsibility of spring container. When spring bean scope is singleton the spring container never makes spring bean class as singleton java class but spring container restricts itself and creates only one object for spring bean class though factory.getBean(id) is called for multiple times. Prototype: It gives an independent spring bean class object for each call to factory.getBean(id); Eg: <bean id = db class = DemoBean scope = prototype/> request, session, global session are used for web applications. request: Only one object will be used from beginning to end of the same request. session: from beginning to expiry of same session single object will be used. global session: Its commonly shared by the entire web application. Note: When we give setter injection we should not give only parameterized constructor in the class.

37 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Because when no <constructor-arg> tags are available in spring configuration file then spring container tries to create object by using default [zero parameterized] constructor. If its not available then immediately error arises. When no constructors (zero or parameterized) are available in the class then automatically compiler creates a default and zero parameterized constructor. //Example: First application with ApplicationContext or JEE or Advanced Container //Client steps: 1. Locate Spring-Configuration file + Activate ApplicationContext Container + Read SpringConfiguration file 2. Request object of business-logic class. 3. Call business-logic methods. 4. Close container //DemoInter.java public interface DemoInter { public String wish(String uname); //DemoInterImpl.java public class DemoInterImpl implements DemoInter { private String message; public DemoInterImpl() { System.out.println("Constructor executed"); public void setMessag(String s) { message=s; public String wish(String uname) { return message+" "+uname+" Have a great day";

38 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id="demo" class="DemoInterImpl" > <property name="messag"> <value>Hello</value> </property> </bean> </beans> //DemoClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient { public static void main(String args[]) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.cfg.xml"); DemoInter d1=(DemoInter)ctx.getBean("demo"); DemoInterImpl d2=(DemoInterImpl)ctx.getBean("demo"); System.out.println(d1.wish("Sai")); ctx.close();

Note: We are requesting the same class object twice. But container creates only one object & gives the same object for every request. Example: Prototype scope Note: 1. Same as above example. We are giving a new attribute for our <bean> tag as shown below in spring configuration file. 2. If we donot specify any scope by default the scope will be singleton. 3. If the scope is prototype:

39 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 }

Sathya Technologies 1.

Spring

Kanakadhar Surapaneni :)

for every request a separate object will be created.

2. Without recieving the request object will not be created by container. <bean id="demo" class="DemoInterImpl" scope="prototype"> <property name="messag"> <value>Hello friends... Gmg. :)</value> </property> </bean> Interface Injection: 1. If sring container performs dependency injection on bean properties by implementing the XxxAware interfaces then it is called as interface injection. 2. All these XxxAware interfaces are predefined interfaces supplied by spring api on one bean spring bean class property. 3. We can perform all 3 types of dependency injection. 4. We cant use interface injection to inject our own values. 5. Interface injection can perform special values injection given by spring container. Predfined interfaces used for dependency injection: 1. org.springframework.beans.factory.BeanNameAware interface makes spring bean class getting its bean id given in spring configuration file through interface injection. 2. org.springframework.beans.factory.BeanFactoryAware interface injects the current underlying bean factory container to spring bean class through interface injection. 3. org.springframework.context.ApplicationContextAware injects the current underlying application context container to spring bean class. Note: 1. While performing interface injection on spring bean class the spring bean class cant act as pojo class. 2. Interface injection is useful to make spring bean to know about itself and other spring beans managed by the container. Example: Interface Injection //Demo.java public interface Demo { String hi(); //DemoBean.java import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanNameAware; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware;

40 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public class DemoBean implements Demo, BeanNameAware, ApplicationContextAware{ String msg, bname; ApplicationContext ctx = null; public void setMsg(String msg) { this.msg = msg; public void setApplicationContext(ApplicationContext ctx) throws BeansException { this.ctx = ctx; public void setBeanName(String bname) { this.bname = bname; public String hi() { System.out.println("Logical current bean name is: "+bname); System.out.println("No. of beans managed by underlying container is: "+ctx.getBeanDefinitionCount()); System.out.println("Current bean is singleton: "+ctx.isSingleton(bname)); System.out.println("Current bean is proptotype bean: "+ctx.isPrototype(bname)); return msg;

// applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id = "db" class = "DemoBean"> <property name="msg"> <value>Hi Friends... Gmg. Njoy Spring concepts n coding. :)</value> </property> </bean> <bean id = "dt" class = "java.util.Date" scope = "prototype"/> <bean id = "dt1" class = "java.util.Date"/> </beans>

41 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//DemoClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Date; public class DemoClient { public static void main(String args[]) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Demo d1=(Demo)ctx.getBean("db"); Date d2=(Date)ctx.getBean("dt"); //DemoImpl d2=(DemoImpl)ctx.getBean("db"); System.out.println(d1.hi()); System.out.println(d2);

Reading Properties File: Place holder represents bean property value that should be collected from properties file based on the given key name dynamically at runtime of the program. Purpose of properties file in spring application: properties files and xml files are given to make java application code as flexible by passing input values of application from outside the application. Note: 1. Work with properties files only when our spring application is forced to work with existing properties file. Dont create new properties files because the same flexibility can be achieved with xml file (spring configuration file) also. 2. The standard principle of s/w industry is dont hard code any values that can be modified in future or changed for regular intervals. Eg: jdbc driver class name, url, username, password etc.., Example: Reading a values from properties file & writing to spring configuration file.

42

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665

Note: In properties file we can specify comments by using # or ! //data.properties #demo.properties our.name = Dharani our.age = 25 our.address = Hyd our.email = dharani@gmail.com //DemoBean.java public class DemoBean { String name, email, address; int age; public void setName(String name) { this.name = name; } public void setEmail(String email) { this.email = email; } public void setAddress(String address) { this.address = address; } public void setAge(int age) { this.age = age; }

43 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 } }

Sathya Technologies public String hi() {

Spring

Kanakadhar Surapaneni :)

return name+" "+age+" "+email+" "+address;

//applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id = "propConfig" class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value = "pf\demo.properties"> <!-</bean> <bean id = "db" class = "DemoBean"> <property name="name"> <value>${our.name}</value> </property> <property name="email"> <value>${our.email}</value> </property> <property name="address"> <value>${our.address}</value> </property> <property name="age"> <value>${our.age}</value> </property> </bean> </beans> <value>demo.properties</value> --> </property>

44 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//DemoClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient { public static void main(String args[]) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DemoBean d = (DemoBean) ctx.getBean("db"); System.out.println(d.hi());

Example: Reading data from multiple properties files #pf1.properties name = Dharani age = 25 #pf2.properties address = Hyd email = dharani@gmail.com name = Sathya Note: 1. "name" property is there in both properties files. So first property file value will be replaces with second property file value. 2. DemoBean.java & DemoClient.java files are same as above example. //applicationContext.xml <bean id = "propConfig" class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>pf1properties</value> <value>pf2.properties</value> </list> </property> </bean>

45 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<bean id = "db" class = "DemoBean"> <property name="name"> <value>${name}</value> </property> <property name="email"> <value>${email}</value> </property> <property name="address"> <value>${address}</value> </property> <property name="age"> <value>${age}</value> </property> </bean> Example: Reading multiple configuration files //applicationContext1.xml <beans> <bean id = "t1" class = "TestBean"> <property name="msg"> <value>Hello friends Gmg.</value> </property> </bean> </beans> //applicationContext2.xml <beans> <bean id = "d1" class = "DemoBean"> <property name="tb"> <ref bean = "t1"/> </property> </bean> </beans> Note: "applicationContext2.xml" is reading identification name of "applicationContext1.xml" file. It means we may have any number of configuration files for the purpose of easy organization, still programaticdally we can consider them as a single file.

46 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 } } } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//DemoBean.java public class DemoBean { TestBean tb = null; public void setTb(TestBean tb) { this.tb = tb; public String toString() { return tb.msg;

// TestBean.java public class TestBean { String msg; public void setMsg(String msg) { this.msg = msg; public String toString() { return msg;

//DemoClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient { public static void main(String args[]) { String cfg[] = {"applicationContext2.xml", "applicationContext1.xml"}; ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(cfg); DemoBean d = (DemoBean) ctx.getBean("d1"); System.out.println(d);

47 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Internationalization (I18n): 1. Making our application projects working for multiple locales with flexibility in presentation logic to pass display labels of input fields or any information from outside the application is called applying I18n on the project. 2. The project i.e., enabled with I18n can give service to multiple client organizations which may belong to multiple communities without changing source code. Locale = language + country Examples for Language code & country code: En-us [English United States] En-au [English Australia] En-ca [English Canada] En-ie [English Ireland] En-nz [English new zealand] En-zw [English Zimbabwe] En-gb [English United Kingdom] Fr-be [French Belgium] Fr-ca [French Canada] Fr [French france] Fr-ch [French Switzerland] 3. All the above locales codes are given by ISO we can collect them from IE [Internet explorer] browser window settings as follows: Tools Internet options languages Add [it shows you multiple countries with multiple languages. So we can choose what we need for our applications] 4. Here we write a separate properties file for each language and we furnish all the labels in it for display of labels based on internet options of browser.

5. In java application we use Locale class & ResourceBundle class of java.util package to apply the effect of I18n. 6. While preparing multiple locale specific properties files the base file must be there because when no matching file is available then values will be taken from this base file. 7. Org.springframework.conext.support.ResouceBundleMessageSource class makes the underlying application context container recognizing multiple locale properties files on I18n that are given to the application. 8. In order to make the container to get message from properties file we need to call getMessage() method on the container object. 9. For getMessage() method we have to pass 4 argumetns. They are: 1. key in properties file 2. java.lang.Object class array to pass argument values to place holders available in property values. If place holders are not there then we can pass null.as a value.

48 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

3. Default message: when message from given key is not collectable default message will be displayed. 4. java.util.Locale class object with language and country code. Example: Spring Internationalization #app.preoperties [base file] str1 = save - {0}english {1} str2 = clear - english str3 = delete - english str4 = cancel - english Note: 1. "Str1" property has two place holders. 2. Every poperty value can have place holders 3. Always place holders starts with zero. 4. For every property value place holder values can be supplied through string array variable. #app_en_ca.preoperties [english canada] str1 = save - {0} english {1} canada str2 = clear - english canada str3 = delete - english canada str4 = cancel - english canada #app_en_gh.preoperties [uk] str1 = save -{0} english {1} uk str2 = clear - english uk str3 = delete - english uk str4 = cancel - english uk #app.preoperties [french belgium] str1 = save - {0} french {1} belgium str2 = clear - french belgium str3 = delete - french belgium str4 = cancel - french belgium //applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd">

49 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<bean id = "messageSource" class = "org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"> <value>app</value> </property> </bean> </beans> //I18nApp.java import java.util.Locale; import org.springframework.context.support.ClassPathXmlApplicationContext; public class I18nApp { public static void main(String args[])throws Exception { Locale l = new Locale(args[0], args[1]); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); String msg = ctx.getMessage("str1", new String[]{"hi", "Sai"}, "default msg", l); msg +=" "+ ctx.getMessage("str2", null, "default msg", l); msg +=" "+ ctx.getMessage("str3", null, "default msg", l); msg +=" "+ ctx.getMessage("str4", null, "default msg", l); System.out.println("Message is: "+msg);

Event Handling: Event is specific action performed on the component or object. To handle events and execute same logic every time we can depend upon listeners. These listeners provide event handling methods to handle the events. All events are objects and all listeners are interfaces in java environment In order to perform event handling four details are required: 1. Source object [Eg: Button component] 2. Event [Eg: ActionEvent] 3. Listener [Eg: ActionListener] 4. Event handling methods [Eg: public void actionPerform()] In spring environment event handling is given to notify when the spring container is activated or deactivated in spring based applications or other java applications where spring is also used. This event handling helps the programmer to notice how much time the spring related business logic is executed in the project. To perform event handling on spring application we need the following details:

50 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

1.source object [application context container] 2.event [application event] 3. listener [application listener] 4.event handling methods on application event ApplicationContext container supports 3 events: 1. ContextRefreshedEvent 2. RequestHandledEvent[Supported only in web applications. It gets activated for every request] 3. ContextClosedEvent Note: 1. Event handling on spring container can be performed without touching existing java source code of application. 2. For more information on this refer 3.8.3 Events topic of spring PDF file. Example: Event Handling public interface DemoInter { public String wish(String uname); public class DemoInterImpl implements DemoInter { private String message; public DemoInterImpl() { System.out.println("Constructor executed"); public void setMessag(String s) { message=s; public String wish(String uname) { return message+" "+uname+" Have a great day";

51 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

// Helper.java import java.util.Date; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; public class Helper implements ApplicationListener { long startTime, endTime; public void onApplicationEvent(ApplicationEvent ae) { System.out.println("control in onApplicationEvent method"); System.out.println(ae.toString()); int index = ae.toString().indexOf("ContextRefreshedEvent"); System.out.println("Index is: "+index); if(index != -1) { startTime = System.currentTimeMillis(); System.out.println("Container started at "+new Date().toString()); } else if(ae.toString().indexOf("ContextClosedEvent") != -1) { endTime = System.currentTimeMillis(); System.out.println("Container is Closed at "+new Date().toString()); System.out.println("Container is in activated mode for "+(endTime startTime)+" milli seconds"); }

//spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id = "help" class = "Helper"/> <bean id="demo" class="DemoInterImpl" > <property name="messag">

52 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<value>Hello</value> </property> </bean> </beans> //DemoClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient { public static void main(String args[])throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.cfg.xml"); DemoInter d1=(DemoInter)ctx.getBean("demo"); //DemoInterImpl d2=(DemoInterImpl)ctx.getBean("demo"); System.out.println(d1.wish("Sai")); Thread.sleep(2000); ctx.close(); //container gets closed now

User defined life cycle methods: Spring bean class allows configuring our user defined methods to act like life cycle methods. 1. init () life cycle method: container calls this method automatically after dependency injection process is completed on bean properties. 2. destroy() life cycle method: Container calls this method just before destruction of spring bean class object created by spring container. We can configure these life cycle methods in two ways: 1. Programmatic statements [by implementing the following interfaces] 1. InitializingBean 1. afterPropertiesSet() 2. DisposableBean 1. destroy() 2. Declarative statements 1. <bean> attributes 1. init-method 2. destroy-method

53 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

As these life cycle methods are user defined methods their names should be configured during spring bean class configuration in spring configuration file by using init-method and destroymethod attributes of <bean> tag. Note: We can give any names for these life cycle methods. But init & destroy are standard names. Any way what ever the name it is, its mandatory to configure them in configuration file. Init() method is useful to check whether appropriate values were injected to spring bean properties are not through dependency injection. destroy() life cycle method is useful to nullify bean properties and to release non java resources associated with bean properties when spring bean class object is about to destroy. Example: Programmatic initialization method import org.springframework.beans.factory.InitializingBean; public class Init implements InitializingBean{ int p1; public Init() { System.out.println("In constructor"); public void setP1(int p1) { System.out.println("Insetter method"); this.p1 = p1; public void afterPropertiesSet() throws Exception { System.out.println("in after proeprties set "+p1);

//applicationContext.xml <beans> <bean id="in" class="Init"> <!-- init-method = "init" --> <property name = "p1" value = "10"/> </bean> </beans> //DemoClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient { public static void main(String[] args) {

54 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Init i1 = (Init) ctx.getBean("in"); System.out.print(i1);

Example: Programmatic destroy method import org.springframework.beans.factory.DisposableBean; public class Destroy implements DisposableBean{ int p1; public Destroy() { System.out.println("In constructor of Destroy class"); public void setP1(int p1) { System.out.println("Insetter method"); this.p1 = p1; public void destroy() throws Exception { System.out.println("In destructor of Destroy class");

//applicationContext.xml <beans> <bean id="de" class="Destroy"> <property name = "p1" value = "20"/> </bean> </beans> //DemoClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient { public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Destroy d = (Destroy) ctx.getBean("de"); System.out.print(d); ctx.close();

55 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//Example: Declarative init() method Note: 1. By using declarative statements we can configure any method as a init() method. 2. Need not to implement any interface in case of declarative approach. //Init.java public class Init{ int p1; public Init() { super(); System.out.println("In constructor"); public void setP1(int p1) { System.out.println("In setter method"); this.p1 = p1; public void init() { System.out.println("in user defined call back method");

//applicationContext.xml <beans> <bean id="in" class="Init" init-method = "init"> <property name = "p1" value = "100"/> </bean> </beans> // DemoClient.java import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class DemoClient { public static void main(String[] args) { ClassPathResource res = new ClassPathResource("applicationContext.xml");

56 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 </bean> } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

XmlBeanFactory factory = new XmlBeanFactory(res); Init i1 = (Init) factory.getBean("in"); System.out.print(i1);

//Example: Declarative destroy() method Note: 1. By using declarative statements we can configure any method as a destroy() method. 2. Need not to implement any interface in case of declarative approach. //Destroy.java public class Destroy { int p1; public Destroy() { System.out.println("In constructor of Destroy class"); public void setP1(int p1) { System.out.println("In setter method"); this.p1 = p1; public void destroy() { System.out.println("In destructor of Destroy class");

//applicationContext.xml <beans> <bean id="de" class="Destroy" destroy-method = "destroy"> <property name="p1"> <value>11</value> </property> </beans> Note: Client program is same as above Inner Beans: If we define a <bean> tag inside another bean tag then we call it as inner bean. Inner beans are used to provide security. If a class is declared as independent bean then the same class can be used by any other class. The same class if we declare as a inner bean then it can be used only by outer bean class.

57 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 } } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Example: public class First { int a; int b; public void setA(int a) { this.a = a; public void setB(int b) { this.b = b; @Override public String toString() { return a+" "+b;

public class Second { First f; public void setF(First f) { this.f = f; @Override public String toString() { return f.toString();

//applicationContext.xml <beans> <bean id = "two" class = "Second"> <property name="f"> <bean class = "First"> <property name="a"> <value>10</value> </property> <property name="b"> <value>20</value>

58 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 } } } } } }

Sathya Technologies </property> </bean> </property> </bean>

Spring

Kanakadhar Surapaneni :)

</beans> //Client.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class Client { public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Second s = (Second) ctx.getBean("two"); System.out.println(s);

Multiple Constructors: In a same class we can have multiple constructors. When ever we need to call multiple constructors through constructor injection then we need to configure the same class more than one time as shown in below example. Example: Calling different constructors of the same class //Bean.java public class Bean { int sno; String sname; public Bean() {} public Bean(String sname) { this.sname = sname; public Bean(int sno, String sname) { super(); this.sno = sno; this.sname = sname; public String toString() { return sno+" "+sname;

59 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

// applicationContext.xml <beans> <bean id = "one" class = "Bean"> <constructor-arg> <value>Sai</value> </constructor-arg> </bean> <bean id = "two" class = "Bean"> <constructor-arg> <value>1</value> </constructor-arg> <constructor-arg> <value>Kanakadhar</value> </constructor-arg> </bean> </beans> //Client.java import org.springframework.context.support.ClassPathXmlApplicationContext; public final class Client { public Client() {} public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); Bean b1 = (Bean) ctx.getBean("one"); //calls one parameter constructor Bean b2 = (Bean) ctx.getBean("two");//calls two parameterized constructor System.out.println(b1); System.out.println(b2);

FactoryBean: BeanFactory: 1. A special bean class that can return other class object instead of its own object is called as FactoryBean. 2. In our regular programming we will come across many predefined FactoryBean classes. 3. When factory bean configuration bean id is configured as dependent value to our bean class property will not be injected with factory bean class object. It will be injected with some other class object returned by factory bean class.

60 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

4. To make spring bean class as factory bean class make that bean class to implement org.springframework.beans.factory.FactoryBean interface. Example: To create our own FactoryBean class. //Demo.java public interface Demo { String hi(); //DemoBean.java import java.util.Calendar; import java.util.Date; public class DemoBean implements Demo{ private Date dt; private Calendar cl; public void setDt(Date dt) { this.dt = dt; public void setCl(Calendar cl) { this.cl = cl; public String hi() { return "date: "+dt+" cl = "+cl;

//TestBean.java [FactoryBean class] import java.util.Calendar; import org.springframework.beans.factory.FactoryBean; public class TestBean implements FactoryBean{ public Object getObject() throws Exception { System.out.println("getObject()"); Calendar cl = Calendar.getInstance(); return cl;

61 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 } } } }

Sathya Technologies public Class getObjectType() {

Spring

Kanakadhar Surapaneni :)

System.out.println("getObjectType()"); return Calendar.class; public boolean isSingleton() { System.out.println("isSingleton()"); return true;

Note:TestBean class returns object of Calendar class. // applicationContext.xml <beans> <bean id = "dat" class = "java.util.Date"/> <bean id = "tbean" class = "TestBean"/> <bean id = "db" class = "DemoBean"> <property name="dt"> <ref bean = "dat" /> </property> <property name="cl"> <ref bean = "tbean"/> </property> </bean> </beans> //DemoClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient { public static void main(String args[]) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DemoBean d = (DemoBean) ctx.getBean("db"); System.out.println(d.hi());

62 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Wiring: The process of configuring bean properties and performing dependency injection on bean is called as wiring operation. There are two types of wiring operations: 1. Explicit wiring 2. Auto wiring If spring bean properties are configured explicitly in spring configuration file for dependency injection is called as explicit wiring. The dependency injection configurations that we have done so far in our programming come under explicit wiring. If container is detecting dependant values to bean properties automatically without any configuration of properties, then it is called as auto wiring. Limitations of auto wiring: 1. Only bean references can be injected. It means simple values of int, float etc.., cant be injected. 2. There is a possibility of ambiguity (confusion) problem. If multiple suitable dependent values are found for a bean property in auto wiring. Spring allows auto wiring in 4 modes: 1. by name 2. by type 3. by constructor 4. by auto detect To enable auto wiring on spring bean we need to use auto wire attribute of <bean> tag. 1. byName: This performs setter injection on bean property. The name of bean property and bean id of dependent bean class object must match by name. Note: We should use auto wiring on bean property only when the bean property is ready to take another spring bean class object as a dependent value. No two bean tags should have same bean id. But same bean class can be configured with separate bean ids using separate bean tags. 2. byType: Performs setter injection on bean properties. In this mode of auto wiring the data type of bean properties must match with the dependent bean object data type. Here it doesnt checks whether the names were matched or not. Note: No two properties should be configured with same data type. If it happens it will raise ambiguity error. 3. constructor: it performs dependency injection on bean properties by using the parameterized constructors [constructor injection]. Here also names need not to match but an appropriate parameterized constructor should be available. 4. autodetect: Chooses constructor or byTypemode of auto wiring by scanning the details of spring bean class. If zero argument constructor is found inspring bean class then byType mode of auto wiring takes place. If appropriate and only parameterized constructor is available then constructor mode of auto wiring takes place.

63 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Note: While working with pre defined spring bean classes and if we do not know its properties names or constructor details particularly then we can use this auto wiring concept. Auto wiring is useful to work with predefined classes and third party APIs. In auto wiring and explicit wiring both were configured with same setter injection on single bean property with two different values then the explicit values will be affected. Eg: byName & explicit. If auto wiring is performing setter injection and explicit wiring is performing constructor injection on same bean properties with different values then auto wiring values will be affected. If auto wiring performs constructor injection and explicit wiring is performing setter injection on the same property with different values then explicit values will be affected. Note: We can also go for few properties with explicit wiring and few properties with autowiring. //Demo.java public interface Demo { String hi(); // DemoBean.java public class DemoBean implements Demo{ TestBean tb = null; public DemoBean() { System.out.println("Zero arg constructor of DemoBean class"); public DemoBean(TestBean tb) { System.out.println("One arg constructor of DemoBean class"); this.tb = tb; public void setTb(TestBean tb) { System.out.println("setTb() of DemoBean class"); this.tb = tb; public String hi() { return tb.toString();

64 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 Note: } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//TestBean.java public class TestBean { String msg; public TestBean() { System.out.println("zero arg. constructor of TestBean class."); public void setMsg(String msg) { System.out.println("setMsg() of TestBean class"); this.msg = msg; @Override public String toString() { return msg;

//applicationContext.xml [Autowiring by name: Here TestBean class "id" & DemoBean class property both are having same names. ] <beans> <bean id = "tb" class = "TestBean"> <!-- Explicit wiring --> <property name="msg"> <value>Hi friends... Keep Rocking. :)</value> </property> </bean> <bean id = "db" class = "DemoBean" autowire = "byName"/> </beans> 1. When we go for explicit wiring through setter injection then autowiring values will be overridden and explicit wiring values will be displayed. 2. When we go for explicit wiring through constructor injection then constructor injection values will be overridden by autowiring values

65 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 Note: } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//DemoClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient { public static void main(String args[]) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DemoBean d = (DemoBean) ctx.getBean("db"); System.out.println(d.hi());

Exmple: Setter injection will always dominate Constructor injection <!-- applicationContext.xml --> <beans> <bean id = "tb" class = "TestBean"> <!-- Explicit wiring --> <property name="msg"> <value>Hi friends... Happy Republic Day.... :)</value> </property> </bean> <bean id = "tb1" class = "TestBean"> <property name="msg"> <value>Gmg. friends.... :)</value> </property> </bean> <bean id = "db" class = "DemoBean" autowire = "byName"/> <constructor-arg> <ref bean = "tb1"/> </constructor-arg> </bean> </beans> 1. Here explicitly we are doing constructor injection. 2. First of all constructor values will be injected & again setter values will be injected. 3. So that setter values will be displayed & constructor values will be ignored.

66 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 Note:

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//Example: Explicit injection dominates implicit injection when both are using either setter or constructor injection <beans> <bean id = "tb" class = "TestBean"> <!-- Explicit wiring --> <property name="msg"> <value>Hi friends... Happy Republic Day.... :)</value> </property> </bean> <bean id = "tb1" class = "TestBean"> <property name="msg"> <value>Gmg. friends.... :)</value> </property> </bean> <bean id = "db" class = "DemoBean" autowire = "byName"/> <property name="tb"> <ref bean = "tb1"/> </property> </bean> </beans> 1. In the above example auto wiring & explicit wiring both are trying to do setter injection. In this case explicit injection will dominate implicit injection. 2. Similarly if auto wiring & explicit wiring both are trying to do constructor injection, then also explicit injection will dominate implicit injection. //Example: byType Note: The entire example is same. The only modification is with configuration file. <!-- applicationContext.xml --> <bean id = "t1" class = "TestBean"> <!-- Explicit wiring --> <property name="msg"> <value>Gmg. friends... Have a joyful day. :)</value> </property> </bean> <bean id = "db" class = "DemoBean" autowire = "byType"/> </beans>

67 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 Note:

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

1. Here TestBean class "id" & DemoBean class property both are different. But still here autowiring is working based up on data type of bean class property & Bean class. 2. In autowiring with byType the same class should not be configured more than once. //Example: We should not do as follows: Because TestBean class is configured more than once where byType is used. If we configure more than once then it will throw amiguity error. <!-- applicationContext.xml --> <beans> <bean id = "t1" class = "TestBean"> <!-- Explicit wiring --> <property name="msg"> <value>Gmg. friends... Have a joyful day. :)</value> </property> </bean> <bean id = "t2" class = "TestBean"> <property name="msg"> <value>Gmg.... friends Have a joyful day. :)</value> </property> </bean> <bean id = "db" class = "DemoBean" autowire = "byType"/> </beans> //Example: constructor Note: The entire example is same. The only modification is with configuration file. <!-- applicationContext.xml --> <beans> <bean id = "t2" class = "TestBean"> <!-- Explicit wiring --> <property name="msg"> <value>Gmg. friends... Have a joyful day. :)</value> </property> </bean> <bean id = "db" class = "DemoBean" autowire = "constructor"/> </beans>

68 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//Example: autodetect <!-- applicationContext.xml --> Note: The entire example is same. The only modification is with configuration file. <beans> <bean id = "t1" class = "TestBean"> <!-- Explicit wiring --> <property name="msg"> <value>Gmg. friends... Have a joyful day. :)</value> </property> </bean> <bean id = "db" class = "DemoBean" autowire = "autodetect"/> </beans> DAO Module: Spring DAO: Connection pooling: Every jdbc data source object represents one jdbc connection pool. To access each connection object of connection pool we need to work with jdbc data source object. Jdbc connection pool is a factory that contains set of readily available jdbc connection objects before actually being used. In spring application we can work with 3 types of connection pools: 1. spring built in jdbc connection pool [org.sf.jdbc.datasource.DriverManagerDataSource class] Note: This connection pool is not real jdbc connection pool. Because it does not pool jdbc connection objects. Moreover it creates one jdbc connection object dynamically based on demand. Using this style is not industrial standard. 2. Using third party connection pool softwares. [c3p0, proxool, dc30, apache.. etc.,] 3. Using web/application server managed jdbc connection pools. If our application is stand alone application or the application that runs outside the server [web/application server] then use third party connection pooling. If our spring application is deployed in web/application server then use server managed connection pooling. DAO class: 1. The java class or application that separates persistence logic from other applications is called as DAO. 2. DAO is very useful to make persistence logic as flexible logic for modification with out affecting the other logics of the application. 3. Spring DAO module is given to develop jdbc style persistence logic in any layer of the project by getting abstraction layer on jdbc programming. 4. Using spring DAO module we can develop jdbc style persistence logic without directly using jdbc logic and without performing common jdbc operations like establishing

69 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

connections, transaction management, jdbc operations, createing & closing of statement objects etc Plain jdbc code: 1. load or register jdbc driver 2. establish connection to database 3. create statement object 4. begin transaction 5. Perform persistent operations like insert, update, delete or read etc.., 6. gather results and process results 7. Commit or rollback based on transaction execution. 8. Close the connection Spring DAO based persistence logic: 1. Get access to jdbc template class object through dependency injection process 2. perform persistence operations like insert, update, delete, read/select. 3. Gather results and process. If we use jdbc template class given by spring dao module, it will take care of the common activities of jdbc programming like establishing connection, closing connection, transaction management & other common operations. So programmer can concentrate only on application specific operations. Jdbc template class provides lots of methods to perform persistence operations on database s/w without using any kind of jdbc api. query(_), queryForXxx(_) of jdbc template class are given to execute sql select queries. update() of jdbc template class is given to execute non-select queries. batchUpdate() is used for batch processing. Limitations with jdbc: 1. All the steps are mandatory to follow. 2. ResultSet object is not serializable object so we cannot send it over network. 3. All jdbc exception are checked exceptions so programmer must catch and handle them. 4. Allows only positional parameters for queries (?). Features of spring DAO: 1. Allows to develop jdbc style persistence logic without using jdbc api. 2. The jdbc template class takes care of the common jdbc workflow or operations. So programmer can concentrate only on application specific persistence logic development. 3. Select query results can be stored directly in collection framework data structures which are serializable objects by default. 4. Spring DAO internally uses jdbc code. So it catches all jdbc checked exceptions thrown by jdbc code and rethrows as unchecked exceptions.

70 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

5. Simplifies the process of developing jdbc style persistence logic by providing abstraction layer on jdbc programming. 6. Spring DAO based persistence logic is not database independent because it internally uses jdbc code and database specific queries given by programmer. 7. To execute select queries that returns multiple records use queryForList(). 8. To execute select query that returns a single record use queryForMap(). 9. To execute select query that contains aggregate function results or any individual values use queryForLong(), queryForInt() etc.., 10.Allows both positional (?) and named (<:pname> parameters for queries. 11.To work with named parameters we must use NamedParameterJdbcTemplate class. 12.Single connection data source represents a connection pool that contains only one jdbc connection object and will not be closed automatically when spring container is stopped. 13.In order to close this single connection we must call close() method implicitly. This class is subclass of DriverManageDataSource and both these classes related connection pools are not meant for real time programming. Connection Pool: 1. Connection Pool is a pool of ready made specified number of database connection objects. 2. When ever client program needs a database connection they can request our pool and can get one connection object. 3. Client program can do all database operations and can release the connection object back to connection pool. 4. The same connection object can be reused any number of times till the connection pool is destroyed. 5. Connection objects will be in waiting state in connection pool for client request. 6. At a time only one client can use one connection object. 7. If all connection objects of connection pool are busy then client program should be waiting state till any client releases a connection object. 8. With connection pool we can increase performance of entire application. 9. In real time applications regularly we work with connection pool. 10. When huge amount of customers are trying to connect with database server in those cases better we use connection pooling concept. Connection pool can be created in 3 ways: 1. Dummy Connection pool 2. Third Party Connection pool 3. Web server or application server supplied connection pool

71 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Example: Integrating spring with Jdbc [Dummy Connection pool] //SelectInter.java public interface SelectInter { public String fetchEmpName(int eno); public long fetchEmpSalary(int eno); } //SelectImple.java import java.sql.*; import javax.sql.DataSource; public class SelectImple implements SelectInter { DataSource ds = null; public void setDs(DataSource ds) { this.ds = ds; } public String fetchEmpName(int eno) { try { //get access to jdbc connection object from jdbc connection pool through data source object "ds" Connection con = ds.getConnection(); //persistence logic Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select ename from emp where empno = "+eno); if(rs.next()) { return rs.getString(1); } else { System.out.println("No record found with employee number: "+eno); } rs.close(); st.close(); con.close(); } catch(SQLException e) { e.printStackTrace(); return "Record not found"; } catch(Exception e)

72 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748

Sathya Technologies {

Spring

Kanakadhar Surapaneni :)

e.printStackTrace(); return "Record not found"; }//catch return "Record not found"; }//fetch empName public long fetchEmpSalary(int eno) { try { //get access to jdbc connection object from jdbc connection pool through data source object "ds" Connection con = ds.getConnection(); //persistence logic Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select sal from emp where empno = "+eno); if(rs.next()) { return rs.getLong(1); } else { System.out.println("No record found with employee number: "+eno); } rs.close(); st.close(); con.close(); } catch(SQLException e) { e.printStackTrace(); return 0; } catch(Exception e) { e.printStackTrace(); return 0; }//catch return 0; }//fetch empsalary } Note: 1. Its same as regular Jdbc program. But here we are getting Connection object by using DataSource object. 2. DataSource is an interface belongs to javax.sql package. The same interface has many implementation classes. One of the class is DriverManagerDataSource. //spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"

73 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

"http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="dmds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> </bean> <bean id="sel" class="SelectImple"> <property name="ds"> <ref bean = "dmds"/> </property> </bean> </beans> Note: In the above xml file we have given service id in url. Q) How to find service id of oracle Ans: SQL> select * from global_name; GLOBAL_NAME -------------------------------------------------------------------------------SATYA.US.ORACLE.COM //SelectClient.java import org.springframework.core.io.FileSystemResource; import org.springframework.beans.factory.xml.XmlBeanFactory; public class SelectClient { public static void main(String args[]) { FileSystemResource res=new FileSystemResource("spring.cfg.xml"); XmlBeanFactory factory=new XmlBeanFactory(res); SelectImple s=(SelectImple)factory.getBean("sel"); System.out.println("Employee name is: "+s.fetchEmpName(7839)); System.out.println("Employee salary is: "+s.fetchEmpSalary(7839)); } }

74 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Example: Third Party Connection pool Apache Tomcat supplied jar file Note: Many third party connection pools are available. We'll see two among them. 1. Tomcat supplied connection pool [Need not to start tomcat server. Simply we need to set the class path for "naming-factory-dbcp.jar" file] 2. It is available in Tomcat 5.5\common\lib\naming-factory-dbcp.jar 3. Also set classpath to classes12.jar Note: Only change is in configurationm file. The rest of resources will be same. //spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="dbcpds" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" destroy-method = "close"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> <property name="initialSize"> <value>3</value> </property> </bean> <bean id="sel" class="SelectImple"> <property name="ds"> <ref bean = "dbcpds"/> </property> </bean> </beans>

75 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Example: Third Party Connection pool Hibernate supplied jar file 1. Tomcat supplied connection pool [Need not to start tomcat server. Simply we need to set the class path for "c3p0-0.9.1.jar" file] 2. It is available in hibernate-home\lib\c3p0-0.9.1.jar 3. Also set classpath to classes12.jar Note: Only change is in configurationm file. The rest of resources will be same. //spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="c3p0ds" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method = "close"> <property name="driverClass"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="jdbcUrl"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="user"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> <property name="initialPoolSize"> <value>3</value> </property> <property name="maxPoolSize"> <value>30</value> </property> <property name="acquireIncrement"> <value>5</value> </property> </bean> <bean id="sel" class="SelectImple">

76 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902

Sathya Technologies <property name="ds">

Spring

Kanakadhar Surapaneni :)

<ref bean = "c3p0ds"/> </property> </bean> </beans> Web or application server based connection pool: 1. The nick name or alias name given to the object that is registered with registry s/w is technically called as JNDI name. 2. Data source represents server managed connection pool. 3. To provide global visibility to this data source object from multiple client applications we need to register it with registry s/w having jndi name. 4. Client application always uses jdbc data source object to get access to connection object of connection pool. 5. Jdbc data source object is an object of a class which implements java.sql.DataSource interface. Steps: 1. Create Jdbc connection pool for certain database s/w. 2. Create jdbc data source and link it with jdbc connection pool. 3. register jdbc data source with registry s/w for global visibility 4. Client application performs jndi lookup operation on registry & gets jdbc data source object. 5. getConnection() method on data source object gets one jdbc connection object from jdbc connection pool. 6. Client application uses this jdbc connection object for persistence operations on database. 7. con.close() releases jdbc connection object back to the connection pool so that the same object can be used by other clients. Example: Application server supplied connection pool with Weblogic set the class path for: 1. "weblogic1.jar" file [C:\bea\weblogic81\server\lib\weblogic.jar] 2. classes12.jar Weblogic8.1 connection pooling: Step1: Create user in weblogic & start admin server Start menu programs bea weblogic platform8.1 configuration wizard next next give password and confirm password as same [remind this password.] next next specify configuration name [domain name] at right bottom of window create select start admin server done. Step2: open administrator console Start menu programs bea weblogic platform8.1 examples weblogic workshop server admin console give password here login.

77 2903 2904 2905 2906

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Step3: Create Connection pool Choose your domain name [in left pane of admin console window] services jdbc click on connection pools Configure a new JDBC Connection Pool choose database and its corresponding driver as shown below continue

2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933

Define connection properties: Name: give some name for connection pool Database name: give service id if it is oracle Host Name: ip address or server name where database server resides Port: port no. of database server Also provide database username & password and click on continue button click on button test driver connection. if it shows connection successful then click on Create & deploy. Step4: Create data source Choose your domain name [in left pane of admin console window] services jdbc click on Data sources click on Configure a new JDBC Data Source Name: Give some name for Data source JNDI name: Give some JNDI name. [remind this. We have to configure this in our program] Select check box of : Emulate Two-Phase Commit for non-XA Driver continue. choose our connection pool from combo box continue create. Note: Only change is in configurationm file. The rest of resources will be same. //spring.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="jofb" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>oraJNDI</value> </property> <property name="jndiEnvironment"> <props> <prop key = "java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>

78 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<prop key = "provider_url">t3://localhost:7001</prop> </props> </property> </bean> <bean id="sel" class="SelectImple"> <property name="ds"> <ref bean = "jofb"/> </property> </bean> </beans> Note: 1. As we have specified driver class, database url, user name & password in weblogic need not to specify once again in spring configuration file. 2. A connection pool is a factory that contains set of readily available jdbc connection objects before actually being used. 3. Jdbc DataSource object always represents one jdbc connection pool. 4. To access each conenction object of connection pool we need to use jdbc data source object. 5. org.springframework.jdbc.datasource.DriverManagerDataSource represents spring built in jdbc dummy connection pool by giving data source object. 6. This is called as dummy connection pool because it does not pools the connection objects. It creates connection object on demand. 7. DriverManagerDataSource implements javax.sql.DataSource interface. 8. This class uses given jdbc driver details and uses jdbc data source object which represents dummy connection pool. Note: Do not use DriverManagerDataSource in your real time projects. Example: Working with JdbcTemplate class [queryForXxx() methods] //SelectInter.java import java.util.List; import java.util.Map; public interface SelectInter { int getEmpCount(String desg); List getEmpDetails(String desg); Map getEmpDetails(int eno); boolean registerEmp(int no, String name, String desg, int sal); boolean modifyDesignation(int no, String newDesig); boolean fireEmp(int eno);

79 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//SelectImple.java import java.util.List; import java.util.Map; import org.springframework.jdbc.core.JdbcTemplate; public class SelectImple implements SelectInter{ JdbcTemplate jt; String qry; public void setJt(JdbcTemplate jt) { this.jt = jt; } public boolean fireEmp(int eno) { qry = "delete from emp where empno = ?"; int res = jt.update(qry, new Object[]{new Integer(eno)}); if(res == 0) return false; else return true; } public int getEmpCount(String desg) { qry = "select count(*) from emp where job = ?"; int count = jt.queryForInt(qry, new String[]{desg}); return count; } public Map getEmpDetails(int eno) { qry = "select * from emp where empno = ? "; Map m = jt.queryForMap(qry, new Object[]{new Integer(eno)}); return m; } public List getEmpDetails(String desg) { qry = "select * from emp where job = ?"; List l = jt.queryForList(qry, new Object[]{desg}); return l; } public boolean modifyDesignation(int no, String newDesig) {

80 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

qry = "update emp set job = ? where empno = ?"; int res = jt.update(qry, new Object[]{newDesig, new Integer(no)}); if(res == 0) return false; else return true; } public boolean registerEmp(int no, String name, String desg, int sal) { qry = "insert into emp (empno, ename, job, sal) values(?, ?, ?, ?)"; int res = jt.update(qry, new Object[]{new Integer(no), name, desg, new Integer(sal)}); if(res == 0) return false; else return true; } //applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <!-- note: add naming-factory-dbcp.jar file from tomcat-home\common\lib --> <bean id="dbcp" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"> <value>scott</value> </property>

81 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<property name="password"> <value>tiger</value> </property> <property name="initialSize"> <value>3</value> </property> </bean> <bean id="template" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean = "dbcp"/> </property> </bean> <bean id="sel" class="SelectImple"> <property name="jt"> <ref bean = "template"/> </property> </bean> </beans> //SelectClient.java import java.util.List; import java.util.Map; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SelectClient { public static void main(String args[])throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); SelectImple s=(SelectImple)ctx.getBean("sel"); System.out.println("Employee count with Clerk disgnation is: "+s.getEmpCount("CLERK")); Map m = s.getEmpDetails(7934); System.out.println("Details of empno: 7934 are: "+m.toString()); System.out.println("Clerk designation employees details are: "); List l = s.getEmpDetails("CLERK"); for(int i = 0; i < l.size(); i++)

82 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 } }

Sathya Technologies {

Spring

Kanakadhar Surapaneni :)

Map m1 = (Map) l.get(i); System.out.println(m1.toString()); } boolean bool = s.registerEmp(1, "Kanakadhar", "MANAGER", 50000); System.out.println("Employee registered "+bool); bool = s.modifyDesignation(1, "PRESIDENT"); System.out.println("Employee designation updated "+bool); Thread.sleep(10000); bool = s.fireEmp(1); System.out.println("Employee fired "+bool);

3089 3090

Note: The same DAO class can be shared by multiple client programs. But in our example we have seen only one client program which is calling all methods of DAO.

83 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Example: Named parameter without container import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.datasource.SingleConnectionDataSource; public class Client { public static void main(String[] args) { SingleConnectionDataSource ds = new SingleConnectionDataSource(); ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); ds.setUrl("jdbc:oracle:thin:@localhost:1521:sathya"); ds.setUsername("scott"); ds.setPassword("tiger"); NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate( String qry = "select count (*) from emp where job = :desig"; MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("desig", "CLERK"); int count = template.queryForInt(qry, params); System.out.println("No. of Clerks are: "+count); ds.destroy();

//Example: Named parameter with container // SelectInter.java public interface SelectInter { int getEmpCount(int eno1, int eno2); //SelectImple.java import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; //Add apache tomcat third party jar "naming-factory-dbcp.jar" file to build path //Add classes12.jar for build path public class SelectImple implements SelectInter{ NamedParameterJdbcTemplate nt; String qry = "select count(*) from emp where empno >= :e1 and empno <= :e2"; public void setNt(NamedParameterJdbcTemplate nt) { this.nt = nt;

84 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 }

Sathya Technologies }

Spring

Kanakadhar Surapaneni :)

public int getEmpCount(int eno1, int eno2) { MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("e1", new Integer(eno1)); params.addValue("e2", new Integer(eno2)); int count = nt.queryForInt(qry, params); return count; } // applicationContext.xml <!-- note: add naming-factory-dbcp.jar file from tomcat-home\common\lib --> <beans> <bean id="dbcp" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> <property name="initialSize"> <value>3</value> </property> </bean> <bean id="namedTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" <constructor-arg> <ref bean = "dbcp"/> </constructor-arg> </bean>

85 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 END; AS BEGIN }

Sathya Technologies <bean id="sel" class="SelectImple"> <property name="nt">

Spring

Kanakadhar Surapaneni :)

<ref bean = "namedTemplate"/> </property> </bean> </beans> //SelectClient.java import org.springframework.context.support.ClassPathXmlApplicationContext; public class SelectClient { public static void main(String args[]) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); SelectImple s=(SelectImple)ctx.getBean("sel"); System.out.println("Employees in between empid 7500 to 7800 count is: "+s.getEmpCount(7500, 7800)); } Example: To call oracle stored procedure Note: 1. Create this procedure through sql> prompt of oracle client. 2. Make sure that "emp" table is esisiting in oracle. Normally it is a default table in scott user. CREATE OR REPLACE PROCEDURE GET_EMP_DATA (NAME IN VARCHAR, NO OUT NUMBER, DESG OUT VARCHAR, SALARY OUT NUMBER)

SELECT EMPNO, JOB, SAL INTO NO, DESG, SALARY FROM EMP WHERE ENAME = NAME;

86 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Employee.java [POJO class] class Employee { private Integer no; private String name; private String designation; private Double salary; public void setNo(Integer no) { this.no = no; public void setName(String name) { this.name = name; public void setDesignation(String designation) { this.designation = designation; public void setSalary(Double salary) { this.salary = salary; public String toString() { return this.no + "\t" + this.name + "\t" + this.designation + "\t" + this.salary;

// SimpleJdbcCallTest.java /* steps: 1. create datasource 2. pass datasource to subclass of StoredProcedure which is a static innerclass 3. Register all in & out parameters 4. read data from Map object, set to bean class object & display */ import java.sql.Types; import java.util.HashMap;

87 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

import java.util.Map; import javax.sql.DataSource; import org.springframework.jdbc.core.SqlOutParameter; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.object.StoredProcedure; import org.springframework.jdbc.datasource.*; public class SimpleJdbcCallTest { public static void main(String args[]) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver"); dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:SATHYA"); dataSource.setUsername("scott"); dataSource.setPassword("tiger"); Employee emp = (Employee) getEmployeeDetailsWithStoredProcedure(dataSource,"ALLEN"); System.out.println("Allen Details : " + emp);

private static Object getEmployeeDetailsWithStoredProcedure (DataSource ds, String ename) { MyStoredProcedure sp = new MyStoredProcedure(ds); //call procedure Map results = sp.myexecute(ename); //set outparmeter values to emp object Employee emp = new Employee(); emp.setName(ename); emp.setNo((Integer)results.get("NO")); emp.setDesignation((String)results.get("DESG")); emp.setSalary((Double)results.get("SALARY")); return emp; }//method2 //MyStoredProcedure.java private static class MyStoredProcedure extends StoredProcedure { public MyStoredProcedure(DataSource ds) { super(ds, "GET_EMP_DATA");

88 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

this.setFunction(false); //false -> indicates its a stored procedure SqlParameter[] params = { new SqlParameter("NAME", Types.VARCHAR), new SqlOutParameter("NO", Types.INTEGER), new SqlOutParameter("DESG", Types.VARCHAR), new SqlOutParameter("SALARY", Types.DOUBLE) }; this.setParameters(params); compile(); }//constructor public Map myexecute(String name) { HashMap map = new HashMap(); map.put("NAME",name); return super.execute(map); }//inner class }//outerclass ORM Module: 1. Spring doesn't provide any of its own ORM tool. Simply it provides us a chance to integrate with any orm tool. 2. We can integrate spring with any ORM module in two ways: 1. Plain: In plain style almost complete code should be written by programmer. 2. Template class: Using template class we can foucs only on database operations instead of focusing on common code. Note: We will see how to integrate spring & hibernate which is a ORM tool. So before we see this lets see a pure example regarding hibernate. So we can feel comfortable ragrding integration of spring n hibernate. Example: Insertion of a record into employee table of oracle database using java hibernate application. Files to be created: 1. hibernate.cfg.xml [Hibernate configuration file] 2. Employee.java [persistent class/POJO] 3. Employee.hbm.xml [Hibernate Mapping file] 4. Client.java [Java application using hibernate API & setup to interact with Database software.]

89 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Step1: Create table in oracle database software as follows: create table employee ( eid number primary key, firstname varchar2(20), lastname varchar2(20), email varchar2(20) ); Note: Whether we configure primary key while creating table or not, but its compulsory to have primary key configuration in mapping file. Step2: Create hibernate configuration file as follows:[Note: For reference open file from Hibernatehome\etc\hibernate.cfg.xml Note: Here Hibernate-home indicates hibernate setup.[that is extracted folder of hibernate zip file which is a installation process of hibernate software.] hibernate.cfg.xml <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:sathya</property> <property name="hibernate.connection.username">scott</property> <property name="hibernate.connection.password">tiger</property> <property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="show_sql">true</property> <mapping resource="Employee.hbm.xml"/> </session-factory> </hibernate-configuration> Note: Hibernate property tag names are fixed but their values will be changed based on version & name of the Database software. Refer Hibernate-home\etc\hibernate.properties file to get each database specific Hibernate properties values. Step3: Develop POJO class/persistent class

90 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//Employee.java public class Employee implements java.io.Serializable { int no; String fname, lname, email; public void setNo(int no) { this.no = no; } public int getNo() { return no; } public void setFname(String fname) { this.fname = fname; } public String getFname() { return fname; } public void setLname(String lname) { this.lname = lname; } public String getLname(){ return lname; } public void setEmail(String email){ this.email = email; } public String getEmail(){ return email; } }//class

91 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Step 4: Develop Hibernate Mapping file (Employee.hbm.xml) Note: Take reference file from Hibernate-home\eg\*.hbm.xml Employee.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Employee" table="employee"> <id name="no" column = "eid"/> <!-- Singular primary key field --> <property name="fname" column="firstname"/> <property name="lname" column = "lastname"/> <prope rty name = "email" column = "email"/> </class> </hibernate-mapping> Note: To see these SQL queries as log messages use hibernate.show_sql property in hibernate configuration file as shown below. <property name = hibernate.show_sql>true</property> Step 5: Develop hibernate based java application with persistence logic operations. [Insertion of record] Client.java import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.Transaction; public class TestClient { public static void main(String[] args) throws Exception { //locate and read configuration file Configuration conf = new Configuration(); conf = conf.configure(); //if we name configuration file differently then we need to specify it as a argument //conf = conf.configure(oracle.cfg.xml); //creation of session factory object based on configuration file details SessionFactory factory = conf.buildSessionFactory();

92 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 } }

Sathya Technologies //get session object

Spring

Kanakadhar Surapaneni :)

Session ses = factory.openSession(); Transaction tx = ses.beginTransaction(); //object creation with data Employee e1 = new Employee(); //Transient state e1.setNo(1); e1.setFname("Vara"); e1.setLname("Prasad"); e1.setEmail("kanakavaraprasad@gmail.com"); //Note: Even after storing data, the object e1 is in transient state. //record insertion ses.save(e1); //now the object e1 is in persistent state. tx.commit(); ses.close(); //closes statement and connection objects //Note: Now the object e1 is in transient state. factory.close(); //destroys entire connection pool

Points to ponder: conf.configure() method takes hibernate.cfg.xml file as a default configuration file. If you change the configuration file name as any other name then we need to pass its name as a string argument to the method configure(). Non select operation must be executed as Transactional operations in hibernate based application. If not no error arises but the updation you have to database wont be affected. So mind it. After completion of task with database software close database connection without fail using ses.close(); If not no error will arise but object will be engaged as a busy connection till end of the particular client application. ses.save() method inserts record into the database table returns primary key value in the form of object and makes POJO class object to represent inserted record with synchronization between them. Every hibernate session object contains buffer. In order to flush this buffer use ses.flush() method. Hibernate software generates database specific sql queries internally for the methods we call from hibernate software to do persistent operations.

Step 6: Add the following jar files to class path to recognize hibernate API which is a third party API. They are as follows: 1.Main Jar file

93 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

1. hibernate3.jar [available in hibernate-home directory] 2.Dependent jar files of hibernate3.jar [available in hibernate-home\lib folder] 1. dom4j-version.jar 2. cglib-version.jar 3. commons-collections-version.jar 4. commons-logging-version.jar 5. jta.jar 6. asm.jar 7. antlr-version.jar classes12.jar [to support oracle type 4 driver for oracle9i] (available in oraclehome\ora92\jdbc\lib\) Note: To get information about required jar files refer _readme.txt file in hibernate-home\lib\ folder When java application uses third party API then the API related jar files must be added in the class path. It is always recommended to add jar files in my computer environmental variables class path.

Step 7: Compile *.java files using javac tool. Step 8: Execute client application [Client] Example: Plain integeration of spring & Hibernate // DemoInter.java import java.util.Iterator; public interface DemoInter { public Iterator getData() throws Exception; // DemoImpl.java import java.util.Iterator; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; public class DemoImpl implements DemoInter{ private SessionFactory factory = null; public void setFactory(SessionFactory factory) { System.out.println("Setter of spring class"); this.factory = factory;

94 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 } } } } ) } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public Iterator getData() throws Exception { System.out.println("In spring class getData()"); Session ses = factory.openSession(); Query query = ses.createQuery("from User"); Iterator i1 = query.iterate(); //ses.close(); return i1;

Table creation in oracle: create table users ( userid number(5) primary key, uname varchar2(20), role varchar2(20) //User.java public class User { private int uid; private String uname, role; public String getUname() { return uname; public void setUname(String uname) { this.uname = uname; public String getRole() { return role; public void setRole(String role) { this.role = role; public int getUid() { return uid;

95 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public void setUid(int uid) { this.uid = uid;

// User.hbm.xml <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="User" table="users" schema="SCOTT"> <id name="uid" column = "userid"/> <property name="uname"/> <property name="role"/> </class> </hibernate-mapping> // SpringHibernate.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id = "ds" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"> <value>scott</value> </property>

96 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 Note:

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<property name="password"> <value>tiger</value> </property> </bean> <bean id = "mySessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref = "ds"/> <property name="mappingResources"> <list> <value>User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> <prop key="show_sql">true</prop> </props> </property> </bean> <bean id = "d1" class = "DemoImpl"> <property name="factory" ref = "mySessionFactory" /> </bean> </beans> 1. We can configure both spring & hibernate properties inside spring configuration file as shown above. 2. In above xml file we have specified show_sql as true. But still it work incase of spring. If we use a separate xml file for hibernate configuration then it supports. We'll see its example later. //Client.java import java.util.Iterator; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Client { public static void main(String[] args) throws Exception { ApplicationContext ctx = new

97 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

ClassPathXmlApplicationContext("SpringHibernate.xml"); BeanFactory factory = (BeanFactory)ctx; DemoInter d = (DemoInter)factory.getBean("d1"); Iterator i1 = d.getData(); while(i1.hasNext()) { User u1 = (User)i1.next(); System.out.println(u1.getUid()+" "+u1.getUname()+" "+u1.getRole()); }

//Example: Integration of spring & Hibernate using HiberanteTemplate class Note: Interface, pojo class, table, mapping file & client program are same as above example. //DemoImpl.java import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; public class DemoImpl implements DemoInter{ private HibernateTemplate ht = null; public void setHt(HibernateTemplate ht) { System.out.println("setter of spring"); this.ht = ht; public Iterator getData() throws Exception { System.out.println("In spring class getData()"); List l = ht.find("from User"); Iterator i1 = l.iterator(); return i1;

98 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!--SpringHibernate.xml--> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd"> <bean id = "ds" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> </bean> <bean id = "mySessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref = "ds"/> <property name="mappingResources"> <list> <value>User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> <prop key="show_sql">true</prop> </props> </property>

99 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687

Sathya Technologies </bean>

Spring

Kanakadhar Surapaneni :)

<bean id = "template" class = "org.springframework.orm.hibernate3.HibernateTemplate"> <constructor-arg> <ref bean = "mySessionFactory"/> </constructor-arg> </bean> <bean id = "d1" class = "DemoImpl"> <property name="ht" ref = "template"/> </bean> </beans> Example: Named Query Note: Instead of writing query in client program we can write it inside mapping file. So the same query can be used by multiple files & maintenance will becomes easy. Note: Table, Pojo class, Sping n hibernate configuration file are same as above example <!--User.hbm.xml--> <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="User" table="users" schema="SCOTT"> <id name="uid" column = "userid"/> <property name="uname"/> <property name="role"/> </class> <query name = "users"> from User where uname like ? </query> </hibernate-mapping> //DemoClient.java import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; <!--hql query-->

100 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient { private HibernateTemplate ht = null; public void setHt(HibernateTemplate ht) { System.out.println("setter of spring"); this.ht = ht; public static void main(String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("SpringHibernate.xml"); BeanFactory factory = (BeanFactory)ctx; DemoClient d = (DemoClient)factory.getBean("d1"); List l =d.ht.findByNamedQuery("users", new Object[]{"%S%"}); Iterator it=l.iterator(); while(it.hasNext()) { User ob=(User)it.next(); System.out.print(ob.getUid()); System.out.println(" "+ob.getUname()+" "+ob.getRole()); System.out.println("--------------"); }

Example: Separate configuration files for Spring & Hibernate <!--spring.cfg.xml--> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd">

101 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 </beans>

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<bean id = "ds" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> </bean> <bean id = "mySessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref = "ds"/> <property name = "configLocation"> <value>hibernate.cfg.xml</value> </property> </bean> <bean id = "template" class = "org.springframework.orm.hibernate3.HibernateTemplate"> <constructor-arg> <ref bean = "mySessionFactory"/> </constructor-arg> </bean> <bean id = "d1" class = "DemoClient"> <property name="ht" ref = "template"/> </bean> <!--hibernate.cfg.xml--> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

102 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<hibernate-configuration> <session-factory> <property name = "hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="show_sql">true</property> <mapping resource="User.hbm.xml"/> </session-factory> </hibernate-configuration> Note: The rest of resources are same as earlier examples. Example: Updating multiple records using HibernateTempalte class //DemoClient.java import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoClient{ private HibernateTemplate ht = null; public void setHt(HibernateTemplate ht) { System.out.println("setter of spring"); this.ht = ht; public static void main(String[] args) throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("SpringHibernate.xml"); BeanFactory factory = (BeanFactory)ctx; DemoClient d = (DemoClient)factory.getBean("d1"); String qry = "update User set role = ? where role = ?"; int res = d.ht.bulkUpdate(qry, new Object[]{"PM", "SSE"}); System.out.println("No. of records updated are: "+res);

103 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 } } } } } )

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Note:The rest of resources are same as earlier example. Example: Retrieving all records of a table using HibernateTemplate class Table in oracle: create table event ( eid number(5) primary key, evname varchar2(25) //eventpojo.java public class eventpojo { Integer eventid; String eventname; public eventpojo(){ } public Integer getEventid() { return eventid; public void setEventid(Integer eventid) { this.eventid = eventid; public String getEventname() { return eventname; public void setEventname(String eventname) { this.eventname = eventname;

<!-- eventpojo.hbm.xml --> <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

104 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<hibernate-mapping> <class name="eventpojo" table="event"> <id name="eventid" column="eid"/> <property name="eventname" column="evname"/> </class> </hibernate-mapping> //eventdao.java import org.springframework.orm.hibernate3.*; import java.util.*; public class eventdao { HibernateTemplate ht; public void setHt(HibernateTemplate ht) { this.ht=ht; public void saveObject(Object o) { ht.save(o); public void selectAll() { List l =ht.loadAll(eventpojo.class); Iterator it=l.iterator(); while(it.hasNext()) { eventpojo ob=(eventpojo)it.next(); System.out.print(ob.getEventid()); System.out.println(" "+ob.getEventname()); System.out.println("--------------"); }

105 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- spring.cfg.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="id1" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> </bean> <bean id="id2" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="id1"/> </property> <property name="mappingResources"> <list> <value> eventpojo.hbm.xml </value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect </prop> <prop key="show_sql"> true </prop> </props> </property> </bean>

106

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 }

<bean id="id3" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="id2"/> </property> </bean> <bean id="id4" class="eventdao"> <property name="ht"> <ref bean="id3"/> </property> </bean> </beans> //client.java import org.springframework.core.io.*; import org.springframework.beans.factory.*; import org.springframework.beans.factory.xml.*; public class client { public static void main(String[] args) { BeanFactory factory=new XmlBeanFactory(new ClassPathResource("spring.cfg.xml")); eventdao ed =(eventdao)factory.getBean("id4"); eventpojo ep=new eventpojo(); ep.setEventid(new Integer(2)); ep.setEventname("WindowEvent"); ed.saveObject(ep); ed.selectAll(); System.out.println("completed..."); } JEE Module: Example: TimerTask [Job Scheduling] When ever we need to execute any task at particular time either for one time or for every particular period then we can use scheduling as follows: //task1.java [Core java program] import java.util.*;

107 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public class task1 extends TimerTask { public void run() { System.out.println("welcome to sathya ");

//scheduledemo.java import java.util.*; public class scheduledemo { public static void main(String args[]) { Timer t1=new Timer(); t1.schedule(new task1(),5000); //initial delay t1.schedule(new task1(),5000,3000); //initial delay, periodical delay } Example: Multiple Tasks Note: "task1" class is same as above. //task2 .java import java.util.*; import java.io.*; public class task2 extends TimerTask { public void run() try { FileWriter fp=new FileWriter("demofile.txt", true); fp.write(new Date().toString()+"\n"); fp.close(); System.out.println("data stored"); }catch(Exception e){} {

108 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 </bean> </beans> </bean> </bean>

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- Timer.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="job1" class="task1" /> <bean id="job2" class="task2" /> <bean id="schedule1" class="org.springframework.scheduling.timer.ScheduledTimerTask" > <property name="delay"> <value>5000</value></property> <property name="period"><value>2000</value></property> <property name="timerTask" > <ref bean="job1" /> </property> <bean id="schedule2" class="org.springframework.scheduling.timer.ScheduledTimerTask" > <property name="delay"> <value>5000</value></property> <property name="period"><value>3000</value></property> <property name="timerTask" > <ref bean="job2" /> </property> <bean id="stt" class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <ref bean="schedule1" /> <ref bean="schedule2" /> </list> </property>

//scheduledemo.java import org.springframework.context.*; import org.springframework.context.support.*; import java.io.*;

109 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public class scheduledemo { public static void main(String args[]) throws IOException { ApplicationContext ctx=new FileSystemXmlApplicationContext("Timer.xml");

Example: Scheduling using spring classes. //democlass1.java public class democlass1 { public void method1() { System.out.println("welcome to sathya");

//democlass2.java import java.io.*; public class democlass2 { public void method2() { try{ FileWriter fp=new FileWriter("demofile.txt",true); fp.write(new Date().toString()+"\n"); fp.close(); System.out.println("data stored"); }catch(Exception e){}

Note: Our classes are not extending any predefined class Injection Process: democlass1 -> MethodInvokingTimerTaskFactoryBean -> ScheduledTimerTask -> TimerFactoryBean

110 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 </bean>

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- Timer.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="c1" class="democlass1" /> <bean id="c2" class="democlass2" /> <bean id="job1" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"> <property name="targetObject"> <ref bean="c1" /> </property> <property name="targetMethod"> <value>method1</value> </property> </bean> <bean id="job2" class="org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean"> <property name="targetObject"> <ref bean="c2" /> </property> <property name="targetMethod"> <value>method2</value> </property> </bean> <bean id="schedule1" class="org.springframework.scheduling.timer.ScheduledTimerTask" > <property name="delay"> <value>5000</value></property> <property name="period"><value>2000</value></property> <property name="timerTask" > <ref bean="job1" /> </property> <bean id="schedule2" class="org.springframework.scheduling.timer.ScheduledTimerTask" > <property name="delay"> <value>5000</value></property> <property name="period"><value>3000</value></property>

111 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 </bean> </beans> </bean>

Sathya Technologies <property name="timerTask" > <ref bean="job2" /> </property>

Spring

Kanakadhar Surapaneni :)

<bean id="stt" class="org.springframework.scheduling.timer.TimerFactoryBean"> <property name="scheduledTimerTasks"> <list> <ref bean="schedule1" /> <ref bean="schedule2" /> </list> </property>

Note: Client program is same like earlier example. JNDI: [Java Naming Directory Interface] 1. When ever we need to give global visibility for any java object then we can use JNDI. So that any program can bidn the object with server from any where through out the world. The same object can be used by some other program through JNDI. 2. JNDI can act as a mediator between server program & client program to exchange objects. 3. To work with JNDI we need to start any application server like weblogic or Jboss. 4. We can do following JNDI operations 1. bind(id, obj): 1. We can bind any object with some identification name. 2. If the object is already binded immediately it throws BindException 2. rebind(id, obj) 1. Same as bind() method 2. But if the object is already exists it replace the exisiting object with new object. 3. unbind(id): Specific id related object will be immediately removed. 4. lookup(id): When ever we need to fetch the object through JNDI then we can use it. 5. list(): returns all the registered objects

112 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 }//class

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Example: Plain JNDI without using Spring Note: 1. start -> programs -> bea products -> example -> weblogic server -> start examples server 2. set the classpath for weblogic.jar //TestJndi.java import javax.naming.*; import java.util.*; public class TestJndi { public static void main(String[] args) throws Exception { //prepare Jndi properties Hashtable ht=new Hashtable(); ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); ht.put(Context.PROVIDER_URL,"t3://localhost:7001"); InitialContext ic=new InitialContext(ht); // ic represents connectivity with Naming/Directory registry S/w //bind operation ic.rebind("today",new Date()); ic.bind("banana",new String("yellow")); //listing System.out.println("---->Listing (after binding)"); NamingEnumeration e=ic.list(""); while(e.hasMore()) { NameClassPair np=(NameClassPair)e.next(); // each binding is accessed System.out.println(np.getName()+"-----> "+np.getClassName()); } }//main

113 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//TestJndi1.java import javax.naming.*; import java.util.*; public class TestJndi1 { public static void main(String[] args) throws Exception { //prepare Jndi properties Hashtable ht=new Hashtable(); ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); ht.put(Context.PROVIDER_URL,"t3://localhost:7001"); InitialContext ic=new InitialContext(ht); // ic represents connectivity with Naming/Directory registry S/w //listing System.out.println("Listing"); NamingEnumeration e=ic.list(""); while(e.hasMore()) { NameClassPair np=(NameClassPair)e.next(); System.out.println(np.getName()+" ---> "+np.getClassName()); } //lookup System.out.println("lookup"); Object obj = ic.lookup("today"); Date d1=(Date)obj; System.out.println("date is "+d1.toString()); obj = ic.lookup("banana"); String color=(String)obj; System.out.println("Banana color is "+color); //unbind operation ic.unbind("banana"); //listing System.out.println("\n\n\nListing---------"); e=ic.list("");

114 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194

Sathya Technologies while(e.hasMore()) {

Spring

Kanakadhar Surapaneni :)

NameClassPair np=(NameClassPair)e.next(); System.out.println(np.getName()+" ---> "+np.getClassName()); } }//main }//class //To execute this application with jboss add jbossall-client.jar in the classpath ht.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); ht.put(Context.PROVIDER_URL,"jnp://localhost:1099"); Note: The rest of steps are same as above program. Example: Spring JNDI <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="jt" class="org.springframework.jndi.JndiTemplate"> <constructor-arg> <props> <prop key="java.naming.factory.initial"> weblogic.jndi.WLInitialContextFactory</prop> <prop key="PROVIDER_URL">t3://localhost:7001</prop> </props> </constructor-arg> </bean> <bean id="test" class="JndiTemplateTest"> <property name="template"><ref bean="jt"/></property> </bean> </beans> //JndiTemplateTest.java import org.springframework.context.support.*; import org.springframework.jndi.*; import java.util.*;

115 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 } Note: } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public class JndiTemplateTest { static JndiTemplate template; public void setTemplate(JndiTemplate template) { this.template=template; public static void main(String[] args) throws Exception { FileSystemXmlApplicationContext ctx= new FileSystemXmlApplicationContext("DemoCfg.xml"); System.out.println("bind()............"); template.bind("today1",new Date()); template.bind("apple",new String("it is red")); System.out.println("lookup operation"); Date d1=(Date)template.lookup("today1"); System.out.println("(today1)lookup value is"+d1.toString()); template.unbind("today1"); template.rebind("apple",new StringBuffer("it is green")); System.out.println("lookup operation"); StringBuffer s1=(StringBuffer)template.lookup("apple"); System.out.println("(apple)lookup value is"+s1.toString());

1. start -> programs -> bea products -> example -> weblogic server -> start examples server 2. set the classpath for weblogic.jar Example: Plain RMI [Remote Method Invocation] 1. Its a distributed application 2. Server side implementation class will contain logics in the form of methods. 3. Server side business logic methods will be called by client program

116 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//ServerInter.java import java.rmi.*; public interface ServerInter extends Remote { public String wish(String uname) throws RemoteException; // ServerImpl.java import java.rmi.*; import java.rmi.server.*; public class ServerImpl extends UnicastRemoteObject implements ServerInter { public ServerImpl() throws RemoteException{} public String wish(String uname) throws RemoteException { return "Good Afternoon "+uname;

//Server.java import java.rmi.*; import java.net.*; public class Server { public static void main(String args[]) throws RemoteException,MalformedURLException { ServerInter i1 = new ServerImpl(); Naming.rebind("rmi://localhost:1099/first",i1); System.out.println("server started..");

117 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//Client.java import java.rmi.*; import java.net.*; public class Client { public static void main(String args[]) throws RemoteException,NotBoundException,MalformedURLException { ServerInter i1=(ServerInter)Naming.lookup("rmi://localhost:1099/first"); System.out.println(i1.wish("Sai"));

RmiServer -----------1) In server machine 1. ServerInter.class 2. ServerImpl.class 3. Server.class 2) In client Machine 1. ServerInter.class 2. Client.class 3. ServerImpl_stub.class [We'll get this through rmic (rmi compilation)] Compilation: javac *.java rmic ServerImpl start rmiregistry [automcatically it starts a rmi registry window. It will be a balck console window. Dont close this. Simply minimise & work. Same jndi operation can be done here. So all the registered objects will be stored in rmi registry] Execute Server program: RmiClient -----------( copy ServerImpl_stub.class & ServerInter.class) javac Client.java java Client java Server

118 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 } } { } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Example: Spring RMI Note: Server side programs & set up every thing is same. But client side programs will be changed as shown below. //ClientInter.java public interface ClientInter { public ServerInter getServerInter(); // ClientImpl.java public class ClientImpl implements ClientInter { private ServerInter si; public void setSi(ServerInter si) { this.si = si; public firstinter getServerInter() return si;

<!-- first.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="pfb" class="org.springframework.remoting.rmi.RmiProxyFactoryBean" > <property name="serviceUrl" > <value>rmi://localhost:1099/first</value> </property> <property name="serviceInterface"> <value>ServerInter</value> </property> </bean>

119 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 } } }

Sathya Technologies <bean id="c1" class="ClientImpl" > <property name="si"> <ref bean="pfb" /> </property> </bean>

Spring

Kanakadhar Surapaneni :)

</beans> //Client.java import org.springframework.beans.factory.*; import org.springframework.context.*; import org.springframework.context.support.*; import java.rmi.*; public class Client { public static void main(String args[]) throws RemoteException { ApplicationContext ctx=new FileSystemXmlApplicationContext("first.xml"); BeanFactory factory=(BeanFactory)ctx; ClientInter i1=(ClientInter)factory.getBean("c1"); ServerInter si=i1.getServerInter(); System.out.println(si.wish("Sai"));

Example: HttpInvoker Note: 1. Our business logic classes classes can be placed in classes folder of a web application. 2. Our business logic classes need not to extend any predefined class or need not to implement any predefined interface. They can be perfect POJO's. 3. Same like a common web application. But through concept of HttpInvoker any kind of java applicaiton like console program, desktop application etc.., can give reqest from any where through out the world and can get response. //httpinter.java public interface httpinter { public String getWeek(); public String getMonth();

120 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

// httpimpl.java import java.util.*; public class httpimpl implements httpinter { public String getWeek() { String weeks[]=new String[] {"","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}; Calendar c1=Calendar.getInstance(); int w=c1.get(Calendar.DAY_OF_WEEK); return "current week :"+weeks[w]; public String getMonth() { String months[]=new String[] {"January","February","March","April","May","June","July","August","September","October","No vember","December"}; Calendar c1=Calendar.getInstance(); int m=c1.get(Calendar.MONTH); return "current month :"+months[m];

<!-- web.xml --> <web-app> <servlet> <servlet-name>remoting</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>remoting</servlet-name> <url-pattern>/http/*</url-pattern> </servlet-mapping> </web-app>

121 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 } } } } </bean> </beans>

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- remoting-servlet.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="h1" class="httpimpl" /> <bean name="/DemoService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter" > <property name="service"> <ref bean="h1" /> </property> <property name="serviceInterface" > <value>httpinter</value> </property>

//Client program Setup //clientinter.java public interface clientinter { public httpinter getInter(); //clientimpl .java public class clientimpl implements clientinter { private httpinter httpin; public void setHttpin(httpinter f1) { httpin=f1; public httpinter getInter() { return httpin;

122 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 } } </bean>

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- Demo.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="pfb" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"> <property name="serviceUrl"> <value>http://localhost:2010/httpserver/http/DemoService</value> </property> <property name="serviceInterface" > <value>httpinter</value> </property> <bean id="c1" class="clientimpl" > <property name="httpin"> <ref bean="pfb"/> </property> </bean> </beans> //DemoClient.java import org.springframework.beans.factory.*; import org.springframework.context.*; import org.springframework.context.support.*; public class DemoClient{ public static void main(String args[]) { ApplicationContext ctx=new FileSystemXmlApplicationContext("Demo.xml"); BeanFactory factory=(BeanFactory)ctx; clientinter c1=(clientinter)factory.getBean("c1"); httpinter h1=c1.getInter(); System.out.println(h1.getWeek()); System.out.println(h1.getMonth());

123 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 } Note:

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

1. Deploy server side ssetup in the form of a web application inside any web server like tomcat or application server like weblogic & start the server & execute the client program. 2. Do not forget to place main jar file & dependency jar file inside "lib" folder of a web application. Example: Working with Spring James Mail Server Note: 1. The mails what we send & recieve will not be stored in database server like oracle. They will be stored inside mail server. 2. We can have commerical servers & also free servers 3. James mail server is free server. But we can send mails only in same network. We cannot send mails to gmail or yahoomail etc.., 4. Microsoft exchange server is commercial server Working with mail server: 1. copy james server in C:\james-2.2.0. [in any root directory] 2.start james server by clicking on C:\james-2.2.0\bin\run.bat 3. start -> run -> telnet -> open localhost 4555 login id: root password: root type: help -> it gives u a list of commands with explanation. Note: While you are typing username or password if any mistake ignore it & retype again. It will also recognise back space or space as a part of password. So be careful while typing. //demointer.java public interface demointer { public void demo(); // demoimpl.java import org.springframework.mail.*; import org.springframework.mail.javamail.*; public class demoimpl implements demointer { private SimpleMailMessage message; private JavaMailSenderImpl sender;

124 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public void setMessage(SimpleMailMessage msg) { message=msg; public void setSender(JavaMailSenderImpl sen) { sender=sen; public void demo() { message.setText("this is first spring mail demo.."); sender.send(message);

<!-- mail.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="msg" class="org.springframework.mail.SimpleMailMessage" > <property name="to"><value>sravanthi</value></property> <property name="from"><value>anil</value></property> <property name="subject"><value>spring mail1</value></property> </bean> <bean id="s1" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <!-<property name="host"><value>m8.hamarashehar.com</value></property> --> <property name="host"><value>localhost</value></property> </bean> <bean id="d1" class="demoimpl" > <property name="message"> <ref bean="msg" /> </property>

125 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 } }

Sathya Technologies <property name="sender"> <ref bean="s1" /> </property> </bean>

Spring

Kanakadhar Surapaneni :)

</beans> //demoapp.java import org.springframework.context.*; import org.springframework.context.support.*; import org.springframework.beans.factory.*; public class demoapp { public static void main(String args[]) { ApplicationContext ctx=new FileSystemXmlApplicationContext("mail.xml"); BeanFactory factory=(BeanFactory)ctx; demointer d1=(demointer)factory.getBean("d1"); d1.demo(); System.out.println("mail sent..");

//Read mail program //ReceiveMail.java // Java Application to receive an E-mail using JAVA Mail API. import javax.mail.*; import javax.mail.internet.*; import java.util.*; public class ReceiveMail { public static void main(String []args) throws Exception { Properties p=new Properties(); p.put("mail.transport.protocol","pop"); p.put("mail.pop.host","localhost"); p.put("mail.pop.port","110"); Session session=Session.getInstance(p);

126 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Store store = session.getStore("pop3"); store.connect("localhost","user_name","pass_word"); Folder myinbox=store.getFolder("INBOX"); myinbox.open(Folder.READ_ONLY); System.out.println("No.of messages in the inbox:"+myinbox.getMessageCount()); Message message=myinbox.getMessage(1); message.writeTo(System.out); myinbox.close(false); store.close();

//Example: Spring Mail through gmail composing mails to any gmail id or yahoo mail id //OrderManager.java public interface OrderManager { void placeOrder(); //JavaMailOrderManager.java import javax.mail.Message; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; public class JavaMailOrderManager implements OrderManager { private JavaMailSender mailSender; public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; public void placeOrder() { try{ MimeMessage msg = mailSender.createMimeMessage(); msg.setSubject("Thank you..... :) "); msg.setContent("Dear Customer thank you for placing order. ","text/plain"); msg.setRecipient(Message.RecipientType.TO, new InternetAddress("s.varaprasad@yahoo.co.in")); this.mailSender.send(msg);

127 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 } }

Sathya Technologies } catch(Exception ex) { ex.printStackTrace(); }

Spring

Kanakadhar Surapaneni :)

<!-- mailsender.xml --> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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-2.5.xsd"> <bean id="ms" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.gmail.com"/> <property name="username" value="kanakavaraprasad@gmail.com"/> <!--Mails will be sent with same id--> <property name="password" value="Secret_Pls"/> <!-- Here we need to give original password of gmail--> <property name="javaMailProperties"> <props> <prop key="mail.transport.protocol">smtp</prop> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.port">465</prop> <prop key="mail.smtp.socketFactory.port">465</prop> <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> <prop key="mail.smtp.socketFactory.fallback">false</prop> <prop key="mail.smtp.quitwait">false</prop> <prop key="mail.smtp.starttls.enable">true</prop> </props> </property> </bean> <bean id="orderManager" class="JavaMailOrderManager"> <property name="mailSender" ref="ms"/> </bean> </beans>

128 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//client.java import org.springframework.core.io.*; import org.springframework.beans.factory.*; import org.springframework.beans.factory.xml.*; class client { public static void main(String[] args) { BeanFactory factory=new XmlBeanFactory(new FileSystemResource("mailsender.xml")); OrderManager om =(OrderManager)factory.getBean("orderManager"); om.placeOrder();

Note: Set the classpath for following jar files 1. mail.jar 2. activation.jar Note: When its needed to send any attachments add the following code: MimeMessage msg = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, true); FileSystemResource img = new FileSystemResource(new File("alice.gif")); helper.addAttachment("alice", img); sender.send(msg); Note: In the above code "sender" is reference of "JavaMailSender". If wee need to foramt data through html, then we can do it as follows: helper.setText("<html><head></head><body text=green><h1>Hello World!" + "</h1></body></html>", true); AOP Module[Aspect Oriented Programming]: Aspect: An Aspect is a functionality or a feature that cross-cuts [commonly shared] over objects. Eg: example, Logging and Transaction Management are the aspects. public void businessOperation(BusinessData data){ // Logging logger.info("Business Method Called"); // Transaction Management Begin

129 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

transaction.begin(); // Do the original business operation here transaction.end(); Join Points defines the various Execution Points where an Aspect can be applied. For example, consider the following piece of code, public void someBusinessOperation(BusinessData data){ //Method Start -> Possible aspect code here like logging. try{ // Original Business Logic here. }catch(Exception exception){ // Exception -> Aspect code here when some exception is raised. }finally{ // Finally -> Even possible to have aspect code at this point too.

// Method End -> Aspect code here in the end of a method. It is not necessary that an Aspect should be applied to all the possible Join Points. Pointcut: on which Join Points the Aspects will be applied is called as pointcut. Advice is the code that implements the Aspect Other Aspect Oriented Programming Languages also provide support for Field Aspect, i.e. intercepting a field before its value gets affected. But Spring provides support only Method Aspect. The following are the different types of aspects available in Spring. Before Advice : Executes before business logic method After Advice : Executes after business logic method Throws Advice : Executes when exception is thrown in a busines logic class Around Advice: Executes before & after business logic method.

Around Advice: When ever we need to perform any pre processing logic or post processing logic for our busines logic methods then we can use it by implementing an interace named as MethodInterceptor.

130 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//Example: AroundAdvice //IBusinessLogic.java public interface IBusinessLogic { public void method1(); public void method2(); // BusinessLogic.java public class BusinessLogic implements IBusinessLogic { public void method1() { System.out.println("execution of method1"); public void method2() { System.out.println("execution of method2");

// AroundAdvice.java import org.aopalliance.intercept.MethodInvocation; import org.aopalliance.intercept.MethodInterceptor; public class AroundAdvice implements MethodInterceptor { public Object invoke(MethodInvocation i1) throws Throwable { System.out.println("Hi....."); i1.proceed(); System.out.println("Goodbye! "); return null;

<!-- springconfig.xml --> <beans>

131 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<bean id="targetobj" class="BusinessLogic"/> <bean id="adv" class="AroundAdvice"/> <bean id="advr" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="adv"/> </property> <property name="pattern"> <value>.*</value> </property> </bean> <bean id="proxyobj" class= "org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>IBusinessLogic</value> </property> <property name="target"> <ref local="targetobj"/> </property> <property name="interceptorNames"> <list> <value>advr</value> </list> </property> </bean> </beans> //MainApplication.java import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class MainApplication {

132 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public static void main(String [] args) { ApplicationContext ctx= new FileSystemXmlApplicationContext("springconfig.xml"); IBusinessLogic testObject=(IBusinessLogic) ctx.getBean("proxyobj"); testObject.method1(); testObject.method2();

//Exmple: Buisness logic method with return value //IBusinessLogic.java public interface IBusinessLogic { public int method1(); // BusinessLogic.java public class BusinessLogic implements IBusinessLogic { public int method1() { System.out.println("execution of method1"); return 1000;

// AroundAdvice.java import org.aopalliance.intercept.MethodInvocation; import org.aopalliance.intercept.MethodInterceptor; public class AroundAdvice implements MethodInterceptor { public Object invoke(MethodInvocation i1) throws Throwable { System.out.println("good mng everybody.."); int n=((Integer)i1.proceed()).intValue(); System.out.println("Goodbye! "); if(n <=100)

133 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

return new Integer(0); else return new Integer(n); //return new Integer(2000);

//Note: What ever the value returned by invoke() method will be returned to client proram. So we can use it when we need to add some value added tax or to give some discount etc.., <!-- springconfig.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="beanTarget" class="BusinessLogic"/> <bean id="ad" class="AroundAdvice"/> <bean id="advisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="ad"/> </property> <property name="pattern"> <value>.*</value> </property> </bean> <bean id="proxyobj" class= "org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>IBusinessLogic</value> </property> <property name="target"> <ref local="beanTarget"/> </property> <property name="interceptorNames"> <list> <value>advisor</value>

134 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 } } } } }

Sathya Technologies </list> </property>

Spring

Kanakadhar Surapaneni :)

</bean> </beans> //MainApplication.java import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class MainApplication { public static void main(String [] args) { ApplicationContext ctx = new FileSystemXmlApplicationContext("springconfig.xml"); IBusinessLogic testObject = (IBusinessLogic) ctx.getBean("proxyobj"); int res=testObject.method1(); System.out.println("test result :"+res);

//Example: To do arguments validation before calling business logic method //IBusinessLogic.java public interface IBusinessLogic { public void method1(int id,String name); //BusinessLogic.java public class BusinessLogic implements IBusinessLogic{ public void method1(int id,String name) { System.out.println(""); System.out.println("execution of method1"); System.out.println(" id :"+id); System.out.println("name :"+name); System.out.println("");

135 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

// AroundAdvice.java import org.aopalliance.intercept.MethodInvocation; import org.aopalliance.intercept.MethodInterceptor; public class AroundAdvice implements MethodInterceptor { public Object invoke(MethodInvocation i1) throws Throwable { System.out.println("good mng. everybody.."); int x = ((Integer)i1.getArguments()[0]).intValue(); String y=(String)i1.getArguments()[1]; if( x <= 0 ) i1.getArguments()[0] = new Integer(101); if( y.length() <= 3) i1.getArguments()[1]="sathya tech"; i1.proceed(); System.out.println("Goodbye! "); return null;

<!-- springconfig.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="beanTarget" class="BusinessLogic"/> <bean id="ad" class="AroundAdvice"/> <bean id="advisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="ad"/> </property> <property name="pattern"> <value>.*</value> </property> </bean>

136 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<bean id="proxyobj" class= "org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>IBusinessLogic</value> </property> <property name="target"> <ref local="beanTarget"/> </property> <property name="interceptorNames"> <list> <value>advisor</value> </list> </property> </bean> </beans> //MainApplication.java import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class MainApplication { public static void main(String [] args) { ApplicationContext ctx = new FileSystemXmlApplicationContext("springconfig.xml"); IBusinessLogic testObject = (IBusinessLogic) ctx.getBean("proxyobj"); testObject.method1(22,"Sai Charan"); testObject.method1(-22,"Kanakadhar"); testObject.method1(-22,"SK");

//Example: To work with before & anround advice //IBusinessLogic.java public interface IBusinessLogic { public void method1();

137 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//BusinessLogic.java public class BusinessLogic implements IBusinessLogic { public void method1() { System.out.println(""); System.out.println("execution of method1"); System.out.println("");

// BeforeAdvice1.java import org.springframework.aop.*; import java.lang.reflect.*; public class BeforeAdvice1 implements MethodBeforeAdvice { public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("before advice");

// AroundAdvice2.java import org.aopalliance.intercept.MethodInvocation; import org.aopalliance.intercept.MethodInterceptor; public class AroundAdvice2 implements MethodInterceptor { public Object invoke(MethodInvocation i1) throws Throwable { System.out.println(" AroundAdvice : good mng everybody.."); i1.proceed(); System.out.println("AroundAdvice : Goodbye! "); return null;

138 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- springconfig.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="adv1" class="BeforeAdvice1"/> <bean id="adv2" class="AroundAdvice2"/> <bean id="targetobj" class="BusinessLogic"/> <bean id="advr1" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor"> <property name="advice"> <ref local="adv1"/> </property> <property name="mappedName"> <value>method1</value> </property> </bean> <bean id="advr2" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="adv2"/> </property> <property name="pattern"> <value>.*</value> </property> </bean> <bean id="proxyobj" class= "org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>IBusinessLogic</value> </property> <property name="target"> <ref local="targetobj"/> </property> <property name="interceptorNames"> <list> <value>advr2</value>

139 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 } } }

Sathya Technologies <value>advr1</value> </list> </property>

Spring

Kanakadhar Surapaneni :)

</bean> </beans> //MainApplication.java import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class MainApplication { public static void main(String [] args) { ApplicationContext ctx = new FileSystemXmlApplicationContext("springconfig.xml"); IBusinessLogic testObject = (IBusinessLogic) ctx.getBean("proxyobj"); testObject.method1();

Example: Working with all 4 advices [Before, After Around & Throws] Note: Here we will work with log4j [logging 4 java] Log4j: is a logging framework which is used to identify the control flow through log files. We can know where the problem is arised. Normally we can display messages on server console using s.o.p() statements. But those statements will be skipped soon & we cannot capture them. We can capture complete logs inforamtion through this log4j framework & we can store in the form of files. So we ever we need to we can open log files & can refer. Note: To work with this we need to set the classpath for log4j.jar // Adder.java package aop; public interface Adder { public int add(int a,int b); //AdderImpl .java package aop; public class AdderImpl implements Adder { public int add(int a, int b){ return a+b;

140 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//LogBeforeCallAdvice.java package aop; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; import org.apache.log4j.*; public class LogBeforeCallAdvice implements MethodBeforeAdvice{ Logger logger = Logger.getLogger(LogBeforeCallAdvice.class); public { SimpleLayout layout = new SimpleLayout(); FileAppender appender = null; try { appender = new FileAppender(layout,"output1.txt",true); } catch(Exception e) {} logger.addAppender(appender); logger.setLevel((Level) Level.DEBUG); public void before(Method method, Object[] args, Object target)throws Throwable { logger.info("Before Calling the Method at: "+new java.util.Date()); LogBeforeCallAdvice()

// LogAfterReturningAdvice.java package aop; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; import org.apache.log4j.*; public class LogAfterReturningAdvice implements AfterReturningAdvice{ Logger logger = Logger.getLogger(LogAfterReturningAdvice.class); public LogAfterReturningAdvice() { SimpleLayout layout = new SimpleLayout();

141 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

FileAppender appender = null; try { appender = new FileAppender(layout,"output1.txt",true); } catch(Exception e) {} logger.addAppender(appender); logger.setLevel((Level) Level.DEBUG); public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { logger.info("After Normal Return from Method at " +new java.util.Date()); } // LogAroundAdvice.java package aop; import org.aopalliance.intercept.*; public class LogAroundAdvice implements MethodInterceptor{ public Object invoke(MethodInvocation i1) throws Throwable { Object arguments[] = i1.getArguments(); int number1 = ((Integer)arguments[0]).intValue(); int number2 = ((Integer)arguments[1]).intValue(); if (number1 == 0 && number2 == 0){ throw new Exception("Dont know how to add 0 and 0!!!"); return i1.proceed();

// LogAfterThrowsAdvice.java package aop; import java.lang.reflect.Method; import org.springframework.aop.ThrowsAdvice; public class LogAfterThrowsAdvice implements ThrowsAdvice{

142 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public void afterThrowing(Method method, Object[] args, Object target, Exception exception){ System.out.println("Exception is thrown on method "+method.getName()); System.out.println("Exception that is raised is " +exception.toString()); } <!-- aop-test.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- Advices --> <bean id = "beforeCall" class = "aop.LogBeforeCallAdvice" /> <bean id = "afterCall" class = "aop.LogAfterReturningAdvice" /> <bean id = "throwCall" class = "aop.LogAfterThrowsAdvice" /> <bean id = "aroundCall" class = "aop.LogAroundAdvice" /> <!-- Implementation Class --> <bean id = "adderImpl" class = "aop.AdderImpl" /> <!-- Proxy Implementation Class --> <bean id="proxy" class= "org.springframework.aop.framework.ProxyFactoryBean"> <property name = "proxyInterfaces"> <value>aop.Adder</value> </property> <property name = "interceptorNames"> <list> <value>beforeCall</value> <value>afterCall</value> <value>throwCall</value> <value>aroundCall</value> </list> </property> <property name = "target"> <ref bean = "adderImpl"/> </property>

143 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 } } //

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

</bean> </beans> //AopTestClient .java package aop; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.*; public class AopTestClient { public static void main(String args[]){ Resource resource = new FileSystemResource("aop-test.xml"); BeanFactory factory = new XmlBeanFactory(resource); Adder adder = (Adder)factory.getBean("proxy"); int result = adder.add(0, 0); int result = adder.add(10, 20); System.out.println("Result = " + result);

//Example: Integration spring servlet & jdbc Note:jar files required in WEB-INF\lib folder & classpath are spring.jar, commons-logging.jar, classes12.jar <!-- index.html --> <frameset rows="30%,*" border = "0"> <frame src="Search.jsp"> <frame name="resultframe"> </frameset> <!-- Search.jsp --> <body bgcolor="pink" > <form action="controller" target="resultframe"> <b>Select job</b> <select name="job"> <option>CLERK</option> <option>ANALYST</option> <option>SALESMAN</option> <option>MANAGER</option> </select>

144 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<input type="submit" value="search"> </form> </body> <!-- Result.jsp --> <%@page import="java.util.*, p1.EmpBean"%> <table> <% ArrayList list=(ArrayList)request.getAttribute("result"); if(list!=null) { %> <%System.out.println("No. of records are : "+list.size()); %> <tr> <th>ID</th> <th>Name</th> <th>Desg</th> <th>Salary</th> </tr> <%for(int i=0;i<list.size();++i) { EmpBean eb=(EmpBean)list.get(i); %> <tr> <td><%=eb.getId()%></td> <td><%=eb.getName()%></td> <td><%=eb.getDesg()%></td> <td><%=eb.getBsal()%></td> </tr> <% } %> </table> <% } %> <!-- web.xml --> <?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>MainServlet</servlet-name>

145 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 } } } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<servlet-class>MainServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MainServlet</servlet-name> <url-pattern>/controller</url-pattern> </servlet-mapping> </web-app> //EmpBean.java package p1; public class EmpBean { int id; String name,desg; float bsal; public EmpBean() { System.out.println("EmpBean Constructor"); public float getBsal() { return bsal; public void setBsal(float bsal) { this.bsal = bsal; public String getDesg() { return desg; public void setDesg(String desg) { this.desg = desg; public int getId() { return id; public void setId(int id) { this.id = id;

146 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 } } } } }

Sathya Technologies public String getName() { return name; public void setName(String name) { this.name = name;

Spring

Kanakadhar Surapaneni :)

//Model .java import java.util.*; public interface Model { public ArrayList search(String desg); // ModelBean.java import java.util.*; import javax.sql.*; import java.sql.*; import p1.EmpBean; public class ModelBean implements Model{ public DataSource ds = null; public void setDs(DataSource ds) { this.ds = ds; public ArrayList search(String desg) { System.out.println("search() of ModelBean class"); ArrayList al=new ArrayList(); try { Connection con=ds.getConnection(); String qry = "select empno, ename, job, sal from emp where job=?"; PreparedStatement ps=con.prepareStatement(qry); ps.setString(1, desg); ResultSet rs=ps.executeQuery(); while(rs.next()) { EmpBean eb=new EmpBean();

147 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 </bean> } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

eb.setId(rs.getInt(1)); eb.setName(rs.getString(2)); eb.setDesg(rs.getString(3)); eb.setBsal(rs.getFloat(4)); al.add(eb); } } catch (SQLException e) { e.printStackTrace(); } return al;

<!-- modelconfig.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"><value>scott</value></property> <property name="password"><value>tiger</value></property> <bean id="mdb" class="ModelBean" autowire="byName"/> </beans> // MainServlet.java import java.io.IOException; import java.util.ArrayList; import javax.servlet.*; import javax.servlet.http.*; import org.springframework.beans.factory.xml.*;

148 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

import org.springframework.core.io.*; public class MainServlet extends HttpServlet { Model mod1=null; public void init() { System.out.println("Init Method"); ClassPathResource res=new ClassPathResource("modelconfig.xml"); XmlBeanFactory factory=new XmlBeanFactory(res); mod1=(Model)factory.getBean("mdb"); }//init public void destroy() { System.out.println("destroy()"); mod1=null; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet() of MainServlet"); try { String job=request.getParameter("job").trim(); ArrayList al=mod1.search(job); request.setAttribute("result",al); RequestDispatcher rd=request.getRequestDispatcher("Result.jsp"); if(rd!=null) rd.forward(request,response); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doPost() of MainServlet"); try { doGet(request,response);

149 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

} catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }//doPost }//MainServlet //Example: Spring Hibernate -Servlet <!-- web.xml --> <web-app> <servlet> <servlet-name>select</servlet-name> <servlet-class>selectservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>select</servlet-name> <url-pattern>/selectaction</url-pattern> </servlet-mapping> </web-app> //demointer.java import org.hibernate.*; public interface demointer { public SessionFactory getFactory(); // demoimpl.java import org.hibernate.*; public class demoimpl implements demointer { private SessionFactory sesfact; public void setSesfact(SessionFactory f1) { sesfact=f1;

150 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 } } ); } }

Sathya Technologies public SessionFactory getFactory() { return sesfact;

Spring

Kanakadhar Surapaneni :)

Note: Create following table in oracle & insert some reocrds So you can see stored records as a report create table users ( userid number(5) primary key, uname varchar2(20), role varchar2(20) //User.java public class User { private int uid; private String uname,role; public void setUid(int n) { uid=n; public int getUid(){ return uid; } public void setUname(String s){ uname=s; } public String getUname(){ return uname; } public void setRole(String r){ role=r; } public String getRole(){ return role; } <!-- User.hbm.xml --> <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping>

151 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455

Sathya Technologies <class name="User" table="users" >

Spring

Kanakadhar Surapaneni :)

<id name="uid" column="userid" /> <property name="uname" /> <property name="role" /> </class> </hibernate-mapping> <!-- ApplicationContext.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property> <property name="username"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="mappingResources"> <list> <value>User.hbm.xml</value> </list> </property>

152 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> </props> </property> </bean> <bean id="d1" class="demoimpl"> <property name="sesfact"> <ref local="mySessionFactory"/> </property> </bean> </beans> //selectservlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import org.hibernate.*; import java.util.*; import org.springframework.beans.factory.*; import org.springframework.context.*; import org.springframework.context.support.*; public class selectservlet extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { PrintWriter out=response.getWriter(); try{ ApplicationContext ctx=new ClassPathXmlApplicationContext("ApplicationContext.xml"); BeanFactory factory=(BeanFactory)ctx; demointer d1=(demointer)factory.getBean("d1"); SessionFactory sf=d1.getFactory(); Session ses=sf.openSession(); Query query=ses.createQuery("from User");

153 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 } } } { +"</tr>"); }

Sathya Technologies Iterator i1=query.iterate();

Spring

Kanakadhar Surapaneni :)

out.println("<body bgcolor=#ffffcc text=red>"); out.println("<h1><center>all users</h1><hr><br><h3>"); out.println("<table width=80% border=2>"); while(i1.hasNext()) { User u1=(User)i1.next(); out.println("<tr><td>"+u1.getUid()+" <td>"+u1.getUname()+" <td>"+u1.getRole()

out.println("</table>"); ses.close(); }catch(HibernateException e) out.println(e); e.printStackTrace();

Note: Set the classpath for: 1. 8 hibernate jars [1 main har + 7 dependncy jars] 2. 2 spring jars [1 main + 1 dependency jar] 3. oracle database specific jar Note: After deplying & starting web or application server give url as follows in browser: http://localhost:2010/SpringHibernateServlet/selectaction Spring MVC: Example: Spring MVC example with SimpleFormController class <!-- index.jsp --> <jsp:forward page="/newpro.htm" /> <!-- web.xml --> <web-app> <servlet> <servlet-name>productaction</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

154 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>productaction</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <taglib> <taglib-uri>spring-tld</taglib-uri> <taglib-location>/WEB-INF/spring.tld</taglib-location> </taglib> </web-app> Note: we need to name spring configuration file name as follows: <front controller class servlet name>-servlet.xml Eg: In above example our front controller class "DispatcherServlet" is named as " productaction" so we have named the spring configuration file as "productaction-servlet.xml". <!-- productaction-servlet.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="simpleUrlMappings" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property name="mappings"> <props> <prop key="/newpro.htm">newproController</prop> </props> </property> </bean> <bean id="newproController" class="NewProductController" > <property name="sessionForm" > <value>true</value></property> <property name="commandName" > <value>product</value></property> <property name="commandClass" > <value>Product</value></property> <property name="formView" > <value>newproduct</value></property> <property name="successView" > <value>showproduct</value></property> </bean>

155 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<bean id="viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property> <property name ="prefix"><value>/</value></property> <property name ="suffix"><value>.jsp</value></property> </bean> </beans> <!-- newproduct.jsp --> <%@ page language="java" %> <%@ taglib prefix="spring" uri="spring-tld" %> <html> <body bgcolor=#ffffcc text=green> <h1><center>new product information</h1><hr><br><h3> <form method="post" > enter product id : <spring.bind path="product.pid" > <input type=text name=pid /> </spring.bind> <br><br> enter product name : <spring.bind path="product.pname" > <input type=text name=pname /> </spring.bind> <br><br> enter product price : <spring.bind path="product.price" > <input type=text name=price /> </spring.bind> <br><br> <input type=submit value=send /> </form> </body> </html>

156 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

//Product.java public class Product { private int pid; private String pname; private double price; public void setPid(int n){ pid=n; } public int getPid(){ return pid; } public void setPname(String s){ pname=s; } public String getPname(){ return pname; } public void setPrice(double p){ price=p; } public double getPrice(){ return price; } //NewProductController.java import org.springframework.web.servlet.mvc.*; import org.springframework.web.servlet.*; import org.springframework.validation.*; import javax.servlet.http.*; public class NewProductController extends SimpleFormController { public ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException e) throws Exception { Product p=(Product)command; String str="Product id :"+p.getPid()+" <br> " +"product name :"+p.getPname()+"<br> " +"Price :"+p.getPrice(); System.out.println(str); request.setAttribute("productinfo",str); return new ModelAndView(getSuccessView()); // return new ModelAndView("showproduct");

157 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- showproduct.jsp --> <%@ page language="java" %> <html> <body bgcolor=#ffffcc text=green> <h1><center>new product information</h1><hr><br><h3> <%= request.getAttribute("productinfo") %> </body> </html> Example: Spring MVC example with "Controller" interface <!-- index.jsp --> <jsp:forward page="/display.form" /> <!-- web.xml --> <web-app> <servlet> <servlet-name>accaction</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>accaction</servlet-name> <url-pattern>*.form</url-pattern> </servlet-mapping> <taglib> <taglib-uri>spring-tld</taglib-uri> <taglib-location>/WEB-INF/spring.tld</taglib-location> </taglib> </web-app> <!-- accaction-servlet.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="simpleUrlMappings" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property name="mappings">

158 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 </bean>

Sathya Technologies <props>

Spring

Kanakadhar Surapaneni :)

<prop key="/display.form">displayaccController</prop> <prop key="/newacc.form">newaccController</prop> </props> </property> </bean> <bean id="displayaccController" class="DisplayAccountsController" > <property name="dsource"> <ref bean="ds" /> </property> <bean id="newaccController" class="NewAccountController" > <property name="sessionForm" > <value>true</value></property> <property name="commandName" > <value>account</value></property> <property name="commandClass" > <value>Account</value></property> <property name="formView" > <value>newaccount</value></property> <property name="successView" > <value>index</value></property> <property name="dsource"> <ref bean="ds" /> </property> </bean> <bean id="viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property> <property name ="prefix"><value>/</value></property> <property name ="suffix"><value>.jsp</value></property> </bean> <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value></property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value> </property>

159 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<property name="username" ><value>scott</value></property> <property name="password" ><value>tiger</value></property> </bean> </beans> //Account.java public class Account { private int acno; private String acname; private double balance; public Account(){} public Account(int a,String b,double c) { acno=a; acname=b; balance=c; public void setAcno(int n){ acno=n; } public int getAcno(){ return acno; } public void setAcname(String s){ acname=s; } public String getAcname(){ return acname; } public void setBalance(double p){ balance=p; } public double getBalance(){ return balance; } // DisplayAccountsController.java import org.springframework.web.servlet.mvc.*; import org.springframework.web.servlet.*; import org.springframework.validation.*; import javax.servlet.http.*; import javax.sql.*; import java.util.*; import org.springframework.jdbc.core.*; import org.springframework.jdbc.support.rowset.*;

160 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public class DisplayAccountsController implements Controller { private DataSource dsource; public void setDsource(DataSource ds) { dsource=ds; public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) { List accs=new ArrayList(); try{ JdbcTemplate jt=new JdbcTemplate(dsource); SqlRowSet rs=jt.queryForRowSet("select * from bank"); while(rs.next()) { accs.add(new Account(rs.getInt(1),rs.getString(2),rs.getDouble(3))); } }catch(Exception e){ System.out.println(e); } return new ModelAndView("displayaccounts","listaccounts",accs);

<!-- displayaccounts.jsp --> <%@ page language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <html> <body bgcolor=#ffffcc text=green> <h1><center>all accounts information</h1><hr><br><h3> <table width=80% border=2> <tr><th>a/c number<th>a/c holder name<th> balance</tr> <c:forEach items="${listaccounts}" var="acc" > <tr> <td><c:out value="${acc.acno}" /> <td><c:out value="${acc.acname}" /> <td><c:out value="${acc.balance}" />

161 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 </tr>

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

</c:forEach> </table> <center><br><br> <a href="/AccountsMvc/newacc.form">new account</a> </body> </html> <!-- newaccount.jsp --> <%@ page language="java" %> <%@ taglib prefix="spring" uri="spring-tld" %> <html> <body bgcolor=#ffffcc text=green> <h1><center>new account information</h1><hr><br><h3> <form method="post" > enter a/c number : <spring.bind path="account.acno" > <input type=text name=acno /> </spring.bind> <br><br> enter a/c holder name : <spring.bind path="account.acname" > <input type=text name=acname /> </spring.bind> <br><br> enter open balance : <spring.bind path="account.balance" > <input type=text name=balance /> </spring.bind> <br><br> <input type=submit value=save /> </form> </body> </html>

162 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

// NewAccountController.java import org.springframework.web.servlet.mvc.*; import org.springframework.web.servlet.*; import org.springframework.validation.*; import javax.servlet.http.*; import javax.sql.*; import org.springframework.jdbc.core.*; public class NewAccountController extends SimpleFormController { private DataSource dsource; public void setDsource(DataSource ds) { dsource=ds; public ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException e1) throws Exception { Account a1=(Account)command; try{ JdbcTemplate jt=new JdbcTemplate(dsource); jt.update("insert into bank values(?,?,?)",new Object[]{new Integer(a1.getAcno()),a1.getAcname(),new Double(a1.getBalance())}); }catch(Exception e){ System.out.println(e); } return new ModelAndView(getSuccessView());

Example: Pure Struts Application <!-- web.xml --> <web-app> <!-- Action Servlet Configuration --> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name>

163 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- The Usual Welcome File List --> <welcome-file-list> <welcome-file>register.jsp</welcome-file> </welcome-file-list> <!-- Struts Tag Library Descriptors --> <taglib> <taglib-uri>/hi-friends-geve</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> </web-app> <!-- register.jsp --> <%@ taglib uri="/hi-friends-gmg" prefix="html" %> <html:html> <html:form action = "/register"> <table border = 0 align = center> <tr> <th>UserName <td><html:text property = "username"/> </tr> <tr> <th>PassWord <td><html:password property = "password"/> </tr> <tr> <td colspan = 2 align = center> <html:submit value = "Register"/>

164 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 } }

Sathya Technologies </tr> </table> </html:form>

Spring

Kanakadhar Surapaneni :)

</html:html> <!-- struts-config.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"> <struts-config> <form-beans> <form-bean name="registerForm" type="app.RegisterForm"/> </form-beans> <action-mappings> <action name="registerForm" path="/register" type="app.RegisterAction"> <forward name="ok" path="/success.jsp"/> <forward name="fail" path="/failure.jsp"/> </action> </action-mappings> </struts-config> //RegisterForm.java package app; import org.apache.struts.action.*; public class RegisterForm extends ActionForm { private String username = null; private String password = null; public void setUsername(String username) { this.username = username; public String getUsername() { return username;

165 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 </html> } } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public void setPassword(String password) { this.password = password; public String getPassword() { return password;

// RegisterAction.java package app; import org.apache.struts.action.*; import javax.servlet.http.*; public class RegisterAction extends Action { public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)throws Exception { RegisterForm rf = (RegisterForm)form; String user = rf.getUsername(); String pass = rf.getPassword(); if(user.equals("sathya") && pass.equals("java")) return mapping.findForward("ok"); else return mapping.findForward("fail");

<!-- success.jsp --> <html> <body> <center> <font size = 5 color = green>Login Successfull</font> </center> </body>

166 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 </html>

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- failure.jsp --> <html> <body> <center> <font size = 5 color = red>Login Failure</font><br> <a href = "register.jsp">Try Again</a> </center> </body> Note: Place struts related jar files inside "lib" folder of WEB-INF. //Example: Integeration of struts & Spring <!-- web.xml --> <web-app> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern> *.do </url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <taglib> <taglib-uri>struts-html</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> </web-app>

167 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- index.jsp --> <%@ page language="java" %> <%@ taglib prefix="html" uri="struts-html" %> <html> <body bgcolor=#ffffcc text=green> <h1><center>struts framewrok</h1><hr><br><h3> <html:form action="/demo"> enter user name :<html:text property="uname" /> <br><br> <html:submit value="wish" /> </html:form> </body> </html> <!-- struts-config.xml --> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"> <struts-config> <form-beans> <form-bean name="demofrm" </form-beans> <action-mappings> <action path="/demo" name="demofrm" type="org.springframework.web.struts.DelegatingActionProxy" > <forward name="success" path="/result.jsp" /> </action> </action-mappings> <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> </plug-in> </struts-config> <!--action-servlet.xml--> [Spring Configuration File] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> type="demopack.DemoForm" />

168 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 } } } } </bean>

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<bean name="/demo" class="demopack.DemoAction" > <property name="model"> <ref bean="d1" /> </property> <bean id="d1" class="demopack.ModelImpl" > </bean> </beans> // DemoForm.java package demopack; import org.apache.struts.action.*; public class DemoForm extends ActionForm { private String uname; public void setUname(String s) { uname=s; public String getUname() { return uname;

//ModelInter.java package demopack; public interface ModelInter { public String getWish(); // ModelImpl.java package demopack; import java.util.*; public class ModelImpl implements ModelInter { public String getWish()

169 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 } } } } {

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

Calendar c1=Calendar.getInstance(); int h=c1.get(Calendar.HOUR_OF_DAY); if(h < 12) return "Good Morning"; else if( h < 17) return "Good Afternoon"; else return "Good Evening";

// DemoAction.java package demopack; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import org.apache.struts.action.*; public class DemoAction extends Action { private { model=i1; public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { DemoForm f1=(DemoForm)form; String uname=f1.getUname(); String msg=model.getWish()+" "+ uname; request.setAttribute("message",msg); return mapping.findForward("success"); ModelInter model; public void setModel(ModelInter i1)

170 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

<!-- result.jsp --> <%@ page language="java" %> <%@ taglib prefix="html" uri="struts-html" %> <html> <body bgcolor=#ffffcc text=green> <h1><center>struts framewrok</h1><hr><br><h3> <%= request.getAttribute("message") %> <br><br> <html:link href="index.jsp" >home</html:link> </body> </html> Note: In "lib" folder of WEB_INF we need to place related jar files of spring & struts. //Example: Integration of struts, spring & hibernate <!-- web.xml --> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern> *.do </url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>

171 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143

Sathya Technologies <taglib> <taglib-uri>struts-html</taglib-uri>

Spring

Kanakadhar Surapaneni :)

<taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> </web-app> <!-- index.jsp --> <%@ page language="java" %> <%@ taglib prefix="html" uri="struts-html" %> <html> <body bgcolor=#ffffcc text=green> <h1><center>new user information</h1><hr><br><h3> <html:form action="/user"> enter user name :<html:text property="uname" /> <br><br> select role: <table> <tr><td> <html:radio property="role" value="Administrator">Administrator</html:radio> <td><html:radio property="role" value="User">User</html:radio> </tr> <tr> <td><html:radio property="role" value="Salesman">Salesman</html:radio> <td> <html:radio property="role" value="Manager">Manager</html:radio> </tr> </table> <html:submit value="save" /> </html:form> </body> </html> <!-- struts-config.xml --> <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"> <struts-config>

172 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178

Sathya Technologies <form-beans> <form-bean name="userform" </form-beans> <action-mappings>

Spring

Kanakadhar Surapaneni :)

type="demo.UserForm" />

<action path="/user" name="userform" type="org.springframework.web.struts.DelegatingActionProxy" > <forward name="success" path="/result.jsp" /> <forward name="failure" path="/index.jsp" /> </action> </action-mappings> <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> </plug-in> </struts-config> <!-- action-servlet.xml--> [Spring Configuration file] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean name="/user" class="demo.UserAction" > <property name="model"> <ref bean="d1" /> </property> </bean> <bean id="d1" class="demo.ModelImpl" > <property name="sesfact"> <ref bean="mySessionFactory" /> </property> </bean> <bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:sathya</value>

173 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

</property> <property name="username"> <value>scott</value> </property> <property name="password"> <value>tiger</value> </property> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="mappingResources"> <list> <value>User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> </props> </property> </bean> </beans> //ModelInter.java package demo; public interface ModelInter { public boolean insertInfo(String uname,String role); // ModelImpl.java package demo; import java.util.*; import org.hibernate.*; public class ModelImpl implements ModelInter {

174 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 } } } }

Sathya Technologies private SessionFactory sesfact;

Spring

Kanakadhar Surapaneni :)

public void setSesfact(SessionFactory sf) { sesfact=sf; public boolean insertInfo(String uname,String role) { Session ses=sesfact.openSession(); Transaction tx=ses.beginTransaction(); boolean flag=false; try{ User u1=new User(); u1.setUname(uname); u1.setRole(role); ses.save(u1); tx.commit(); flag=true; }catch(Exception e) { } ses.close(); return flag; tx.rollback(); System.out.println(e);

//User.java package demo; public class User{ private int uid; private String uname,role; public void setUid(int n) { uid=n;

175 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 } } }

Sathya Technologies public int getUid(){ return uid; }

Spring

Kanakadhar Surapaneni :)

public void setUname(String s){ uname=s; } public String getUname(){ return uname; } public void setRole(String r){ role=r; } public String getRole(){ return role; } <!-- User.hbm.xml --> <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="demo.User" table="users" > <generator class="increment" /> </id> <property name="uname" /> <property name="role" /> </class> </hibernate-mapping> // UserForm.java package demo; import org.apache.struts.action.*; public class UserForm extends ActionForm { private String uname,role; public void setUname(String s) { uname=s; public String getUname() { return uname; public void setRole(String s){ role=s; } <id name="uid" column="userid" >

176 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 } } } }

Sathya Technologies

Spring

Kanakadhar Surapaneni :)

public String getRole(){ return role; }

// UserAction.java package demo; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import org.apache.struts.action.*; public class UserAction extends Action { private { model=i1; public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { UserForm f1=(UserForm)form; String uname=f1.getUname(); String role=f1.getRole(); if(model.insertInfo(uname,role)) return mapping.findForward("success"); else return mapping.findForward("failure"); ModelInter model; public void setModel(ModelInter i1)

<!-- result.jsp --> <%@ page language="java" %> <%@ taglib prefix="html" uri="struts-html" %> <html> <body bgcolor=#ffffcc text=green> <h1><center>welcome user</h1><hr> </body> </html>

You might also like