Spring Integration Webapp
Spring is one of the best Framework’s around in J2EE field which has made integration to various Framework pretty easy. This article is in series of articles which teach about spring integration in details. All source code is checked into svn which can be checked out and tested.
Assumption : Readers has basic knowledge of Servlets and JSP technologies.
Background : Sample project named testspring has been create in modular manner using Maven. I used 2 differrent database schema names of mysql testjpa/testejb to test this project. I have configured
so that once proper connectivity is made program on startup will generate all tables in database
Any framework that has to integrated into J2EE frontend technology has to get control from Servlet Container, As all “http”(There can be other requests RMI/JMS..etc) requests are passed on to servlet container first which inturn based on configuration passes to corresponding framework.
All the integrations are generally handle using servlet mapping, or using listeners or filters in Webapplication.
To to integrate spring in webapplication we have to do the following Configure spring Listener and Servlet in web.xml
Now that you have configured spring now start configuring spring beans in Spring configuration files.( As per the above configuration file. All requests with url pattern services/* will get routed to spring dispatcher servlet. Which inturn takes care of request mapping based on Configuration files or using Annotations.
if you have observerd the spring servlet name is “dispatcher”
so the configuration file that is read by default will be dispatcher-servlet.xml and then other files with same name pattern defined in context-param will get loaded.
Attached is my Dispatcher Servlet Sample code
Above code has Configuration to define view resolver (We can integrate different View Technologies in it JSP/Freemarker/Velocity…etc). I’m using freemarker in my example. It also has a commented code which uses jsp as view resolver
The above configuration is basic configuration for Spring MVC. If you have observed it we have defined that spring should discover beans by itself based on annotations rather than configuration stuff. Annotations make is easier for developer to define beans avoiding unnecessary xml configuration which is difficult to remember
Above configuration also lists out url pattern’s that have to be excluded in this flow (Example all css/js/p_w_picpaths etc files ).
Below is same Spring MVC controller which is configured through annotations
C:\development\linkwithweb\svn\SpringTutorials\testspring\p_w_picpaths
If you look into the code it defines that this class is a Spring MVC Controller(Class that handles all requests)
All the methods that you want to expose in this class should get a RequestMapping annotation with URL pattern and corresponding attributes defined for that
Ex:@RequestMapping(value = “/test”, method = RequestMethod.POST) (This says any URL with services/test has to be handled by this method).. “services” is base url for spring requests which is configured in web.xml
You can directly render response from here using ResponseBody annotation or you can create model object and pass it to View Technology to render that by creating ModelAndView as response object
In the above example i have @ResponseBody annotation configured for one method and i have configured to receive JSON repsonse for any ResponseBody annotation in my app-config.xml
Here is sample Spring MVC Design
Read more about spring MVC in
http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html
The below one is one of best link which explains all different way you can use Rest Style URL in Spring MVC
http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/
Now that i have given basic Introduction to Spring MVC integration i’ll take you through JPA Configuration both in Tomcat as well as JBOSS.
JPA can be used in 2 ways ( Using Spring and Using EJB3 container) . As we don’t have EJB container in tomcat we use spring to configure JPA for us.
Let me start with JPA/Hibernate using Spring in tomcat
I have configured JPA in app-jpa-config.xml in testspring-webapp/WEB-INF/spring folder (Checkout code from svn to see project structure)
Here is snippet of the JPA config file
As you see here we have configured persistenceUnitName as “testspring-jpa”. This name has been configured in persistence.xml of testspring-java project module. Here is the snippet for that
And now that we have configured spring we can create entities in JPA style and use EntityManager to fire our queries.
Here is the sample welcomeService that is used in our Spring MVC controller
Now Lets switch to other part of using JPA with EJB ( This can be tested in jboss)
Here is sample snippet of stateless session bean in testspring-ejb project that is using JPA to get list of users
Below is code of User Entity i have created
Now that we are done with basic end to end integration .I’ll also show how to inject EJB in Servlet/Spring MVC
Below is sample servlet which called stateless bean . Same method is used in spring MVC too
Now that i have covered all topics from frontend to db, now i’ll take you though how to configure webservices. I’ll show examples with both Apache CXF and JAX-WS
Webservices
Similar to spring MVC configuration through servlet , we have to configure both JAX-WS and Apache CXF through their own servlets. Below is servlet configuration to enable them
Now that we have configured respective URL patterns now lets see configuration in Spring that is required to expose Beans as webservices
Webservice configuration for spring is configured in app-ws-config.xml
Below is how i have expose OrderService as webservice for apache CXF
Below is code of bean which is exposed by JAX-WS
Sample WSDL URL’s
http://localhost:8080/testspring-webapp/webservice/OrderProcess?wsdl
http://localhost:8080/testspring-webapp/ws?wsdl
And finally one more thing which i haven’t used in example. I have configured HSQLDB to used so that any demo’s need not have an external database but have Inbuilt DB
Here is how you do that
If you use http://localhost:8080/appname/admin/h2 you will goto to HSQLDB Admin console
I think i have covered all concepts and code snippets to get you started.
Code has been checked in to
https://linkwithweb.googlecode.com/svn/trunk/SpringTutorials/testspring
Checkout
mvn clean install package
testspring-war ( Webapp code for ear file) (To be deployed on Jboss
testspring-ejb (Has ejb code)
testspring-ear – Combining both ejb and war to create ear
———————————————–
testspring-java (Java code used in tomcat)
testspring-webapp ( Web configuration for tomcat)
to test on tomcat follow the below steps
cd testspring-webapp
mvn tomcat:run and njoy playing with code
Njoy playing with code. Get back to me if you have any questions.
Assumption : Readers has basic knowledge of Servlets and JSP technologies.
Background : Sample project named testspring has been create in modular manner using Maven. I used 2 differrent database schema names of mysql testjpa/testejb to test this project. I have configured
so that once proper connectivity is made program on startup will generate all tables in database
Any framework that has to integrated into J2EE frontend technology has to get control from Servlet Container, As all “http”(There can be other requests RMI/JMS..etc) requests are passed on to servlet container first which inturn based on configuration passes to corresponding framework.
All the integrations are generally handle using servlet mapping, or using listeners or filters in Webapplication.
To to integrate spring in webapplication we have to do the following
contextConfigLocation
/WEB-INF/spring/app-config.xml,
/WEB-INF/spring/app-*-config.xml
org.springframework.web.context.ContextLoaderListener
org.springframework.web.context.request.RequestContextListener
dispatcher
org.springframework.web.servlet.DispatcherServlet
1
dispatcher
/services/*
Now that you have configured spring now start configuring spring beans in Spring configuration files.( As per the above configuration file. All requests with url pattern services/* will get routed to spring dispatcher servlet. Which inturn takes care of request mapping based on Configuration files or using Annotations.
if you have observerd the spring servlet name is “dispatcher”
so the configuration file that is read by default will be dispatcher-servlet.xml and then other files with same name pattern defined in context-param will get loaded.
Attached is my Dispatcher Servlet Sample code
Above code has Configuration to define view resolver (We can integrate different View Technologies in it JSP/Freemarker/Velocity…etc). I’m using freemarker in my example. It also has a commented code which uses jsp as view resolver
The above configuration is basic configuration for Spring MVC. If you have observed it we have defined that spring should discover beans by itself based on annotations rather than configuration stuff. Annotations make is easier for developer to define beans avoiding unnecessary xml configuration which is difficult to remember
Above configuration also lists out url pattern’s that have to be excluded in this flow (Example all css/js/p_w_picpaths etc files ).
Below is same Spring MVC controller which is configured through annotations
C:\development\linkwithweb\svn\SpringTutorials\testspring\p_w_picpaths
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.northalley.template.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import com.northalley.template.services.WelcomeService;
/**
* @author ashwin kumar
*
*/
@Controller
public class GenericController {
@Autowired
@Qualifier("welcomeService")
private WelcomeService welcomeService;
/**
* Constructor
*/
public GenericController() {
}
/**
* @param searchCriteria
* @param formBinding
* @param request
* @return
*/
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public Response search(SearchCriteria searchCriteria,
BindingResult formBinding, WebRequest request) {
Response response = new Response();
response.setWelcome(welcomeService.hello("Ashwin"));
return response;
}
@RequestMapping("/freemarkertest")
public ModelAndView hello() {
return new ModelAndView("hello", "greeting", "Hello world!");
}
}
If you look into the code it defines that this class is a Spring MVC Controller(Class that handles all requests)
All the methods that you want to expose in this class should get a RequestMapping annotation with URL pattern and corresponding attributes defined for that
Ex:@RequestMapping(value = “/test”, method = RequestMethod.POST) (This says any URL with services/test has to be handled by this method).. “services” is base url for spring requests which is configured in web.xml
You can directly render response from here using ResponseBody annotation or you can create model object and pass it to View Technology to render that by creating ModelAndView as response object
In the above example i have @ResponseBody annotation configured for one method and i have configured to receive JSON repsonse for any ResponseBody annotation in my app-config.xml
Here is sample Spring MVC Design
Read more about spring MVC in
http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html
The below one is one of best link which explains all different way you can use Rest Style URL in Spring MVC
http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/
Now that i have given basic Introduction to Spring MVC integration i’ll take you through JPA Configuration both in Tomcat as well as JBOSS.
JPA can be used in 2 ways ( Using Spring and Using EJB3 container) . As we don’t have EJB container in tomcat we use spring to configure JPA for us.
Let me start with JPA/Hibernate using Spring in tomcat
I have configured JPA in app-jpa-config.xml in testspring-webapp/WEB-INF/spring folder (Checkout code from svn to see project structure)
Here is snippet of the JPA config file
org.hsqldb.jdbcDriver
jdbc:hsqldb:mem:testspring-db
sa
As you see here we have configured persistenceUnitName as “testspring-jpa”. This name has been configured in persistence.xml of testspring-java project module. Here is the snippet for that
And now that we have configured spring we can create entities in JPA style and use EntityManager to fire our queries.
Here is the sample welcomeService that is used in our Spring MVC controller
/*
*/
package org.northalley.template.testspring.services;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.northalley.template.testspring.entities.Welcome;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("welcomeService")
public class WelcomeServiceImpl implements WelcomeService {
@PersistenceContext
private EntityManager entityManager;
@Transactional
public Welcome hello(String name) {
if (name == null || name.trim().length() == 0)
throw new RuntimeException("Name cannot be null or empty");
Welcome welcome = null;
try {
Query q = entityManager
.createQuery("select w from Welcome w where w.name = :name");
q.setParameter("name", name);
welcome = (Welcome) q.getSingleResult();
} catch (NoResultException e) {
welcome = new Welcome();
welcome.setName(name);
welcome.setMessage("Welcome " + name);
entityManager.persist(welcome);
}
return welcome;
}
}
Now Lets switch to other part of using JPA with EJB ( This can be tested in jboss)
Here is sample snippet of stateless session bean in testspring-ejb project that is using JPA to get list of users
package org.testspring.ejb.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testspring.ejb.entity.User;
/**
* @author ashwin kumar
*
*/
@Stateless(mappedName = "userDAOBean")
public class UserDAOBean implements UserDAO {
private static Log log = LogFactory.getLog(UserDAOBean.class);
private EntityManager em;
@PersistenceContext(unitName = "TestEntityManager")
public void setEm(EntityManager em) {
this.em = em;
}
public List getUsers() {
log.debug("getUsers");
List users = this.em.createQuery(
"select user from User user order by user.lastName")
.getResultList();
return users;
}
// not using this method in this example app
public User saveUser(User user) {
log.debug("saveUser: " + user);
this.em.persist(user);
this.em.flush();
return user;
}
}
Below is code of User Entity i have created
package org.testspring.ejb.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
//if the table name matches your class name, you don't need the 'name' annotation
@Table(name="lt_user")
public class User extends BaseEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
//we don't need the Column annotation here bc the column name and this field name are the same
private Long id;
@Column(name="first_name",nullable=false,length=50)
private String firstName;
@Column(name="last_name",nullable=false,length=50)
private String lastName;
private Date birthday;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
Now that we are done with basic end to end integration .I’ll also show how to inject EJB in Servlet/Spring MVC
Below is sample servlet which called stateless bean . Same method is used in spring MVC too
package com.testspring.servlet;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.testspring.ejb.dao.UserDAO;
import org.testspring.ejb.entity.User;
import com.testspring.service.MathService;
/**
* @author ashwin kumar
*
*/
public class UserAdminServlet extends HttpServlet {
@EJB(mappedName = "testspring-ear-0.0.1-SNAPSHOT/UserDAOBean/local")
private UserDAO userDao;
WebApplicationContext context = null;
/**
* @param filterConfig
* @throws ServletException
*/
public void init(ServletConfig filterConfig) throws ServletException {
System.out.println("Inti calleddddddddddddddd");
super.init(filterConfig);
ServletContext servletContext = filterConfig.getServletContext();
context = WebApplicationContextUtils
.getWebApplicationContext(servletContext);
// set up an injected bean into application scope
// servletContext.setAttribute("mybean", context.getBean("aBean"));
}
/*
* (non-Javadoc)
*
* @see
* javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
* , javax.servlet.http.HttpServletResponse)
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println(((MathService) context.getBean("mathService")).add(
1, 2));
if (userDao == null) {
try {
Hashtable environment = new Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
environment.put(Context.URL_PKG_PREFIXES,
"org.jboss.naming:org.jnp.interfaces");
environment.put(Context.PROVIDER_URL, "jnp://localhost:1099"); // remote
// machine
// IP
Context context = new InitialContext(environment);
userDao = (UserDAO) context
.lookup("testspring-ear-0.0.1-SNAPSHOT/UserDAOBean/local");
// context.lookup("userDAOBean");
} catch (Exception e) {
e.printStackTrace();
}
}
doPost(req, resp);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List users = userDao.getUsers();
for (int i = 0; i < users.size(); i++) {
response.getWriter().append(
"UserName :" + users.get(i).getFirstName() + " "
+ users.get(i).getLastName()).append("
");
response.getWriter().append("id :" + users.get(i).getId()).append(
"
");
}
}
}
Now that i have covered all topics from frontend to db, now i’ll take you though how to configure webservices. I’ll show examples with both Apache CXF and JAX-WS
Webservices
Similar to spring MVC configuration through servlet , we have to configure both JAX-WS and Apache CXF through their own servlets. Below is servlet configuration to enable them
jaxws-servlet
com.sun.xml.ws.transport.http.servlet.WSSpringServlet
jaxws-servlet
/ws/*
CXFServlet
org.apache.cxf.transport.servlet.CXFServlet
1
CXFServlet
/webservice/*
Now that we have configured respective URL patterns now lets see configuration in Spring that is required to expose Beans as webservices
Webservice configuration for spring is configured in app-ws-config.xml
Below is how i have expose OrderService as webservice for apache CXF
package org.northalley.template.testspring.controller;
import javax.jws.WebService;
@WebService(endpointInterface = "org.northalley.template.testspring.controller.OrderProcess")
public class OrderProcessImpl implements OrderProcess {
public String processOrder(Order order) {
return order.validate();
}
}
Below is code of bean which is exposed by JAX-WS
/*
*
*/
package org.northalley.template.testspring.controller;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import org.northalley.template.testspring.services.WelcomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
/**
* @author ashwin kumar
*
*/
@WebService(name = "/hello")
@SOAPBinding(style = SOAPBinding.Style.RPC, use = SOAPBinding.Use.LITERAL)
public class WebserviceController {
@Autowired
@Qualifier("welcomeService")
private WelcomeService welcomeService;
/**
* Constructor
*/
public WebserviceController() {
}
/**
* @param searchCriteria
* @param formBinding
* @param request
* @return
*/
@WebMethod(operationName = "getMessage")
public String search() {
return welcomeService.hello("Ashwin").getMessage();
}
@WebMethod(operationName = "sayHello")
public String sayHelloToTheUser(@WebParam(name = "name") String userName) {
return "Testing: " + " " + userName;
}
}
Sample WSDL URL’s
http://localhost:8080/testspring-webapp/webservice/OrderProcess?wsdl
http://localhost:8080/testspring-webapp/ws?wsdl
And finally one more thing which i haven’t used in example. I have configured HSQLDB to used so that any demo’s need not have an external database but have Inbuilt DB
Here is how you do that
H2Console
org.h2.server.web.WebServlet
-webAllowOthers
true
2
H2Console
/admin/h2/*
If you use http://localhost:8080/appname/admin/h2 you will goto to HSQLDB Admin console
I think i have covered all concepts and code snippets to get you started.
Code has been checked in to
https://linkwithweb.googlecode.com/svn/trunk/SpringTutorials/testspring
Checkout
mvn clean install package
testspring-war ( Webapp code for ear file) (To be deployed on Jboss
testspring-ejb (Has ejb code)
testspring-ear – Combining both ejb and war to create ear
———————————————–
testspring-java (Java code used in tomcat)
testspring-webapp ( Web configuration for tomcat)
to test on tomcat follow the below steps
cd testspring-webapp
mvn tomcat:run and njoy playing with code
Njoy playing with code. Get back to me if you have any questions.