Click here to Skip to main content
12,547,501 members (53,976 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


5 bookmarked

Spring Integration Webapp( JPA/Hibernate | Webservices (JAX-WS|Apache CXF) | JQuery | EJB3 | Maven | Jboss | Annoatations)

, 22 Aug 2011 Apache
Rate this:
Please Sign up or sign in to vote.
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.

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

<property name=”” value=”update” />

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
<!--<span class="code-comment"> Configuration files for spring  --></span>

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

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns=""

	<!--<span class="code-comment"> DispatcherServlet Context: defines this servlet's request-processing infrastructure --></span>

	<!--<span class="code-comment"> Enables the Spring MVC @Controller programming model --></span>
	<annotation-driven />

	<!--<span class="code-comment"> Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --></span>
	<resources mapping="/resources/**" location="/resources/" />
	<resources mapping="/assets/**" location="/assets/" />
	<resources mapping="/CSS/**" location="/CSS/" />
	<resources mapping="/images/**" location="/images/" />
	<resources mapping="/JS/**" location="/JS/" />
	<resources mapping="/swfupload/**" location="/swfupload/" />

	<!--<span class="code-comment"> Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />

	<!--<span class="code-comment"> freemarker config --></span>
	<beans:bean id="freemarkerConfig"
		<beans:property name="templateLoaderPath" value="/WEB-INF/freemarker/" />
		<beans:property name="freemarkerVariables">
				<beans:entry key="xml_escape" value-ref="fmXmlEscape" />

	<beans:bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />

	<!--<span class="code-comment">

		View resolvers can also be configured with ResourceBundles or XML
		files. If you need different view resolving based on Locale, you have
		to use the resource bundle resolver.
	<beans:bean id="viewResolver"
		<beans:property name="cache" value="true" />
		<beans:property name="prefix" value="" />
		<beans:property name="suffix" value=".html" />

		<!--<span class="code-comment">
			if you want to use the Spring FreeMarker macros, set this property to
		<beans:property name="exposeSpringMacroHelpers" value="true" />



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/images etc files ).

Below is same Spring MVC controller which is configured through annotations


 * 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
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * 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;


 * @author ashwin kumar
public class GenericController {

	private WelcomeService welcomeService;

	 * Constructor
	public GenericController() {

	 * @param searchCriteria
	 * @param formBinding
	 * @param request
	 * @return
	@RequestMapping(value = "/test", method = RequestMethod.POST)
	public Response search(SearchCriteria searchCriteria,
			BindingResult formBinding, WebRequest request) {
		Response response = new Response();

		return response;

	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

<!--<span class="code-comment">
    Define the OXM marshaller which is used to convert the Objects <->

Here is sample Spring MVC Design

Read more about spring MVC in

The below one is one of best link which explains all different way you can use Rest Style URL in Spring 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

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns=""
	xmlns:xsi="" xmlns:beans=""

	<tx:annotation-driven transaction-manager="transactionManager" />

	<!--<span class="code-comment">
        Data source
	<beans:bean id="dataSource"
		<beans:property name="driverClassName">
		<beans:property name="url">
		<beans:property name="username">
		<beans:property name="password">

	<!--<span class="code-comment">
        Configuration for Hibernate/JPA
	<beans:bean id="entityManagerFactory"
		<beans:property name="persistenceUnitName" value="testspring-jpa" />
		<beans:property name="dataSource" ref="dataSource" />
		<beans:property name="jpaDialect">
			<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
		<beans:property name="jpaVendorAdapter">
				<beans:property name="showSql" value="false" />
				<beans:property name="generateDdl" value="true" />
				<beans:property name="databasePlatform"
					value="org.hibernate.dialect.HSQLDialect" />

	<beans:bean id="transactionManager"
		<beans:property name="entityManagerFactory" ref="entityManagerFactory" />
		<beans:property name="dataSource" ref="dataSource" />


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


 <persistence-unit name="testspring-jpa">


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




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;

public class WelcomeServiceImpl implements WelcomeService {

	private EntityManager entityManager;

	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 = :name");
			q.setParameter("name", name);
			welcome = (Welcome) q.getSingleResult();
		} catch (NoResultException e) {
			welcome = new Welcome();
			welcome.setMessage("Welcome " + name);
		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<User> getUsers() {
		List<User> users = this.em.createQuery(
				"select user from User user order by user.lastName")
		return users;

	// not using this method in this example app
	public User saveUser(User user) {
		log.debug("saveUser: " + user);
		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;

//if the table name matches your class name, you don't need the 'name' annotation
public class User extends BaseEntity {

    //we don't need the Column annotation here bc the column name and this field name are the same
    private Long id;

    private String firstName;

    private String lastName;

    private Date birthday;

    public Long getId() {
        return id;

    public void setId(Long 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.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.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");
		ServletContext servletContext = filterConfig.getServletContext();
		context = WebApplicationContextUtils
		// 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.PROVIDER_URL, "jnp://localhost:1099"); // remote
				// machine
				// IP

				Context context = new InitialContext(environment);
				userDao = (UserDAO) context
				// context.lookup("userDAOBean");
			} catch (Exception e) {

		doPost(req, resp);

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<User> users = userDao.getUsers();
		for (int i = 0; i < users.size(); i++) {
					"UserName :" + users.get(i).getFirstName() + " "
							+ users.get(i).getLastName()).append("<br/>");
			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



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

<!--<span class="code-comment">  jax-ws --></span>

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

<?xml version="1.0" encoding="UTF-8"?>

	<!--<span class="code-comment">

<beans:beans xmlns=""
	xmlns:jaxws="" xmlns:mvc=""
	xmlns:xsi="" xmlns:ws=""
	xmlns:wss="" xmlns:context=""
	xmlns:beans="" xmlns:util=""

	<!--<span class="code-comment"> Web service config for Apache CXF --></span>
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<jaxws:endpoint id="orderProcess"
		address="/OrderProcess" />

	<!--<span class="code-comment"> Web service config for JAX-WS --></span>

	<wss:binding url="/ws">
			<ws:service bean="#helloWs" />

	<beans:bean id="helloWs"


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.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 {

	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




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

<!--<span class="code-comment"> H2 Database Console for managing the app's database --></span>



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





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.










This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0


About the Author

Chief Technology Officer Northalley
United States United States
A Technology evangelist with no technical language barriers. A strong believer that Simple Sofware Is Perfect Software. A staunch proponent of software / documentation automation in all domain's. And finally a true diciple of Google Search.

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161018.1 | Last Updated 22 Aug 2011
Article Copyright 2011 by AshwinRayaprolu
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid