Spring boot for Spring mvc and Angular JS not refreshing static resources - spring

I am running Spring boot in IntelliJ idea and have found that spring boot is no longer refreshing my changes to the resources which is where i have the html and js files. It was working fine but now only seems to detect changes on system reboot.
Is there a way to prevent caching of files ?

let assume you cached the required files like below code :
#SpringBootApplication
public class App extends SpringBootServletInitializer {
#Bean
public WebMvcConfigurerAdapter webConfigurer () {
return new WebMvcConfigurerAdapter() {
#Override
public void addResourceHandlers (ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/js/**")
.addResourceLocations("/static/js/")
.setCacheControl(CacheControl.maxAge(300, TimeUnit.DAYS));
registry.addResourceHandler("/static/images/**")
.addResourceLocations("/static/images/")
.setCacheControl(CacheControl.maxAge(7, TimeUnit.DAYS));
registry.addResourceHandler("/static/css/**")
.addResourceLocations("/static/css/")
.setCacheControl(CacheControl.maxAge(300, TimeUnit.DAYS));
}
};
}
}
add new folder like "nonCached" folder and include your non Cached files like below :

Related

Component inside auto configuration application not getting registered

I have created a simple spring boot starter configuration.
Along with other files I have Interceptor which should auto-register.
My Configuration is registered in the file is as follow:
/resource/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports=DynamicDataSourceAutoConfiguration
Autoconfiguration kicks in but the components inside this are not initialized.
My default component inside auto configuration is as follow;
#Component
public class AppWebMvcConfigurer implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CommonHeadersInterceptor());
}
}
This starter I am using in multiple micro-service.
Since it is not registered automatically. I have to re-create this AppWebMvcConfigurer file in each of my micro-services.
Please help me if there is some other configuration I need to do for AutoConfiguration to kick in.
FYI: Other files include
Properties
Configuration
DataSources
EDIT:1
I created config file and added the same path in .imports file metioned above. For time being this seems solved.
#Configuration
public class HeaderTenantMvcConfiguration {
#Bean
public AppWebMvcConfigurer webMvcConfigurer() {
return new AppWebMvcConfigurer();
}
}
My org.springframework.boot.autoconfigure.AutoConfiguration.imports now looks something like this:
com.silentsudo.data.DataSourceAutoConfig
com.silentsudo.web.mvc.AppWebMvcConfigurer

Spring Boot: Adding static resources from file system breaks existing mappings

I have a Spring Boot MVC application in which I am trying to load resources from an external folder on the file system. I have used the following to configure this:
#Configuration
#EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/where/**")
.addResourceLocations("file:///C:/some/where/");
}
...
}
Once I configure this, I can access my static files by going to http://serverurl/where/somefile
BUT, I am no longer able to access the home page at http://serverurl/
Any idea what I did wrong here?

How to Configure Servlet Mapping and Resource Handler in Spring MVC

I have created sample Spring MVC REST Maven project with following folder structure
ResourceHandlerRegistry configuration as follows
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.raju.spring_app")
public class RootConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static_res/*").addResourceLocations("/WEB-INF/html/static_res/");
}
//Other methods
}
Servlet mapping as follows
public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected String[] getServletMappings() {
return new String[] { "/", "/static_res/*" };
}
//Other Methods
}
The problem is whenever I tried to access resource
http://localhost:8080/spring4_rest_angular_demo/static/css/app.css
I got 404 error.
I want to keep this folder structure to get css IntelliSense suggestions
in index.jsp file.
<link href="static_res/css/app.css" rel="stylesheet"></link>
Few corrections :
Replace
return new String[] { "/", "/static_res/*" };
with
return new String[] { "/" };
and
registry.addResourceHandler("/static_res/*")
with
registry.addResourceHandler("/static_res/**")
Also, the right path is
http://localhost:8080/spring4_rest_angular_demo/static_res/css/app.css
and not
http://localhost:8080/spring4_rest_angular_demo/static/css/app.css
With Spring 3.0.4.RELEASE and higher you can use
<mvc:resources mapping="/resources/**" location="/public-resources/"/>
As seen in http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-static-resources
Also, you should avoid putting pages in WEB-INF. Put the folder with html/css/js higher in hierarchy, under the web app folder. Generally, in WEB-INF there should be only configuration xml files.

Spring Boot - custom 404 page with standalone tomcat

I am running a Spring boot application inside a standalone tomcat instance, and I am trying to override the error pages. From my understanding, Spring provides a filter ErrorPageFilter that allows me to just setup error pages as normal for Springs EmbeddedServletContainerCustomizer to handle this case exactly.
So I have my standard auto configuration/servlet initializer in one class:
#Configuration
#ComponentScan
#EnableAutoConfiguration(exclude = [ GroovyTemplateAutoConfiguration, SecurityAutoConfiguration, ErrorMvcAutoConfiguration, JmxAutoConfiguration ] )
class Application extends SpringBootServletInitializer {
#Override protected SpringApplicationBuilder configure( SpringApplicationBuilder application ) {
application.sources( Application )
}
(I am using the same class for autoconfiguration and servlet init, which is why i just pass my Application class in the configure method)
Looking at the source code for SpringBootServletInitializer it looks like the ErrorPageFilter class is being added by just extending that class here. I have turned off the ErrorMvcAutoConfiguration - but again, looking at that source code it looks like that is just setting default error pages and not actually setting anything up with the ErrorPageFilter.
I then have my error config file:
#Configuration
class ErrorConfiguration implements EmbeddedServletContainerCustomizer {
#Override public void customize( ConfigurableEmbeddedServletContainer container ) {
container.addErrorPages(new ErrorPage( HttpStatus.NOT_FOUND, "/errors/404" ))
}
However, if I just visit an invalid URL, and I DispatcherServlet can't find a match then I just get tomcats /404.html - not my view linked to "/errors/404" (I have this path mapped to a thymeleaf view template, that works fine - if I navigate to /errors/404 it displays ok)
Any ideas why my custom error page is not working? tracing the logs, I get a line about the ErrorPageFilter being configured and setup ok on application startup, but then no mentions of the filter doing anything when a request comes in.
You can use following code for older versions of spring boot (0.5.x)
public class ServerCustomization extends ServerProperties {
#Override
public void customize(ConfigurableEmbeddedServletContainerFactory factory) {
super.customize(factory);
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
"/yourpath/error-not-found.jsp"));
factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,
"/yourpath/error-internal.jsp"));
factory.addErrorPages(new ErrorPage("/yourpath/error-other.jsp"));
}
}
Newer spring boot versions (1.X.RELEASE) has some refactoring around ServerProperties. See below,
public class ServerCustomization extends ServerProperties {
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
super.customize(container);
container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,
"/jsp/404.jsp"));
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR,
"/jsp/500.jsp"));
container.addErrorPages(new ErrorPage("/jsp/error.jsp"));
}
}
Then define a bean to inject ServerProperies.
#Bean
public ServerProperties getServerProperties() {
return new ServerCustomization();
}
Sample project posted in git
Very Important: If you are using maven to build, You must store all the resource files under src/main/resources folder. Otherwise maven will not add those files to final jar artifact.
You can either use Spring Boot's builtin error view by implementing a view named error, or switch it off by setting error.whitelabel.enabled=false property and implement your own. It's explained more in the docs.

META-INF/resources not works properly with #EnableWebMVC in Spring Boot

1.
I'm working with Spring Boot. My Main class very simple
#ComponentScan
#EnableAutoConfiguration
#Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#2. Now I would like to make my static content externalised into a jar file. So, below is the jar project
/pom.xml
/src/main/resources/META-INF/resources/hello.json // here is my resource
I do maven install and put the dependency into the main app, run the app normally. Now I can invoke http://localhost:8080/hello.json to get my hello.json file
#3. Then, the next step is using the Apache Tiles for my main web project, so I create a #EnableWebMvc class to configure the tilesViewResolver
#Configuration
#EnableWebMvc
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
public #Bean TilesViewResolver tilesViewResolver() {
return new TilesViewResolver();
}
public #Bean TilesConfigurer tilesConfigurer() {
TilesConfigurer ret = new TilesConfigurer();
ret.setDefinitions(new String[] { "classpath:tiles.xml" });
return ret;
}
}
Then I started again the application and try the hello.json to ensure everything still works properly. But, the 404 page appear. Delete the WebMvcConfiguration give back my hello.json.
What configuration I should do to resolve this issue?
Thanks a lot.
In Spring MVC, using XML configuration, you have to have a tag like the following to service static content:
<mvc:resources mapping="/js/**" location="/js/"/>
This insinuates that Spring Boot is doing something to automatically guess that you have static content and properly setup the above example in META-INF/resources. It's not really "magic", but rather that they have a default Java Configuration using #EnableWebMvc that has some pretty reliable default values.
When you provide your own #EnableWebMvc, my guess is you are over-writting their "default" one. In order to add back a resource handler, you would do something like this:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
}
This is equivalent to the XML above.

Resources