How can i add multiple resource handler in spring boot - java

In spring the resource handler is working fine
<mvc:resources mapping="/Lab/**" location="/WEB-INF/Assets/Lab/"/>
<mvc:resources mapping="/Tools/**" location="/WEB-INF/Assets/Tools/"/>
<mvc:resources mapping="/Images/**" location="/WEB-INF/Assets/Images/"/>
How can i add multiple resources in spring boot?
The below code is not working
#Configuration
#EnableWebMvc
public class ResourceHandlers extends WebMvcConfigurerAdapter
{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry
.addResourceHandler("/Lab/**")
.addResourceLocations("/WEB-INF/Assets/Lab/");
registry
.addResourceHandler("/Tools/**")
.addResourceLocations("/WEB-INF/Assets/Tools/");
registry
.addResourceHandler("/Images/**")
.addResourceLocations("/WEB-INF/Assets/Images/");
}
}

registry
.addResourceHandler("/Lab/**", "/Tools/**", "/Images/**")
.addResourceLocations("/WEB-INF/Assets/Lab/",
"/WEB-INF/Assets/Tools/",
"/WEB-INF/Assets/Images/");
It allows multiple arguments

Related

Spring WebMVC 5 - Annotation based Interceptor

How to configure an Interceptor, through Annotation only(I do NOT like to register the interceptor in .XML file, I do not use .XML based configuration)?
Note : I see in example on internet it is suggesting to use org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter, when I tried to use it, I found it is DEPRECATED
I am testing on SpringWebMVC-5 with SpringBoot-2
In Spring5 you can use org.springframework.web.servlet.config.annotation.WebMvcConfigurer:
#EnableWebMvc
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(....);
}
}

Webjars + Springboot. Custom resource path

I have a Spring Boot application which acts as a server for my frontend, built by webpack and included into my spring boot web archive.
I use webjars to access my frontend scripts and contents.
But there is one problem. To access webjars resources I need to use pathes like:
/webjars/jar-file-name/resource-name.ext
When in my react-js frontend code I use relateve pathes:
/resource-name.ext
I want to rebind paths of webjars to serve all resources /** from /webjars/jar-file-name
I have used this do to do it https://www.webjars.org/documentation#springmvc, but this seems to not work with Spring Boot
#Configuration
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/webjars/jar-file-name/");
}
}
It should work with Spring MVC, but don't work in Spring Boot.
Could you please advice the right way to do it?
I think the following code would resolve your issue:
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Here is my static content serving URL for bootstrap 3.1.0 from tutorial: http://localhost:8080/bootstrap/3.1.0/css/bootstrap.min.css

spring test \ Junit - skip configuration on tests

I have the following class:
#Configuration
#EnableWebSocketMessageBroker
#EnableScheduling
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableStompBrokerRelay(
"/topic",
"/queue/");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint(
"/wsdemo").withSockJS();
}
}
I would like to be able to NOT configure the class above whenever I'm running tests. is that possible?
Thanks!
A plain Junit test (without the spring runner) will ensure the class is not configured. you can then use mock objects (see Mockito) to satisfy any dependencies.
If you have separate "application-context.xml" for your tests, then there you must have directive:
<context:component-scan base-package="...">
...
</context:component-scan>
Modify it as below:
<context:component-scan base-package="...">
...
<context:exclude-filter type="regex" expression="{package}.WebSocketConfig"/>
</context:component-scan>

Annotation Configuration Replacement for mvc:resources - Spring

I'm trying to upgrade my spring mvc project to utilize the new annotations and get rid of my xml. Previously I was loading my static resources in my web.xml with the line:
<mvc:resources mapping="/resources/**" location="/resources/" />
Now, I'm utilizing the WebApplicationInitializer class and #EnableWebMvc annotation to startup my service without any xml files, but can't seem to figure out how to load my resources.
Is there an annotation or new configuration to pull these resources back in without having to use xml?
For Spring 3 & 4:
One way to do this is to have your configuration class extend WebMvcConfigurerAdapter, then override the following method as such:
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
Spring 5
As of Spring 5, the correct way to do this is to simply implement the WebMvcConfigurer interface.
For example:
#Configuration
#EnableWebMvc
public class MyApplication implements WebMvcConfigurer {
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
See deprecated message in: WebMvcConfigurerAdapter

How to configure MappingJacksonHttpMessageConverter while using spring annotation-based configuration?

I was unreasonable enough to went into configuring spring beans via annotations and not pure xml beans and now I'm facing the consequences.
I configure REST channels using
<mvc:annotation-driven />
Now I want simply configure the MappingJacksonHttpMessageConverter to output to JSON only this fields that have non-null values. I've tried the following:
<bean id="jsonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prefixJson" value="false" />
<property name="supportedMediaTypes" value="application/json" />
<property name="objectMapper">
<bean class="org.codehaus.jackson.map.ObjectMapper">
<property name="serializationInclusion" value="NON_NULL"/>
</bean>
</property>
</bean>
The beans gets created, but another instance of converter is created and used in channels. So I've tried the way with #Configuration and #Bean described in this Stackoverflow question, but still json serialization uses its own configuration.
Finally I've tried to inject the mapper via
#Autowired
private MappingJacksonHttpMessageConverter jacksonConverter;
but I've ended with NoSuchBeanDefinitionException. So now I'm out of options and therefore I'm asking for any ideas here. How to controll and configure the mapper used by framework?
Use the WebMvcConfigurer.configureMessageConverters() method:
Configure the HttpMessageConverters to use [...] If no message converters are added to the list, default converters are added instead.
With #Configuration you have:
#Configuration
class MvcConf extends WebMvcConfigurationSupport {
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(converter());
addDefaultHttpMessageConverters(converters);
}
#Bean
MappingJacksonHttpMessageConverter converter() {
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter()
//do your customizations here...
return converter;
}
}
Call to addDefaultHttpMessageConverters() is required because the defaults are not applied when using custom converters.
IMPORTANT NOTE You must remove #EnableWebMvc for your converters to be configured if you extend WebMvcConfigurationSupport.
The customization of the spring mvc servlet configuration only in java code can be accomplished in multiple ways.
The simplest one seems to be extending your #Configuration annotated class with WebMvcConfigurerAdapter:
#Configuration
#EnableWebMvc
public class ApplicationSpringConfig extends WebMvcConfigurerAdapter {
#Override
public void configureMessageConverters( List<HttpMessageConverter<?>> converters ) {
converters.add(converter());
}
#Bean
MappingJackson2HttpMessageConverter converter() {
// [...]
}
}
Notice that this is lot like the example provided by the answer of Tomasz Nurkiewicz.
However using WebMvcConfigurationSupport instead of WebMvcConfigurerAdapter is more appropriate for Advanced Customizations. That was the case if you needed to also add the default converters.
See the Spring documentation Customizing the Provided Configuration
The following solution is for Spring 4.3, (non-boot) where it was necessary to address fetch=FetchType.LAZY by adding a module to the Jackson converters. A similar technique can be used to modify converters in any way, including removal and recreation.
#Configuration
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> mc : converters){
if (mc instanceof MappingJackson2HttpMessageConverter || mc instanceof MappingJackson2XmlHttpMessageConverter) {
((AbstractJackson2HttpMessageConverter) mc).getObjectMapper().registerModule(new Hibernate5Module());
}
}
return;
}
In this case,
the WebMvcConfigurerAdapter has a lot of other configuration in it and I wanted to avoid another configuration class.
Using extendMessageConverters enabled access to the automatically-configured Jackson classes without losing the configuration of all other message converters, which is what configureMessageConverters would have done.
Using registerModuleyou can simply add the needed Hibernate5Module to the existing converters.
The module was added to both the JSON and XML processors

Categories