Patrick Grimard's Java Blog

How to build a Spring Boot application using IntelliJ IDEA

Welcome back!  This tutorial will be a basic introduction to creating a Spring Boot application using IntelliJ IDEA.  No prior knowledge is expected, the main purpose of this post is to help anyone new to Spring get rolling quickly writing Spring applications with Spring Boot in IntelliJ.  For further reading, be sure to check out Spring’s Guide section on for other tutorials on writing Spring Boot applications.

Create your new project with IntelliJ

Open up IntelliJ and click on the Create New Project option.

Screen Shot 2014-08-14 at 7.28.53 PM

Read More

Bootiful Spring apps with Supervisor

Like many other developers, most of the apps I’ve developed ended up running in Tomcat.  This worked out fine for a while, but one of my biggest pain points was with deployment, or redeployment of an updated app.  For some reason, at some point or another, I would run into deployment issues.  These issues ranged from Tomcat not exploding my WAR file when auto deployment was enabled, or the app not wanting to start, or even OutOfMemory errors during deployment.  Often times, restarting Tomcat or even the server was the only solution.  If you have a very small set of apps and a very small set of users accessing those apps, that might seem fine, but as time goes on and you add more apps and more users, restarting Tomcat or the server is no longer feasible.

I had been looking into Spring Boot for a little while and finally decided it was time to migrate an app.  This was a simple app which had some @Scheduled and @Async tasks.  This wasn’t even an app that users would access, but rather it was a stand alone app that read data from a database, created CSV files and FTP’d them.  So it was a simple candidate.  I won’t go into details about migrating the app, I’ll just say in the end I had a much shorter POM.  I used the Spring Boot starter web, jetty, test and actuator dependencies.  I didn’t end up using the Spring Data JPA starter because I prefer EclipseLink to Hibernate.

Running your Spring Boot app in production

Now that I had a functional Spring Boot app (no pun intended), it was time to get it running in production.  I knew immediately that I couldn’t simply execute my JAR and be done with it.  What happens if the process crashes?  What happens if the server is rebooted?  I want my app to keep running.  So I Googled for some solutions and found this Github issue on Spring Boot which lead me to Supervisor.  Supervisor is a simple process control system.  Installation was as simple as easy_install supervisor on my linux server. The documentation on Supervisor’s website is very good, so I recommend you read it if you’re having any trouble.

Once I had Supervisor up and running, I modified the configuration file supervisord.conf which I put in /etc.  Mainly, I changed the last line to include external configuration files for any app I would want to run with Supervisor.

My app configuration file is located at supervisor/conf.d/myapp.conf, relative to the directory where supervisord.conf is located.

These files are simple key=value configuration files.  This configuration file tells Supervisor to run the command listed at the “command” key.  The “autostart” and “autorestart” keys ensure the app starts and restarts automatically.  The “startsecs” says that the app must run for at least 10 seconds to be considered a successful start, otherwise retry the number of times denoted by “startretries”.  The final keys setup logging output.

With that file saved, issuing supervisorctl reload from the command line will force Supervisor to read in that configuration file and know about my app.  It should attempt to start it up automatically.  If everything was successful, then issuing supervisorctl without any arguments, or supervisorctl status will list the apps running along with their status, PID and uptime.  A status of RUNNING means it’s running successfully.  While testing this out, I saw another status of BACKOFF because the value of my command key in the configuration file wasn’t correct.

And that’s pretty much it for getting a Spring Boot app running in production.

Final thoughts

At this point, if this app were a web application that users would access, I would setup a server to act as a reverse proxy to my apps.  I’ve had good experience setting up Nginx in this manner.  You can have multiple instances of your Spring Boot app running and Nginx can load balance between each instance.

I hope this post helps you out :)

Pagination with Spring Data and HATEOAS in an AngularJS app

Most of us have seen pagination used in one form or another for presenting a collection of data to a user that gives them the ability to page through the data.  This is most useful when you’re dealing with large datasets that you don’t want to display all at once on a single page. With Spring Data, a lot of the heavy lifting is done for you and presented in a nice simple interface.  Spring Data comes with the PagingAndSortingRepository interface with extra methods for pagination and also sorting.  If like me you’re using Spring Data JPA, the JpaRepository already extends the PagingAndSortingRepository, so you already have the added benefits.

Getting to know Spring Data’s pagination support

Here is a simple Widget repository with a custom finder that returns a paged result.

As you can see, it’s pretty simple.  Our finder accepts a Pageable argument and returns a Page of Widget entities.  To make this useful from a web application, Spring Data comes with some nice out of the box functionality, using the @EnableSpringDataWebSupport annotation.  Add this annotation to your configuration class and it will add some paging and sorting functionality to your web application that we’ll get into next. Now that we have our repository, we’ll create a controller.

Read More

jQuery Simple Forms

GitHub repo:

