From Request to Response – Part 1

facebooktwittergoogle_pluslinkedin

This article is part of the bigger series about my Software Engineering internship this summer. To read all the posts, simply visit the category archive.

Today I’d like to give you some insights 4seohunt.com/www/www.aleaiactaest.ch on a application architecture as a whole. So first let’s review the architecture once again. I already briefly presented it in a earlier article. It consists of the following technologies:

  • JPA / EclipseLink for the Persistence Layer
  • Spring Core and MVC for the Web and Service Layers, enhanced with some own components
  • Angular JS for the Web Views

A classic EJB application you say? Sure, but for the amount of things I learned in the last couple of weeks, I’d like to share some knowledge and give you an introduction into this architecture. To show you how this all works, I’ll follow some simple requests from the client back to the database and back until we get our response. I’ll not focus on details in each technology but want to provide some sort of overview and will the further dig into particular topics in the future.

It all starts as usual – the index file

A simple table with some data from the backend

A simple table with some data from the backend

Okay, my let’s assume our user visits our page under the following uri: ‘/employees’. This should provide our user with the list of all employees stored on the database. A simple table so to say. Just to show you the end result I attached a screenshot from the current state of my project to it. So the first thing that will be loaded is a simple index.html file on the server. It will mainly only contain a rough html skeleton consisting of a <html>, <head> and <body> tag. But this will be enough to boostrap our application with angular js. So it looks something like this:

<html ng-app="myModule">
  <head> ... </head>
  <body>
    <!-- e.g. render a head navigation here -->
    <ng-view>
      <!-- Angular JS loads the view in this part -->
    <ng-view>
    <!-- load the scripts here --> 
  </body>
</html>

index.html

The Angular Module

So when angular is initialized it will parse the content and compile it with it’s own html compiler. But it has to now what the content for the view should be, loaded in the ng-view tags. This is configured in the module, specified in the ng-app tag at the top. This module could look like this:

var module = angular.module('myModule', ['ngResource']);

module.config(function ($routeProvider) {
  $routeProvider.
    when('/employees/', {controller:EmployeesIndex, templateUrl:'/pages/employees.html'}).
    /* ... further routes ... */
    otherwise({redirectTo:'/'});
});

module.factory('Employee', function ($resource) {
  return $resource('/employee/:employeeId', {employeeId:'@id'}, {
    update:{method:'PUT'}
  })
});

mymodule.js

Okay, lets take a closer look at this module. In the first line we define the name of the module (‘myModule’) so that it can used to bootstrap our application like in the index.html file. It also defines all modules it depends on. This can be other modules of your own (e.g. I have a ‘component’ module where I declare all the new ui elements I’m using), or like in this case specific modules from the Angular JS libraries. Here we use ngResource which allows use a very elegant way to interact with our REST resources.

Then on the following lines we define our routes, like the one we’re needing now: ‘/employees/’. It states which controller is used and which template is needed.

In the third part we prepare some dependency injection for our Controllers. I’m quite excited about that, as it simplifies so much of your code. Here we’re defining our REST resource for the employees. This is a simple provider, stating that whenever we need something called an ‘Employee’ return the following resource. The resource has an URI with a parameter (the employeeId) and I usually also state an additional method on the resource to allow PUT-Requests.

The Angular Controller

So let’s follow the trail: Angular now has a Controller Method and a view and connects them to each other to further render the end result. The view is pretty straightforward: A simple html file with only that part of the view which will be needed for the actual data table. Not much to show there. Let’s take a look at the controller:

function EmployeesIndex($scope, Employee) {
    $scope.employees = Employee.query();
}

employees.js

Jep, that’s already it. As you can see, we already need the defined resource from before. Angular will call the factory method for the ‘Employee’ and return a $resource object. This $resource object has a method .query() which simply sends a GET Request to the specified URI and expects an array as result. It also states no parameter, as we want a list of all employees.

The Spring MVC web layer

Okay, now it’s getting interesting. Now the server gets a request and on the server side we have configures the Spring MVC to handle this request. I’ll not show you the whole configuration of the spring beans as it’s fairly well documented on the web. Just the heart piece here:

...
<context:component-scan base-package="org.application.web"/>

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean>
      <property name="objectMapper" ref="jacksonObjectMapper"/>
    </bean>
  </mvc:message-converters>
</mvc:annotation-driven>

mvc-dispatcher-servlet.xml

Together with the web.xml which definies the according servlets this sets up our web layer. Basically it states: We’re using an annotation driven approach and there you have to look for our controller classes. We’re registering a specific jackson object mapper for as a message converter. The last thing isn’t really necessary as loading jackson with maven is sufficient here. But for example I use a customized mapper where I can define some details like how dates are rendered.

Spring Controller

All we need now is a Controller class. Something like this:

@Controller
@RequestMapping(value = "/employee")
public class EmployeeController {
    private final EmployeeService employeeService;

    @Inject
    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public List<EmployeeData> listAll() {
        return employeeService.getAll();
    }

    /* Further controller methods */
}

EmployeeController.java

So with all these annotations we’re saying: Requests with ‘/employee’ go to this controller object. The object gets it’s service injected which will handle the requests. When the request is without any further URI specification and a GET-Request, then it goes to the method listAll(). The response of the request will be a list of DTOs (Data transfer objects). How this is rendered depends on the request (header content-type attribute) and on the registered message converters. In our case this will use the jackson mapper to satisify application/json requests with json responses.

Note that the object mapper would also map to request body objects, when the method parameters are annotated with @RequestBody. So you actually don’t have to worry in any way with the parsing and mapping of your request and response formats and the according data objects.

That’s it for tonight. I’ll post the second part in the next couple of days, showing you some further details on:

  • How the service maps it’s dtos with dozer
  • EclipseLink and enhanced DAOs (Data access objects)
  • Some special mapping and serializing problems

One thought on “From Request to Response – Part 1

  1. Pingback: Custom form validation in Angular JS | alea iacta est

Comments are closed.