Spring MVC – Full java based config

Spring MCV is a very powerful and flexible framework for web application development.

It doesn’t just implement the MVC pattern, it allows you to develop Rest web services.

   

This post presents a web project sample with a full java configuration using Spring MVC 4 and Servlet 3 api. The source code is available in this link.

This project implements client side for the persistence sample presented in Spring-Data-JPA article

1 – Add project dependencies

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.0.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

2 – Spring MVC config class

import org.springframework.context.annotation.*;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.mycompany.myproject.web.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver jspViewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setPrefix("/WEB-INF/views/");
        bean.setSuffix(".jsp");
        return bean;
    }

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver getMultipartResolver() {
        return new CommonsMultipartResolver();
    }

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();
        resource.setBasename("classpath:messages");
        resource.setDefaultEncoding("UTF-8");
        return resource;
    }

}


3 – Webapp initializer

With servlet 3 API you can use a class to configure your web project instead of the classic web.xml file.
You have to check if your application server or your servlet container supports servlet 3 spec. For Tomcat you can have this information in this link:
tomcat.apache.org/whichversion

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

public class WebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(ServiceConfig.class, JPAConfig.class, SecurityConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
        dispatcherServlet.register(MvcConfig.class);
            
        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
        
    }

 }


4 – Model class.

public class User {
 
    private Long id;

    private String firstName;

    private String familyName;

    private String email;

    // add extra attributes
    	
    // add getters and setters
	
}

5 – Add view as jsp page
We create a usersView.jsp page with code source bellow to display users list.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<div class="col-sm-offset-1 col-sm-10">

    <legend>
        <spring:message code="table.user.title" />
    </legend>

    <div>
        <table id="dataTable" class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th><spring:message code="table.user.id" /></th>
                    <th><spring:message code="table.user.firstName" /></th>
                    <th><spring:message code="table.user.falilyName" /></th>
                    <th><spring:message code="table.user.email" /></th>
                </tr>
            <thead>
            <tbody>
                <c:forEach var="u" items="${usersModel}">
                    <tr>
                        <td>${u.id}</td>
                        <td>${u.firstName}</td>
                        <td>${u.familyName}</td>
                        <td>${u.email}</td>
                    <tr>
                </c:forEach>
            </tbody>
        </table>
    </div>
</div>

6 – Develop your controller

The @Controller annotation indicates that a particular class serves the role of a controller.
The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
 
    /**
    * Request mapping for user
    */
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ModelAndView getUsersView() {
        ModelAndView mv= new ModelAndView("usersView");
        mv.addObject("usersModel", userService.findAll());
        return mv;
    }
    
    /**
    * Rest web service
    */
    @RequestMapping(value = "/usersList", method = RequestMethod.GET)
    public @ResponseBody List<UserDto> getUsersRest() {
        return userService.findAll();
    }
}

7 – Test web project
When building your project you may have maven error telling you that the web.xml file is missing.
You can fix it by configuring the maven war plugin as presented bellow.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

  • Test display users
    http://localhost:8080/myproject/users
    spring_mvc_test

  • Test rest web service
    http://localhost:8080/myproject/usersList
    You will get json reponse.

    [
        {
            "id": 1,
            "firstName": "adminName",
            "familyName": "adminFamily",
            "email": "admin@maycompany.com",
            "phone": "0033 1 23 45 67 89",
            "language": "en",
            "login": "admin",
            "password": "admin",
            "burthDate": null,
            "authorities": [
                {"id": 3, "name": "user"},
                {"id": 2, "name": "technical user"},
                {"id": 1, "name": "admin"}
            ],
            "enabled": true,
            "pictureId": null,
            "authoritiesAsString": "user, technical user, admin"
        },
        ..........
    ]
    

Here’s the how to video created by Webucator.com. Check out their Spring training classes.

Advertisements

Web Services with Apache CXF

CXF framework is widely used to create web services. It supports a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI.

CXF has some tools like wsdl2java witch generate web service code from WSDL. This tool is very useful but it integrates some code that usually we don’t control all its details.

Photo credit: Brian A Jackson

I wrote this article to presents a concise way to create a web service with CXF and Spring. This solution has the advantage to avoid generating extra code to integrate in your project.

1 – CXF dependency

If you are using Maven you can add dependency by adding the XML code below.

<dependency>
	<groupId>org.apache.cxf</groupId>
	<artifactId>cxf-rt-frontend-jaxws</artifactId>
	<version>2.1.3</version>
</dependency>
<dependency>
	<groupId>org.apache.cxf</groupId>
	<artifactId>cxf-rt-transports-http</artifactId>
	<version>2.1.3</version>
</dependency>

2 – Web service implementation

First, add a web service interface. The code source bellow is a simple of web service that allows adding a customer to an existent JSF web application.

import javax.jws.WebService;
import com.mycompany.entity.Customer;

@WebService
public interface CustomerService {

	String SaveCustomer(Customer customer);

}


Next, write your web service implementation.

import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mycompany.dao.ICustomerDao;
import com.mycompany.entity.Customer;

@Component("customerService")
@WebService(endpointInterface = "com.mycompany.service.CustomerService")
public class CustomerServiceImpl implements CustomerService {
	
@Autowired
private ICustomerDao customerDao;

	public String SaveCustomer(Customer customer) {
		customer.setCustomerId(null);
		customer.setCustomerOrders(null);
		customerDao.save(customer);
		return "saved";
	}	
}


Finally, add spring configuration to configure the web service end point and client.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

	<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="customerServiceEndPoint" implementor="#customerService"
		address="/CustomerService" />

	<jaxws:client id="customerServiceClient" serviceClass="com.mycompany.service.CustomerService"
		address="http://localhost:8080/myApp_JSF_CXF/ws/CustomerService" />
</beans>

3 – Web service test

Test with SoapUi
You can use SoapUi to test your web service. In this case you don’t need to implemente a service client.

SoapUi needs a wsdl file. You can provide this URL http://localhost:8080/myApp_JSF_CXF/ws/CustomerService?wsdl.

Test with JUnit

Testing a web service with junit it’s more likely to be an integration test than a unit test because it depends on other resources. You will need to start your application server and deploy your web service before running your test.

The code source bellow uses the web service client to test the web service developed in this article.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/application-context-test.xml"})
public class CustomerServiceTest {
	
	@Autowired
	@Qualifier("customerServiceClient")
	private CustomerService customerServiceClient;

	@Test
	public void SaveCustomerClientTest() {
		Customer customer = new Customer(25, "nameTest","adresse", "city", "state", "123", "0606060606", null);
		assertEquals("saved", customerServiceClient.SaveCustomer(customer));	
	}
}

Spring Integration

Today’s business applications rarely live in isolation. That’s why we have often in applications development to implement a communication module to make the new application exchanging data with the existent information system. To implement those data flow we can use many technologies (JMS, SOA, Apache commons IO …). Managing all those components in a project can be tricky and not easily maintainable.

   

Photo credit: Michelangelo

Spring Integration provides an extension of the Spring programming model to support the well-known Enterprise Integration Patterns. It enables lightweight messaging within Spring-based applications and supports integration with external systems via declarative adapters.

The first part of this article presents some basic background to start using Spring Integration. The second part deals with a project sample.

1- Spring Integration Basics

Spring Integration adds essentially three components to the core Spring Framework: messages, message channels, and endpoints.

1.2-Spring Integration components

In this part we will present some basic components used in this article sample.

Message: is a data structure that will have payload and the header. The payload can be a file, String, JMS message … The header is a key-value map that contains some properties that will be used by the framework or user values.

Channel: it represents the “pipe” of a pipes-and-filters architecture. Producers send Messages to a channel, and consumers receive Messages from a channel.

Inbound Channel: it does some mapping between the Message and whatever object or resource is received-from the other system (File, HTTP Request, JMS Message, etc).

Outbound Channel: it does the same thing like the inbound Channel but in the other side. It map message to send to other system.

Service Activator: it’s a generic endpoint for connecting a service instance to the messaging system. The input Message Channel must be configured, and if the service method to be invoked is capable of returning a value, an output Message Channel may also be provided.

Transformer: is used to create a Message-transforming endpoint. It requires a “ref”. The “ref” may either point to an Object that contains the @Transformer annotation on a single method or it may be combined with an explicit method name value provided via the “method” attribute.[2]

Splitter: is a component whose role is to partition a message in several parts, and send the resulting messages to be processed independently.

To get more details about those components and to discover others components you can read the Spring integration reference manual in this link : http://static.springsource.org/spring-integration/reference/htmlsingle/

1.2- Spring integration component specification

To specify components, you can use the basic xml language or annotations.

This source code presents the transformer declaration by sing the XML language.

<integration:transformer input-channel="channel1" output-channel="channel2">
	<bean class="com.mycompany.integration.FileTransformer" />
</integration:transformer>


The same thing could be done by using Spring integration annotation.
First add to your spring application context the declaration of the package where your annotated classes are defined.

	<integration:annotation-config/>
	<context:component-scan base-package="com.mycompany.integration"/>

Next you add the annotation to your transformer class.

@Component
public class FileTransformer {	
	
	@Transformer(inputChannel="channel1", outputChannel="channel2")
	public NewMessageFormat transform(OldMessageFormat omf) throws IOException{
		//Your transformation implementation here
		return newMessageFormat;
	}
}

I recommend the xml specification because it could be used by STS to display integration graph. This graphic representation is helpful for reading and verifying the integration flow.

1.3- Create Spring integration project

The simplest way to create a Spring Integration project is to create a basic Spring project and to add Spring Integration dependencies to the pom file.

<dependency>
	<groupId>org.springframework.integration</groupId>
	<artifactId>spring-integration-core</artifactId>
	<version>${spring.integration.version}</version>
</dependency>

<dependency>
	<groupId>org.springframework.integration</groupId>
	<artifactId>spring-integration-file</artifactId>
	<version>${spring.integration.version}</version>
</dependency>

<dependency>
	<groupId>org.springframework.integration</groupId>
	<artifactId>spring-integration-jdbc</artifactId>
	<version>${spring.integration.version}</version>