I just published a set of handy jQuery plugins for working with forms!

It includes the following:

  • Function to serialize a form to JSON.
    This is useful if you’re submitting a form via AJAX and need to serialize your form to JSON.  The form serialization will also look for data-default-value attributes on your named form elements and use that value if the input is left blank.  The default value is also verified to see if it’s numeric, in which case the resulting JSON property will be numeric.
  • Function to add new option to an HTML select.
    Adds a button next to your select that when clicked, replaces your select with a text input of the same name, ID and classes.
  • Enable/Disable buttons.
    Simple functions for enabling/disabling buttons.

Spring Security CSRF Protection in a Backbone single page app

Be advised this post has been revised since it’s original writing.  Rob Winch, Spring Security project lead suggested a simpler method of doing what I needed and indeed, it is simpler.

Happy New Year!!  What better way to kick off this new year than to write a new post?  Let’s get to it.  This post will not try to show you best practices for protecting against CSRF (cross-site request forgery).  Instead, I hope to start a discussion on what would be the best way to achieve CSRF protection in a Backbone app using the new Spring Security 3.2.0 release, so that I may better understand it myself.  The source code for this experiment is available at the bottom of this post.

What does Spring Security CSRF protection assume?

In version 3.2.0, CSRF is enabled by default when using Spring Security.  Since I’m building a Backbone app which will be accessed from a browser, I want the added protection.  While reading the documentation, I quickly realized that the way the implementation has been done, the CSRF token needed on your page is stored in a session attribute on the HttpSession.  On the backend, the CSRF token is created using a HttpSessionCsrfTokenRepository.

The token is created automatically when you request the page being protected.  This doesn’t pose any problems if you’re building your app with JSP for example.  If you’re using Spring MVC’s JSP tag libs, or something like Thymeleaf (which I loved using before discovering Backbone) then the CSRF token is available for you as a page attribute when the page is rendered on the server and can be inserted in a form for example or in a meta tag for later use in an AJAX request.  In a Backbone app however, where the  page is rendered primarily in the browser, you need another means to get that CSRF token when you first load the page because we don’t get access to page attributes like we do in JSP.

How about a servlet filter?

One thought I had to retrieve the CSRF token at page load was to create a servlet filter.  This allows me to retrieve the CSRF token from the request and add information about it as response headers.

Read More

Cross-Origin Resource Sharing (CORS) requests with Spring MVC

Welcome back!  :)  This will be a brief post to show you how to setup CORS in your Spring MVC application.  The objective here is to keep the code out of my @RequestMapping request handlers so that it can be easily used across the application.

The CORS Filter

The first thing we need is a CORS filter.  When you make an AJAX request from your domain to another domain, the first thing that will happen is an OPTIONS request will be made to the URI in question to determine what requirements are needed to complete this request.  This request is where we need to verify that the origin is actually allowed to make that request and send back a response to the browser permitting it to proceed.  We will retrieve the “Origin” header from the servlet request and verify that it’s one of the origins permitted to to make CORS requests to the application.  Assuming the origin is permitted, we’ll add a “Access-Control-Allow-Origin” header to the servlet response which will contain the value of the incoming “Origin” header.  Let’s extend Spring’s OncePerRequestFilter, verify the origin, then adjust the response headers.

Read More

Yeoman Backbone apps meet Tuckey’s UrlRewriteFilter!

A couple months ago, I started using Yeoman to rapidly scaffold out webapps with AngularJS.  I even wrote a quick blog post about Yeoman, as well as how to use the Yeoman Maven plugin when writing webapps in Spring and setting up the Jetty Maven plugin to use the scaffolded app during development.  Since then, I’ve begun using Backbone and Underscore and I’ve honed how I use Yeoman on a daily basis.

Today I don’t really use the Yeoman Maven plugin anymore during development.  Indeed it is a great plugin.  The main issue I had during development time was the time it took to complete a build because the Yeoman Maven plugin is doing a few long lasting IO tasks over the internet.  Combine with that the fact that I didn’t need to actually build my entire WAR every time I wanted to compile changes I made to my JavaScript source.  In fact, for the most part, the servlet part of my webapp didn’t require much changes at all since I was mainly exposing REST endpoints producing JSON data.  Now during development, I simply build my WAR once (assuming there are indeed no changes to make on the server side) and test my app using the Jetty Maven plugin as usual.

A few things have changed in my application structure in the past couple months.  When I started using Yeoman, I was creating a directory called “yo” outside of my usual src/main directory structure used by Maven.  At the time, it seemed like the right thing to do from what I was reading in blog posts and StackOverflow.  Over the course of development, this posed a few challenges that I spent some time trying to find solutions to, but nothing seemed all that elegant or straightforward.  So the first big change to my structure is now I run my Yeoman commands within my src/main/webapp directory which Maven does recognize by default.

Read More


Get every new post delivered to your Inbox.

Join 83 other followers