HTML 5 Offline Web Application with Spring Boot

30 11 2014

Think of users using your web application from mobile phones when their internet connection breaks down. Native mobile app would still work and cache all user actions, synchronizing them afterwards. HTML5 web apps can also work offline.

Basically it is done by listing the resource files (html, js, images) that browser should cache immadietly and use the cached version when user redirects to it. If internet connection is working, the browser will return the online server version, else, if user is offline the cached version will be used.

Resources to cache can be defined in html headers or in .manifest file. These two locations are interpreted by all modern browsers.

1. Download the code base

This tutorial is based on the source code from SpringBoot MVC Hello World tutorial. All instructions are performed on this code.

2. Create offline.manifest file

In this file you can select the files and resources that will be cached by the browser and used if user requests to connect with server while being disconnected from the Internet. I will create new html file: offline.html and redirect to it if user is offline. My offline.manifest looks as follows:

CACHE MANIFEST
#v1

CACHE:
offline.html

NETWORK:
*

FALLBACK:
/ /offline.html

And is located under the /src/main/resources/static/offline.manifest.

3. Manifest file explained

The manifest file must begin with CACHE MANIFEST. The CACHE: section lists the files that we need for offline use. The NETWORK: section lists any resources that should not be cached. The FALLBACK: section uses the / character to define a URL pattern. It basically asks “is this page in the cache?” If it finds the page there, it displays it. If not, it shows the user the file specified – offline.html.

4. Create the offline.html page

This page will be displayed when user requests any page while being offline. This is static page – not the Spring template, so i simply put it in the /src/main/resources/static folder, next to the offfline.manifest file. The offline.html page content is basic one:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:th="http://www.thymeleaf.org" >
    <head>
        <title>Offline Web Application</title>
    </head>
    <body>
        <h1>You are offline</h1>
    </body>
</html>

5. Request to cache resources

To make use of offline.manifest file I point it in my hello.html and greeting.html page head:

<html xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:th="http://www.thymeleaf.org" 
  manifest="offline.manifest">

This way the browser will download the manifest and cache specified resources. Moreover it will add the hello.html and greeting.html to the cache as well

6. Test it

Run spring boot app, and open the url in the browser. When you are on hello page, the browser will cache files for offline use. In Chrome console this is indicated as:

hello:1 Creating Application Cache with manifest http://localhost:8080/offline.manifest
hello:1 Application Cache Checking event
hello:1 Application Cache Downloading event
hello:1 Application Cache Progress event (0 of 1) http://localhost:8080/offline.html
hello:1 Application Cache Progress event (1 of 1) 
hello:1 Application Cache Cached event

Now stop the Spring Boot app and click the url on th page. Since the server is offline, you will be redirected to cached offline.html page (or the greeting.html if it was previously cached). If you try tu go to any other url, for example: http://localhost:8080/someInvalidUrl – then the offline html page will be displayed.

Note: best to be tested in private / incognito browser mode to prevent unwanted cache.

Get the source Code

Full source code for this tutorial you can get at my GitHub under the SpringBootOfflineWebApp tag: https://github.com/yacekmm/looksok/tree/SpringBootOfflineWebApp.

Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Spring Boot: SSL/HTTPS for embedded Tomcat

22 11 2014

If your Spring Boot app is running on embedded Tomcat, you need to use the TomcatConnectionCustomizer class to set up the HTTPS in Tomcat.

Get the source code

Source Code for this tutorial is available on my github under the SpringBootHttps tag: https://github.com/yacekmm/looksok/tree/SpringBootHttps

1. Prepare keystore and certificate

First you need to have your certificate. If you already have it, go to point 2., else, follow the step 1 and 2 from this tutorial: https://looksok.wordpress.com/2014/11/16/configure-sslhttps-on-tomcat-with-self-signed-certificate/

2. Put your keystore in defined location

You need to locate your keystore file in path on your machine. On my machine this is:

D:\keystore\server.p12

This path I will use in my app configuration.

3. Customize Tomcat Connection

Create class implementing the TomcatConnectorCustomizer, and override its customize(Connection) method. As you can see, in customize() I set exactly the same properties as in stantalone Tomcat xml configuration (see this post). Note that in class constructor I convert the alias string to lowercase – in keystore only these are allowed.

public class MyTomcatConnectionCustomizer implements TomcatConnectorCustomizer {

  private String absoluteKeystoreFile;
  private String keystorePassword;
  private String keystoreType;
  private String keystoreAlias;

  public MyTomcatConnectionCustomizer(String absoluteKeystoreFile,
      String keystorePassword, String keystoreType, String keystoreAlias) {
    this.absoluteKeystoreFile = absoluteKeystoreFile;
    this.keystorePassword = keystorePassword;
    this.keystoreType = keystoreType;
    this.keystoreAlias = keystoreAlias.toLowerCase();

  }

  @Override
  public void customize(Connector connector) {
    connector.setPort(443);
    connector.setSecure(true);
    connector.setScheme("https");
    
    connector.setAttribute("SSLEnabled", true);
        connector.setAttribute("sslProtocol", "TLS");
        connector.setAttribute("protocol", "org.apache.coyote.http11.Http11Protocol");
        connector.setAttribute("clientAuth", false);
        connector.setAttribute("keystoreFile", absoluteKeystoreFile);
        connector.setAttribute("keystoreType", keystoreType);
        connector.setAttribute("keystorePass", keystorePassword);
        connector.setAttribute("keystoreAlias", keystoreAlias);
        connector.setAttribute("keyPass", keystorePassword);
  }
}

4. Create containerCustomizer Bean

Now to use the TomcatConnectionCustomizer, create the bean as follows:

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() throws FileNotFoundException {

  final String absoluteKeystoreFile = ResourceUtils.getFile("D:\\keystore\\server.p12").getAbsolutePath();

  final TomcatConnectorCustomizer customizer = new MyTomcatConnectionCustomizer(
      absoluteKeystoreFile, "keyPwd", "PKCS12", "keyalias"); 

  return new EmbeddedServletContainerCustomizer() {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
      if(container instanceof TomcatEmbeddedServletContainerFactory) {
        TomcatEmbeddedServletContainerFactory containerFactory = (TomcatEmbeddedServletContainerFactory) container;
        containerFactory.addConnectorCustomizers(customizer);
      }
    };
  };
}

5. Test it

Start Spring Boot App and go to the:

https:\\127.0.0.1

Your browser will propably warn you about the untrusted certificate:

Przechwytywanie

Note: Don’t use Self_signed certificates in production! Use it only in test / dev environment

Get the source code

Source Code for this tutorial is available on my github under the SpringBootHttps tag: https://github.com/yacekmm/looksok/tree/SpringBootHttps

Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!






Spring website layouts SSI with thymeleaf templates

28 06 2014

Based on application from this post, I will show how to make the MVC app containing two pages, both with the same header and footer, but different contents. I will reuse the header and footer HTML code, to avoid code duplication and follow DRY principle.

What I am going to build

The goal is to have two pages differecing only in body, the header and footer are the same, reused by SSI (Server Side Include)

layout

Get the source code

The source code for this tutorial you can find here. on the GitHub

Build basic MVC Spring app

You can base it, or copy the code from the tutorial in this post

Create Header and Footer contents

Create two HTML files with header and footer content. Mine will be basic ones:

header.html:

<div th:fragment="head" style="background-color: red">
	<h3><i>Spring tutorial header</i></h3>
</div>

footer.html:

<footer th:fragment="foot" style="background-color: yellow;">
  &copy; 2014 Jacek Milewski from <a href="http://www.looksok.wordpress.com">Looks OK!</a>
</footer>

Include fragments in your main pages
Add header and footer divs in your page, and include head and foot fragment from header.html and footer.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" 
	xmlns:th="http://www.thymeleaf.org" >
    <head>
        <title>Spring MVC Example</title>
    </head>
    <body>
       	<div th:include="header::head"></div>
    
        <h1>Welcome!</h1>
        <p>Click <a th:href="@{/greeting}">here</a> to advance to the next page.</p>

        <div th:include="footer::foot"></div>

    </body>
</html>

You can do it at any other page you need.

Include or replace?

Here I used th:include, so the header.html was inserted into div element. The other option is to replace that div entirely with fragment content. You can do it with th:replace instead of th:include.

Get the source code

The source code for this tutorial you can find here. on the GitHub

Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Spring boot MVC application tutorial

21 06 2014

spring-logoI will tutor you to create simple Spring MVC application based on Spring boot. App will have two linked web pages with thymeleaf. The project itself will be made in Eclipse as an Gradle project. Let’s start!

Download Source Code

Source for this tutorial is available here, on GitHub

Create project with Gradle build file

Create build.gradle file. First of all depict repositories and dependencies that you will use for gradle plugins:

buildscript {
    repositories {
        maven { url "http://repo.spring.io/libs-release" }
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.1.RELEASE")
    }
}

Then apply plugins for java, spring-boot and eclipse to have default targets of these plugins:

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'

Now show which java version compliance you want to have, and how your jar file will be named:

sourceCompatibility = 1.6

jar {
    baseName = 'looksok-mvc-demo'
    version =  '0.1.0'
}

And add repositories with dependencies used in your code:

repositories {
    mavenLocal()
    mavenCentral()
    maven { url "http://repo.spring.io/libs-release" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    testCompile("junit:junit")
}

Note: Use gradle version 1.1 or higher

Create web page templates in thymeleaf

Start with welcome page in src/main/resources/templates/hello.html with link to greeting page. If gradle did not automatically create directory structure, then create necessary folders on your own.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" 
	xmlns:th="http://www.thymeleaf.org" >
    <head>
        <title>Spring MVC Example</title>
    </head>
    <body>
        <h1>Welcome!</h1>

        <p>Click <a th:href="@{/greeting}">here</a> to advance to the next page.</p>
    </body>
</html>

and second template named greeting.html with link to previous page:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" 
	xmlns:th="http://www.thymeleaf.org" >
    <head>
        <title>Spring MVC Example</title>
    </head>
    <body>
        <h1>Hello on a second page!</h1>

        <p>Click <a th:href="@{/hello}">here</a> to go back.</p>
    </body>
</html>

Configure MVC application components

Now with template pages you need to register controllers that will expose views (templates). Create java class with MVC Configuration (extending WebMvcConfigurerAdapter and market with @Configuration annotation). There override the addViewControllers method and add your views to the registry:

@Configuration
public class MvcConfig extends WebMvcAutoConfigurationAdapter {

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/hello").setViewName("hello");
		registry.addViewController("/greeting").setViewName("greeting");
	}
}

Make the Spring boot application executable
Spring boot will compile to Uber jar file with servlet engine embedded. To make it possible, the jar needs to have main class. This is how it should look like:

@EnableAutoConfiguration
@Configuration
@ComponentScan("pl.looksok.spring")
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

Remember about annotations. The configuration annotation to indicate this is Spring config class, EnableAutoConfiguration of servlet engine and ComponentScan with package to scan (package is not mandatory when all @Configuration classes are in the same package).

Compile and run
Execute the command to build spring boot app:

gradle build compile

and to start the application:

java -jar [path_to_your_otput_jar]/looksok-mvc-demo-0.1.0.jar

To launch webpage, access the url:
localhost:8080\hello

Download Source Code

Source for this tutorial is available here, on GitHub

Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!








%d bloggers like this: