Top Tabs

Monday, December 10, 2012

In this tutorial, we will create an application that can post messages and retrieve profile information from Facebook and Twitter. We will use Spring Social to implement these features. To secure our application we will use Spring Security, and to manage our views, we will use Thymeleaf.

Review

In the previous section, we have discussed the functional requirements of our application. In this section we will study how to generate OAuth keys for Facebook and Twitter. These are required so that Spring Social can communicate with these social media sites.

Review

In the previous section, we have shown the steps on how to generate and retrieve the OAuth secret keys from Facebook and Twitter. In this section we will setup the Spring Social configuration settings through JavaConfig.

We have declared a ConnectionFactoryLocator which allows us to register connections to Facebook and Twitter. Notice how we passed the OAuth secret IDs and secret keys to the locator

We've declared a TextEncryptor for encrypting strings. This is required by Spring Social's JdbcUsersConnectionRepository

JdbcUsersConnectionRepository is used for persisting connections to a database through JDBC

ConnectionRepository allows a specific user to save and retrieve connections. We need to use this in conjunction with Spring Security because it provides us ready-made authenticated users. Notice how we assigned the current authenticated user

ConnectController is a controller for managing the connection flow to social media sites

HiddenHttpMethodFilter is required by Spring Social so that users can disconnect from social media sites. The filter needs to be declared in the web.xml or ApplicationInitializer

Note: If you need an in-depth explanation of each classes, please see the official Spring Social docs

Next

In the next section, we will focus on Spring Security-related configuration. Click here to proceed.

Spring Security

What is Spring Security?

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Spring Security is one of the most mature and widely used Spring projects. Founded in 2003 and actively maintained by SpringSource since, today it is used to secure numerous demanding environments including government agencies, military applications and central banks. It is released under an Apache 2.0 license so you can confidently use it in your projects.

First, we declare a DelegatingFilterProxy bean using JavaConfig. This allows Spring Security to intercept requests to our application and verify if the required authentication and authorization are met. This bean needs to be registered in the web.xml (or ApplicationInitializer) as a filter (see next section).

Second, we declare the usual XML-based configuration. This allows us to define the intercept-url patterns. Why are we not using JavaConfig here? Because the XML-based configuration is simpler, less-verbose, and easier:

JavaConfig

As stated in the introduction, we will be using JavaConfig-based configuration instead of the usual XML config. However, I don't want to alienate our readers who are used to XML. As a result, I've decided to provide both implementations. However, our focus here is still on JavaConfig.

Note: With JavaConfig, we can now omit the ubiquitous web.xml. But in order to that, we need to run a Servlet 3.0 web container. For this tutorial, I have tested the application with Tomcat 7.0.30 (Maven plugin), 7.0.33 (standalone Tomcat), and Jetty 8.1.5.v20120716 (Maven plugin).

ApplicationInitializer.javaThe ApplicationInitializer.java is the equivalent of web.xml. Here's where we declare the DispatcherServlet and also we've registered two filters: one for Spring Security and another for Spring Social.

Here's the equivalent XML configuration:

ApplicationContext.javaThe ApplicationContext.java contains our main configuration. It's responsible for loading other configurations, either as JavaConfig or XML config.

@Import({DataConfig.class, ThymeleafConfig.class, SocialConfig.class, SecurityConfig.class})
- This allows us to import JavaConfig-based config. Notice we have imported four configuration classes

@ImportResource("classpath:trace-context.xml")
- This allows us to import XML-based config files. (As a side note why can't we just declare this as a JavaConfig? It turns out there's no direct translation for the trace-context.xml, so we'll have to import it as XML).

This is equivalent in XML as:

@PropertySource("classpath:spring.properties")
- This allows us to import property files

These allows to redirect virtual path requests to specific templates within our application. We need to do this because the ConnectController from Spring Social has its own built-in controller path requests. And we need to redirect the resulting views that matches our template path.

For example, when connecting to Facebook, ConnectController will use the connect/facebookConnect path and you are required to provide a view. Using the addTemplateAlias() method, we can provide a custom view, in this case, the view points to the directory in the WEB-INF/templates/facebook/connect.

Also, we've disabled the caching feature so that we can easily update and test our html pages.

Here's the equivalent XML configuration:

SecurityConfig.javaThe SecurityConfig.java contains a single bean DelegatingFilterProxy. This is required for Spring Security.

spring.propertiesspring.properties contains the property settings of our application. You need to declare your Facebook and Twitter OAuth settings here. Here's also where you declare your database.

messages_en.propertiesThis is for internationalization of messages. The default language is English. If you need to provide custom language, create a new properties file and replace the values according to the language you've chosen. Please see the Spring documentation for more info on internationalization.

Next

In the next section, we will discuss the Domain, Service, Controller, and View layers. Click here to proceed.

View with Thymeleaf

The goal of this section is not to teach you everything about Thymeleaf but to point out the important sections. If you need a full Thymeleaf documentation, please see the official docs.

What is Thymeleaf?

Thymeleaf is a Java library. It is an XML / XHTML / HTML5 template engine (extensible to other formats) that can work both in web and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of web applications, but it can process any XML file even in offline environments.

It provides an optional module for integration with Spring MVC, so that you can use it as a complete substitute of JSP in your applications made with this technology, even with HTML5.

The main goal of Thymeleaf is to provide an elegant and well-formed way of creating templates. Its Standard and SpringStandard dialects allow you to create powerful natural templates, that can be correctly displayed by browsers and therefore work also as static prototypes. You can also extend Thymeleaf by developing your own dialects.

Declares a resource relative to the context of the app. When testing the html mockup, the th:href attribute is ignored by the browser. When running the app, Thymeleaf's preprocessor will ignore the value of the href attribute and use the value in the th:ref attribute.

th:text attribute

<title th:text="#{'profile.title.' + ${source}}">Title</title>

Declares the usual title element. When testing the html mockup, the th:text attribute is ignored by the browser. When running the app, Thymeleaf's preprocessor will ignore the value of the title and use the value in the th:text attribute.

This is a common attribute. So pay attention to this one.

th:include attribute

<div th:include="include :: menu"></div>

Includes an html fragment. The fragment is declared in the include.html

A conditional expression. This states "if the profileInfo.email attribute is empty, print out 'no email listed', but if it's not empty, then print out the value.

Note: To see the remaining html pages, please visit the Github repository. I've omitted them here because most of the Thymeleaf tags we've discussed here are also the same ones we've used on those pages.

login.html
This is the login page. We've shown it here because this is used by Spring Security for rendering the login page.

Layers

Domain

Our domain layer consists of two simple classes: User.java and Role.java. By annotating these classes with @Entity we're declaring these classes as JPA entities and consequently will be persisted to a database.

The User class contains the following properties: first name, last name, username, role, and password. For the Role class, we only have two values: an admin and a regular user.

Although this is not part of the domain layer, we've included the UserDto here. This DTO is used for transferring user information to the view layer.

Controller

We have five controllers:

AccessController is responsible for managing login and signup requests

FacebookController is responsible for handling Facebook requests

TwitterController is responsible for handling Twitter requests

UserController is responsible for handling User CRUD operations

MediatorController simply handles call to the root page

AccessController.java

FacebookController.java

MediatorController.java

TwitterController.java

UserController.java

Repository

We have a simple repository. There's nothing much to explain here.

UserRepository.java

Service

We have two services:

UserService is used for handling user-related CRUD operations

RepositoryBasedUserDetailsService is used for retrieving user details for authentication purposes

UserService.java

RepositoryBasedUserDetailsService.java

Next

In the next section, we will study how to build and run our application. We will use Maven, Tomcat, and Jetty to run the app. We'll also study how to import the project in Eclipse. Click here to proceed.

Review

In the previous section, we have discussed the Domain, Repository, Service, Controller layers. In this section, we will build and run our sample application. We will verify if our application is able to communicate with Facebook and Twitter. We will also show how to import the project in Eclipse.

Sunday, December 2, 2012

In this tutorial, we will create a CRUD application based on Spring MVC 3.x and Spring Data JPA. We will utilize JavaConfig instead of XML to configure our application. For the view layer, we will use Thymeleaf as our template engine instead of JSP to process our html pages.

Creating the View

In designing our application we'll start with the view layer because we can. Thanks to Thymeleaf creating HTML mockups is easy. Thymeleaf allows us to use these mockups as our HTML templates without any aesthetic changes. In addition, it passes W3C Markup Validation Service with flying colors.

What is Thymeleaf?

Thymeleaf is a Java library. It is an XML / XHTML / HTML5 template engine (extensible to other formats) that can work both in web and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of web applications, but it can process any XML file even in offline environments.

It provides an optional module for integration with Spring MVC, so that you can use it as a complete substitute of JSP in your applications made with this technology, even with HTML5.

The main goal of Thymeleaf is to provide an elegant and well-formed way of creating templates. Its Standard and SpringStandard dialects allow you to create powerful natural templates, that can be correctly displayed by browsers and therefore work also as static prototypes. You can also extend Thymeleaf by developing your own dialects.

Before we proceed, let me provide you a short description of the specific Thymeleaf attributes we'll be using:

The important attributes

The # means to resolve the attribute from the messages bundle

The $ means to resolve the attribute from the model

The # and $ can be combined together so that messages can be dynamically generated from the model and internationalized from the messages bundle

th:fragment="header"

This allows us to include template fragments from other templates. For example, we can reuse them in footers, headers, and menus. For this tutorial, we won't be reusing the header, but I've added it anyway for future tutorials.

th:each="u : ${users}

This allows us to loop a list of records. This is equivalent to Java's for-loop construct.

th:text="${u.id}"

This allows to dynamically set the label of an element.

th:href="@{/users/delete(id=${u.id})}">

This allows us to define a dynamic URL.

th:field="*{id}"

This allows us to define the field where an input's field will be attached to.

th:remove="all"

This allows us to setup mockup data. Thymeleaf will automatically remove any element contained within this attribute.

Notice the th:text attributes. Some of them refer to a dot notation object. Where does Thymeleaf retrieve this information?

The information is retrieved from the messages_en.properties resource bundle:

We've declared that in the ApplicationContext.java configuration (see next section):

The Data transfer object (DTO)

In order for our html page to display data from the Controller, we need to pass a Model attribute. The model attribute is represented by the UserDto.

The fields we declared on the users.html form is based from the fields of the UserDto:

Notice the form has a form-backing object declared named commanduser. Using Thymeleaf's attribute th:object, we're able to declare this form-backing object.

This object passed from the UserController.

Next

In the next section, we will focus on the configuration layer. We'll study how to declare a JavaConfig-based configuration. We'll also provide an XML-based configuration for comparison purposes. Click here to proceed.

Review

In the previous section, we focused on the view layer and created an HTML mockup template. In this section, we will focus on configuration and declare them using JavaConfig. We will also provide an XML-based config.

JavaConfig

As stated in the introduction, we will be using JavaConfig-based configuration instead of the usual XML config. However, I don't want to alienate our readers who are used to XML. As a result, I've decided to provide both implementations. However, our focus here is still on JavaConfig.

Note: With JavaConfig, we can now omit the ubiquitous web.xml. But in order to that, we need to run a Servlet 3.0 web container. For this tutorial, I have tested the application with Tomcat 7.0.30 (Maven plugin), 7.0.33 (standalone Tomcat), and Jetty 8.1.5.v20120716 (Maven plugin).

ApplicationContext.java

The ApplicationContext.java contains our main configuration. It's responsible for loading other configurations, either as JavaConfig or XML config.

@Import({SpringDataConfig.class, ThymeleafConfig.class})
- This allows us to import JavaConfig-based config. Notice we are importing two external configuration classes: SpringDataConfig and ThymeleafConfig

@ImportResource("classpath:trace-context.xml")
- This allows us to import XML-based config files. (As a side note why can't we just declare this as a JavaConfig? It turns out there's no direct translation for the trace-context.xml, so we'll have to import it as XML).

This is equivalent in XML as:

@PropertySource("classpath:spring.properties")
- This allows us to import property files

Review

In the previous section, we declared our configuration using JavaConfig and compared it side-by-side with an XML-based configuration. In this section, we will discuss the remaining layers of our application.

Layers

Here we'll discuss the Domain, Repository, Service and Controller layers.

Domain

Our domain layer consists of two simple classes: User.java and Role.java. If you'd been following my previous tutorials, you will notice that these are the same domain classes we'd been using before. Both classes had been annotated with @Entity which means these are JPA entities and will be persisted to a database.

These classes represent a user with the following properties: first name, last name, username, role, and password (we're not actively using the password field).

For role, we only have two values: an admin or a regular user.

User.java

Role.java

Controller

Our controller is a standard controller providing CRUD requests. The most important lines here are the following:

commanduser - the form backing object or the command object of the form

usertype - an attribute to determine if the request is a new user or existing user

UserController.java

Repository

We have created two repositories: UserRepository and RoleRepository(not shown). We will be using UserRepository as our primary data access object. Notice we have declared a custom method findByUsername but beyond that, this repository is pretty much standard. UserRepository.java

Service

Our service layer basically delegates to the repository. It provides an extra logic to filter out duplicate usernames. UserService.java

Next

In the next section, we will study how to build and run our application. We will be using Maven, Tomcat, and Jetty to run the app. We'll also study how to import the project in Eclipse. Click here to proceed.

Review

In the previous section, we have discussed the Domain, Repository, Service, and Controller classes. In this section, we will build and run our app. We will also study how to import the project in Eclipse.

You may have to enable "show hidden files" in your file explorer to view them.

Run Eclipse and import the application as Maven project

Validate with W3C Markup Validation Service

One of the promises of Thymeleaf is it produces valid HTML pages. Let's test that out using W3C validation service.

Run the application

Open a browser

Visit the following URL:

http://localhost:8080/spring-thymeleaf-tutorial/users

View the HTML source (right-click or go to menu)

Copy the HTML source

Open W3C Markup Validation Service at http://validator.w3.org/#validate_by_input

Paste the HTML source and wait for the validation result

You should see a similar output:

Conclusion

We've have completed our Spring MVC application with Thymeleaf as our template engine . We've studied how to convert our HTML mockup into a Thymeleaf template that validates with W3C validator service. We've also discussed how to create a JavaConfig-based application. As a bonus, we've also provided an XML-based application.

I hope you've enjoyed this tutorial. Don't forget to check my other tutorials at the Tutorials section.