Friday, February 28, 2014

How To: Use Bootstrap 3 in your Java Web App

Last year I built a Java webapp for work using JSF, Primefaces, Spring, PrettyFaces, the regular kind of stuff that is generally used when developing an app to run on Tomcat Server. I chose not to use the Primefaces styling, wanting to create my own styles making use of the LESS files that are used to generate Bootstraps CSS. It's worth noting that Primefaces does have various themes including a Bootstrap theme but it isn't quite the same. You can remove the Primefaces styling by placing the following in your web.xml:

The app originally used Bootstrap 2.3.2 and much has changed since then. I've spent the whole of today going through the process of upgrading to Bootstrap 3.1.1. For anyone wanting to update from version 2 there is a convenient page on the Bootstrap website: Migrating to v3.x. Apart from the obvious changes to classnames were are a few steps required to get the new version working properly.

The best way to make use of Twitter Bootstrap in a JSF web application is to use bootstraps LESS files. These should be added the same way as any other resources. When you come to build your application the 'lesscss-maven-plugin' can compile all the LESS files into a minified css file, which can be used in your template using the following:

When upgrading to Bootstrap 3 I found that the plugin was no longer able to compile Bootstraps LESS files as the used features that were not supported in the version of LESS that was used by the plugin. Fortunately this can be resolved in the configuration block for the plugin by manually providing a path to a more recent LESS version.

Add the fonts to '/webapp/resources/fonts' then edit 'glyphicons.less', change the @font-face block to match the following:
@font-face {
font-family: 'Glyphicons Halflings';
src: url("#{resource['fonts/glyphicons-halflings-regular.eot']}");
src: url("#{resource['fonts/glyphicons-halflings-regular.eot']}?#iefix") format('embedded-opentype'),
url("#{resource['fonts/glyphicons-halflings-regular.woff']}") format('woff'),
url("#{resource['fonts/glyphicons-halflings-regular.ttf']}") format('truetype'),
url("#{resource['fonts/glyphicons-halflings-regular.svg']}#glyphicons-halflingsregular") format('svg');
Using the steps provided here you should be all set to start theming you app using Bootstrap. The great thing about using the LESS files rather than just adding the compiled CSS to the app is that you can use the same mixins that Bootstrap provides as well as easy access to the global values used in variables.less.

No comments: