Skip to content

Instantly share code, notes, and snippets.

@SylvainMarty
Created December 3, 2017 09:21
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SylvainMarty/5b0427a0bed3a46cc60b691f7a5d1921 to your computer and use it in GitHub Desktop.
Save SylvainMarty/5b0427a0bed3a46cc60b691f7a5d1921 to your computer and use it in GitHub Desktop.
Code snippet to enable "HTML5 history mode" in Spring MVC

Spring MVC - Enable HTML5 history mode

This snippet shows how to authorize HTML5 history mode used by Javascript frameworks like Angular or VueJS.

There is two simple steps :

  • Create the filter
  • Register it in your project configuration

Create the filter

Create the file HistoryModeFilter.java with the following content :

import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

public class HistoryModeFilter extends OncePerRequestFilter {

    // Update the regex as you needed
    private Pattern patt = Pattern.compile("^/([^\\.])*");
    // Main route
    private String endpoint = "/";

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        if(this.patt.matcher(request.getRequestURI()).matches()) {
            RequestDispatcher rd = request.getRequestDispatcher(endpoint);
            rd.forward(request, response);
        } else {
            filterChain.doFilter(request, response);
        }
    }

}

Register the filter

Add this line in your local WebSecurityConfigurerAdapter :

@Configuration
public class WebConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ...
        
        http.addFilterAfter(new HistoryModeFilter(), FilterSecurityInterceptor.class);

        // ...
    }
    
}

Greetings

Thanks to @iwanzarembo for this thread.

@549393092
Copy link

Thanks for this great article.
Currently, I am facing some similar issue. Could you please check below issue?
https://forum.vuejs.org/t/vue-router-disclosure-json-result-after-reload-page/11007
It says it has to be fixed on the server, as I can't find any answer related to spring MVC except yours.
I tried your solution, but it seems not work.
If I refresh link on the browser or navigate from the main page, the variable "request.getRequestURI()" is the same.
Appreciate for you help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment