How to go with Spring

To start with Spring framework, one needs to download latest SpringFramework jar from http://www.springframework.org. There will be two zip files one with dependencies and other without. The spring framework with dependencies is larger and includes all dependent libraries. Example: Download Spring framework 1.2 without dependency and unzip on the hard disk as spring12 Inside the folder spring12 we can find 7 folders. The name and the contents of all the folders are given below, 1. dist: It contains various Spring distribution jar files. 2. docs: It contains general documentation and API javadocs. 3. mock: It contains mock JNDI contexts and a set of servlet API mock objects. 4. samples: It contains demo applications and skeletons. 5. src: It contains the Java source files for the framework. 6. test: It contains the Java source files for Spring's test suite. 7. tiger: It contains JDK1.5 examples and test suite. Inside the "dist" directory, we can find all the jar files necessary for compiling and executing the program. The jar files and its contents are listed below: 1. spring.jar : It contains the entire Spring framework including everything in the other JAR files also. 2. spring-core.jar : It contains the core Spring container and its utilities. 3. spring-beans.jar : It contains the bean Spring container and JavaBeans support utilities. 4. spring-aop.jar : It contains Spring's AOP framework, source-level metadata support, AOP Alliance interfaces etc., 5. spring-context.jar : It contains application context, validation framework, JNDI, templating support and scheduling. 6. spring-dao.jar : It contains DAO support and transaction infrastructure. 7. spring-jdbc.jar : It contains the JDBC support. 8. spring-support.jar : It contains JMX support, JCA support, scheduling support, mail support and caching support. 9. spring-web.jar : It contains the web application context, multipart resolver, Struts support, JSF support and web utilities. 10. spring-webmvc.jar : It contains the framework servlets, web MVC framework, web controllers and web views. 11. spring-remoting.jar :It contains remoting support, EJB support and JMS support. 12. spring-orm.jar : It contains iBATIS SQL Maps support, Apache OJB support, TopLink support and JDO support. 13. spring-hibernate.jar : It contains Hibernate 2.1 support, Hibernate 3.x support. 14. spring-mock.jar : It contains JNDI mocks, Servlet API mocks and JUnit support.

Created by Jill

1

Spring has strict dependency on commons-logging.jar, Download Apache Commons-logging.jar from http://commons.apache.org/downloads/download_logging.cgi. Add spring.jar and commons-logging.jar to project’s classpath. For a typical Spring Application we need the following files 1. An interface that defines the functions. 2. An Implementation that contains properties, its setter and getter methods, functions etc., 3. A XML file called Spring configuration file. 4. Client program that uses the function. Ex: 1. Hello.java 2. HelloImpl.java 3. Hello.xml 4. HelloClient.java HelloI.java:
public interface Hello { public String sayhello(String a); }

HelloImpl.java
public class HelloImpl implements Hello { private String greeting; public HelloImpl() { } public HelloImpl(String a) { greeting = a; } public void setGreeting(String a) { greeting = a; } public String sayhello(String a) { return greeting + a; } }

Created by Jill

2

Hello.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="hello" class="HelloImpl"> <!-- <property name="greeting"> <value>Good Morning!...</value> </property> --> <constructor-arg> <value>Good Morning!...</value> </constructor-arg> </bean> </beans>

HelloClient.java:
import import import import org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;

public class HelloClient { /** * @param args */ public static void main(String[] args) { try { Resource res = new ClassPathResource("hello.xml", HelloClient.class); System.out.println(res.getFile().getAbsolutePath()); BeanFactory factory = new XmlBeanFactory(res); Hello bean1 = (Hello) factory.getBean("hello"); String s = bean1.sayhello("Jill"); System.out.println(s); } catch (Exception e1) { e1.printStackTrace(); } } }

Run HelloClient.java as a java Application: U should be getting the following message in the console:

Spring with Servlet
Created by Jill 3

For a typical Spring based Web Application we need the following files 1. An interface that defines the functions. 2. An Implementation that contains properties, its setter and getter methods, functions etc., 3. A XML file called Spring configuration file. 4. A HTML file to do request Post. 5. Servlet Program to process the HTML Request. Ex: 1.Hello.java [As mentioned in page:1] 2.HelloImpl.java [As mentioned in page:1] 3.Hello.xml [As mentioned in page:2] 4. Hello.html 5. ServletClient.java Hello.html:
<html> <body> <form method=post action="http://localhost:7001/springTest/servlet/ServletClient"> <center> <p> <input type=text name="text1"></p> <p> <input type=submit name="Submit"></p> </center> </form> </body> </html>

Created by Jill

4

ServletClient.java:
import java.io.IOException; import java.io.PrintWriter; import import import import import import import import javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource;

public class ServletClient extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("Welcome to Spring"); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); String a = req.getParameter("text1"); try { Resource res = new ClassPathResource("hello.xml", ServletClient.class); BeanFactory factory = new XmlBeanFactory(res); Hello bean1 = (Hello) factory.getBean("hello"); String s = bean1.sayhello(a); out.println(s); } catch (Exception e) { e.printStackTrace(); } } }

Created by Jill

5

Build the war: 1. web.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>ServletClient</servlet-name> <display-name>Simple Servlet Client to test Spring</display-name> <servlet-class>a.b.ServletClient</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletClient</servlet-name> <url-pattern>/servlet/ServletClient</url-pattern> </servlet-mapping> <session-config> <session-timeout>0</session-timeout> </session-config> <welcome-file-list> <welcome-file>uis/hello.html</welcome-file> </welcome-file-list> </web-app>

2. weblogic.xml For Weblogic server:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 8.1//EN" "http://www.bea.com/servers/wls810/dtd/weblogic810-web-jar.dtd"> <weblogic-web-app> <description><![CDATA[Generated by XDoclet. Use weblogicwebxml's description attribute to modify this value.]]></description> <weblogic-version>8.1</weblogic-version> <context-root>springTest</context-root> </weblogic-web-app>

Created by Jill

6

3. War Folder Structure:

4. Deploy war on Weblogic, Run hello.html:

5. Enter “Jill” in text box and click “Submit” Button:

Created by Jill

7

Spring and DB Access
Spring comes with a family of data access frameworks that integrates well will variety of data access technologies like JDBC, Java Data Objects and Object Relational Mapping (ORM) tools like Hibernate, OJB, iBatis etc., Many J2EE application servers and even web servers provide a 'dataSource' via Jndi name. To configure the spring bean with the Jndi name of our 'dataSource' and use its connection pooling facility 'JndiObjectFactoryBean' is used. When a DataSource is not present, we need a connection pooling bean that implements 'dataSource'. For this purpose we use 'dbcp.BasicDataSource' is used. By using this we can have a 'dataSource' with connection pooling independent of application server. To perform unit-tests in our data access code, spring comes with a very lightweight 'dataSource' implementation class: 'DriverManagerDataSource'. This class can be easily configured for unit tests as:
DriverManagerDataSource dataSource = new dataSource.setDriverClassName(driver); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); DriverManagerDataSource();

These properties can be configured in the spring configuration file also. Spring comes with its own data access framework. Spring separates the fixed and variant parts of data access process into two distinct classes: Template and Callback. Template manages the fixed part of our framework like data connection, managing resources, controlling transaction etc. Callback defines the things that are specific to our application like creating statements, binding parameters etc. The template class of Spring is 'JdbcTemplate'. A 'dataSource' is provided inside JdbcTemplate. An example of database connection using 'JdbcTemplate' is shown below. Here we are using 'MySql' database. The MySql database can be downloaded from http://www.mysql.com. Install MySQL. Download mysql-connector-java-5.0.6-bin.jar, add it in weblogic’s lib folder and add this in project’s classpath. For a simple Spring based Web application with data persistence, we need the following files: 1. An interface that defines the functions. 2. An Implementation that contains properties, its setter and getter methods, functions etc. 3. A XML file called Spring’s Data configuration file. 4. A HTML file to do request Post. 5. Servlet Program to process the HTML Request.

Created by Jill

8

Ex: 1. DataCon.java 2. DataConImpl.java 3. DataCon.xml 4. SpringServlet.java 5. springServlet.html DataCon.java:
package dbtest; import javax.sql.DataSource; public interface DataCon { public DataSource dbcon(); }

DataConImpl.java:
package dbtest; import javax.sql.DataSource; public class DataConImpl implements DataCon { private DataSource dataSource; public void setDataSource(DataSource ds) { dataSource = ds; } public DataSource dbcon() { return dataSource; } }

Created by Jill

9

DatCon.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="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/test</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>Harry123</value> </property> </bean> <bean id="datacon" class="dbtest.DataConImpl"> <property name="dataSource"> <ref local="dataSource"/> </property> </bean> </beans>

Created by Jill

10

SpringServlet.java:
package dbtest; import import import import import import import import import import import import import import java.io.IOException; java.io.PrintWriter; java.util.Iterator; java.util.List; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.sql.DataSource; org.springframework.beans.factory.BeanFactory; org.springframework.beans.factory.xml.XmlBeanFactory; org.springframework.core.io.ClassPathResource; org.springframework.core.io.Resource; org.springframework.jdbc.core.JdbcTemplate;

public class SpringServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); String a = req.getParameter("text1"); String b = req.getParameter("text2"); String c = req.getParameter("combo1"); String d = req.getParameter("combo2"); try { System.out.println("Wait..."); Resource res = new ClassPathResource("DataCon.xml", SpringServlet.class); BeanFactory factory = new XmlBeanFactory(res); DataCon bean1 = (DataCon) factory.getBean("datacon"); DataSource ds = bean1.dbcon(); if (d.equals("add")) { JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("insert into table1 values('" + a + "','" + b + "') "); out.println("Record Added"); } if (d.equals("delete")) { JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("delete from table1 where name='" + a + "' "); out.println("Record Deleted"); } if (d.equals("find")) { List list1; JdbcTemplate jt = new JdbcTemplate(ds);

Created by Jill

11

list1 = jt.queryForList("select * from table1 where name='" + a + "'"); Iterator i = list1.iterator(); while (i.hasNext()) { Object ob = i.next(); out.println(ob.toString()); } } if (d.equals("update")) { if (c.equals("name")) { JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("update table1 set table1.place='" + b + "'where table1.name='" + a + "' "); } if (c.equals("place")) { JdbcTemplate jt = new JdbcTemplate(ds); jt.execute("update table1 set table1.name='" + a + "'where table1.place='" + b + "' "); } out.println("Record Updated"); } }catch (Exception e1) { e1.printStackTrace(); System.out.println("" + e1); } } }

Created by Jill

12

springServlet.html:
<html> <body bgcolor="pink"> <form method=post action="http://localhost:7001/springServletSimpleDB/servlet"> Name: <input type=text name="text1"> <br><br> Place: <input type=text name="text2"> <br><br> Criterion: <select name="combo1" size=1> <option value="name">Name <option value="place">Place </select> <br><br> <select name="combo2" size=1> <option value="add">Add <option value="delete">Remove <option value="find">Find <option value="update">Update </select> <br><br> <input type=submit name="SUBMIT"> </form> </body> </html>

Build War: 1. web.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>SpringServlet</servlet-name> <display-name>Servlet to Test Spring with MySQL</display-name> <servlet-class>dbtest.SpringServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringServlet</servlet-name> <url-pattern>/servlet</url-pattern> </servlet-mapping> <session-config> <session-timeout>0</session-timeout> </session-config> <welcome-file-list> <welcome-file>uis/springServlet.html</welcome-file> </welcome-file-list> </web-app>

Created by Jill

13

2. weblogic.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web Application 8.1//EN" "http://www.bea.com/servers/wls810/dtd/weblogic810-web-jar.dtd"> <weblogic-web-app> <description><![CDATA[Generated by XDoclet. Use weblogicwebxml's description attribute to modify this value.]]></description> <weblogic-version>8.1</weblogic-version> <context-root>springServletSimpleDB</context-root> </weblogic-web-app>

3. War folder structure:

4. Create war “ jar –cf SpringServletSimpleDB.war * “ from the command prompt.

Created by Jill

14

5. Deploy war on Weblogic and run the “springServlet.html”

Enter name and place and select add/delete/update/find and click on “Submit Query’ button.

Created by Jill

15

Check in MySQL for record addition:

Created by Jill

16

Spring & Hibernate Interaction

Spring can simplify your Hibernate application. Spring's Hibernate integration uses the same generic transaction infrastructure and DAO exception hierarchy that it uses for JDBC, JDO, iBATIS, and TopLink, making it easy to mix and match persistence methodologies if necessary. There are two approaches to Spring's Hibernate integration: 1. Inversion of Control with a HibernateTemplate and Callback 2. Extending HibernateDaoSupport and Applying an AOP Interceptor The IoC/HibernateTemplate methodology feels a lot like the JdbcTemplate methodology as discussed in the above example web application. Spring's lightweight bean container offers IoC-style wiring up of business objects, DAOs, and resources like JDBC DataSources and Hibernate SessionFactories. Such an XML-defined application context is a powerful alternative to manually managed singletons or factories that parse their configuration from custom properties files. As non-intrusiveness is a central goal, such Spring-configured application beans do not need to depend on Spring interfaces or classes but get configured via their bean properties. This concept can be applied in any environment, be it a J2EE web app, a desktop app, or even an applet. In the context of Hibernate, Spring's generic transaction management for DAOs is of particular interest. The goal is to separate data access and transaction demarcation aspects to allow for reusable transactional business objects that are not tied to any specific data access or transaction strategy. Demarcation can either happen programmatically via TransactionTemplate, or declaratively via the AOP TransactionInterceptor. Both native Hibernate / JDBC transactions and JTA are supported as strategies out-of-the-box. This is a viable alternative to local Stateless Session Beans. Spring's HibernateTemplate offers a simple way to implement Hibernate-based DAOs without caring about handling Session instances or participating in transactions. No need for try-catch blocks, no need for transaction checks. A simple Hibernate access method can be a one-liner! Combining heterogeneous DAOs works seamlessly, both in terms of DAO interfaces and participating in transactions. For example, certain DAOs can be implemented on plain JDBC, preferably via Spring's JdbcTemplate to avoid manual exception handling.

Created by Jill

17