</dependency>

1.4- Spring Tools Suite (STS)

You can develop your spring integration application with your favorite IDE without any extra feature. But I think it is too much easier if it will be done with STS. You can download STS from this link http://www.springsource.com/developer/sts or to install the STS plugin for eclipse form this link http://marketplace.eclipse.org/content/springsource-tool-suite.

2- Spring integration sample

In this sample, we suggest to implement data integration between two systems. The first one produces data into flat file and the second system receives a data into a database.

You can import the project sample from google code SVN link: http://project4example4.googlecode.com/svn/trunk/

The application needs to detect the new file in a folder, log the name of the detected file, read text file and integrate its content into the database.

Bellow we present the source formatted flat text file content and the destination persistent classe.

id tax name adresse city state zip phone
5 2 name5 adresse5 Paris Paris 75001 0606060606
6 2 name6 adresse6 Paris Paris 75001 0606060606
7 2 name7 adresse7 Paris Paris 75001 0606060606
8 2 name8 adresse8 Paris Paris 75001 0606060606
9 2 name9 adresse9 Paris Paris 75001 0606060606
Source file format Persistent class

The picture bellow presents Spring integration graph used to implement the solution.

The file inbound channel inspect every 5 second the input folder. If a new file is present a message with a payload of type file will be created and sent to the service activator.
The service activator in this sample will just log the file name and deliver the message to the channel1.
The Transformer gets the Message from channel1, parse it, create a list of Customers and send the new message content to channel2.
The splitter gets the message, read the payload content and split the message to massages with a payload of type Customer.
The JDBC outbound channel gets the payload and uses payload attribute to execute the query.

The code source bellow presents the xml code of the spring integration graph. You can edit your Spring integration flow with both modes graphic and XML code mode. If you change XML code, the graph will be updated and if you use the graphic mode the changes done to the graph will affect the source code.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:integration="http://www.springframework.org/schema/integration"
  xmlns:file="http://www.springframework.org/schema/integration/file"
  xmlns:jdbc="http://www.springframework.org/schema/integration/jdbc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integration
http://www.springframework.org/schema/integration/spring-integration-2.0.xsd
http://www.springframework.org/schema/integration/file
http://www.springframework.org/schema/integration/file/spring-integration-file.xsd
http://www.springframework.org/schema/integration/jdbc
http://www.springframework.org/schema/integration/jdbc/spring-integration-jdbc.xsd">

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" />

	<file:inbound-channel-adapter id="filesIn"
		directory="${customer.file.input.path}">
		<integration:poller id="poller" fixed-delay="5000"/>
	</file:inbound-channel-adapter>

	<integration:service-activator	input-channel="filesIn" ref="handler" output-channel="channel1" />

	<bean id="handler" class="com.mycompany.integration.Handler" />
	
	<integration:channel id="channel1" />
	
	<integration:transformer input-channel="channel1" output-channel="channel2">
		<bean class="com.mycompany.integration.FileTransformer" />
	</integration:transformer>

	
	<integration:channel id="channel2" />

	<integration:splitter expression="payload" input-channel="channel2"  output-channel="dbChannel"/>	
	
	<integration:channel id="dbChannel" />

	<jdbc:outbound-channel-adapter
		query="insert into customer (customer_id, tax_id, name, adresse, city, state, zip, phone) values
		(:payload.customerId, :payload.taxId, :payload.name, :payload.adresse, :payload.city, :payload.state, :payload.city, :payload.phone)"
		channel="dbChannel" data-source="dataSource" />

</beans>

To test the application, you can run the jUnit test “testIntegrateCustomer”.

@Test
	public void testIntegrateCustomer() throws Exception {
		
		Collection<Customer> listCustomers = iCustomerDao.getAll();
		Assert.assertEquals(3, listCustomers.size());
		logger.info("customers number : {}", listCustomers.size());
		
		logger.info("wait .... ");
		Thread.sleep(2000);
		
		URL customerFileUrl = this.getClass().getResource("/input/customer.txt");
		File customerFile = new File(customerFileUrl.toURI());
		Assert.assertTrue(customerFile.exists());
		
		
		FileUtils.copyFileToDirectory(customerFile, new File(inputDirectoryPath));
		logger.info("test file {} copied to {}", customerFile.getName(), inputDirectoryPath);
		
		Thread.sleep(4000);
		
		
		listCustomers = iCustomerDao.getAll();
		logger.info("new customers number : {}", listCustomers.size());
		Assert.assertEquals(8, listCustomers.size());
		
	}


Spring Integration is a smart solution for application data integration. It provides support for the standard patterns typically used in enterprise integration. Spring Integration adds lightweight messaging and support for integrating with external systems and services using an adapter framework. Adapters enable a higher-level abstraction for communication with external systems and for Spring’s support for data and remote access as well as scheduling.

Reference

[1] http://www.eaipatterns.com/
[2] http://static.springsource.org/spring-integration/reference/htmlsingle/
[3] Dr. Mark Lui, Mario Gray, Andy H. Chan, and Josh Long, Pro. Spring Integration. Apress.