Author: Dimitrios Mandekis

Java - Spring - Angular - TIBCO fan.
Enjoy architecting and developing simple solutions for complex problems.

Serve an AngularJS app from your Spring container.

Sometimes in life you have to take difficult decisions,

One of them is whether you will serve your beautiful designed AngularJS user interface from within your Spring container or as a separate deployment (on Apache httpd for example).

In case that you choose the former and if you are using Spring’s java config and Servlet 3.0 the following steps will do the trick.

  1. In your spring application initializer (the class that implements WebApplicationInitializer) add the following lines:

https://gist.github.com/mandekisd/067956b4ad74f3c2e225

Explanation: The first mapping serves requests made by your UI to the rest api.  The second serves the UI itself.  Substitute (in your mind) “servlet” with:

ServletRegistration.Dynamic servlet

2. In DispacherServlet’s WebConfig class (the class that extends the WebMvcConfigurerAdapter) add the following resource handler:

https://gist.github.com/mandekisd/f60bfddbec7c804deed2

Explanation: This resource handler is for serving the AngularJS UI as a static resource.

3. In the same file (WebConfig) add the DefaultServetHandling configuration element (http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-default-servlet-handler).

And finally run and enjoy!!!