How can i add css, js, image in spring - spring

For adding css/js/image. I used WebMvcConfigurer (inteface) that have a method addResourceHandlers().[this is the interface1
This is the method of WebMvcConfigurer
This is the result after i run the application on server.

Related

How to set different prefix for endpoints and for static content in spring boot?

I would like to ask if it is possible (and how) to set different prefixes for static content and for endpoints in the spring boot app. I have been using server.servlet.contextPath=/api in application properties but it also sets the prefix for static content.
What I would like to achieve is to have "/api" prefix for endpoints in controllers and to serve the static content from "/" root.
EDITED
Actually what I need is to be able to set only the static content to "/" and rest of the app be available on "/api"
Spring Boot uses the built-in WebMvcAutoConfigurationAdapter for a Webapplication. The default behavior is defined within this class.
I assume your controllers are annotated with #RestController. If this is the case, you're able to map all controllers to a different location.
Create a configuration class which implements the WebMvcConfigurer interface. Override the method configurePathMatch(PathMatchConfigurer configurer) and implement your desired path configuration.
In the following example, the static content will still be served at "/" and all REST endpoints will be accessible with "/api" as prefix.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerTypePredicate;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
public class WebMvcConfig implements WebMvcConfigurer {
#Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.addPathPrefix("/api", HandlerTypePredicate.forAnnotation(RestController.class));
}
}
You'll notice there's no #EnableWebMvc annotation in this class, because it would disable the Spring Boot autoconfiguration mechanism for WebMvc.

spring-aop "None or multiple beans found in Spring context for type class"

I am not able to apply an aspect to my spring rest endpoint components for logging purposes.
All of endpoint classes are implemented like
#Component
#Path("mypath")
public class MyEndpointImpl extends MyEndpoint
{...}
Without aspect everything works fine without any errors. When I try to apply aspect I just get list of errors for each endpoint class like "None or multiple beans found in Spring context for type class **.*EndpointImpl" and no aspect is intercepting endpoints' methods. However everything works fine as if there were no error message and no aspect.
Interesting is when I create e.g. simple filter
#Component
#WebFilter(filterName = "MySimpleFilter", urlPatterns = "/*")
public class SimpleFilter implements javax.servlet.Filter
{...}
in package of pointcut, doFilter method of SimpleFilter is intercepted by the aspect as would expect for all endpoint methods.
What could be a problem here, any ideas?
In my environment the Problem disappeared when adding the following to the application.yml file
spring.aop.proxy-target-class: true

Serving single html page with Spring Boot

I'm developing a simple Spring Boot app that uses Spring Boot Web. I placed my index.html into the templates subdirectory of the resources directory as per the Spring Boot docs. I've defined inside the application.properties file:
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
My WebMvcConfigurerAdapter looks like this:
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter{
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
super.addViewControllers(registry);
}
}
My problem is I cant seem to serve index.html at http://localhost:8080.
I get the following error:
"javax.servlet.ServletException: Could not resolve view with name 'index' in servlet with name 'dispatcherServlet'".
How can I fix this without the use of a controller?
Kind regards,
Dave
In order to serve static content from Spring Boot application you just need to place them in src/main/resources/static - no other configuration needed.
put index.html to src/main/resources/static/index.html
delete properties from application.properties
delete addViewControllers method and #EnableWebMvc annotation - you can actually delete whole class
access index by going to http://localhost:8080/

The annotation #EnableSpringDataWebSupport does not work with WebMvcConfigurationSupport?

I had been using the WebMvcConfigurerAdapter for a while. Since i could not get all the registered interceptors with the method getInterceptors(), i have switched to WebMvcConfigurationSupport, which has lot of default registered Spring Beans like ContentNegotiationManager, ExceptionHandlerExceptionResolver usw.
Now i have realised that, the very handy DomainClassConverter (which converts the domain class ids to domain class objects by using a CrudRepository) is not registered by default, although i use the annotation #EnableSpringDataWebSupport on my WebConfig class.
When i define this bean explicitly like this, it works then.
#EnableSpringDataWebSupport
#Configuration
public class WebConfig extends WebMvcConfigurationSupport {
#Bean
public DomainClassConverter<?> domainClassConverter() {
return new DomainClassConverter<FormattingConversionService>(mvcConversionService());
}
}
But why EnableSpringDataWebSupport does not work with WebMvcConfigurationSupport?
It looks like configuration classes that extend WebMvcConfigurationSupport directly suffer from SPR-10565. The solution, at least for me, is to extend from DelegatingWebMvcConfiguration instead.
If you're overriding individual callbacks in your configuration class you'll likely want to call the superclass' implementation of the callback as well to ensure it's all handled correctly.

When use AbstractAnnotationConfigDispatcherServletInitializer and WebApplicationInitializer?

I am working with Spring 4.0.7
I did a research about configure Spring MVC through JavaConfig.
Practically until yesterday I have seen two configurations using these two options
extends AbstractAnnotationConfigDispatcherServletInitializer
extends WebMvcConfigurerAdapter and implements WebApplicationInitializer
Note: (2) are two classes, one for extension and the other for implementation
I am using (2) because I have found many examples where I am able to configure converters, formatters, resources handlers etc…
But in the latest days I have tried to help a question on StackOverflow and I did realize (1) exists.. I did some overview on Google about (1) and exists some examples working with (1)
My question is how the title of this post describe.
Thank You
With the release of the Servlet 3.0 spec it became possible to configure your Servlet Container with (almost) no xml. For this there is the ServletContainerInitializer in the Servlet specification. In this class you can register filters, listeners, servlets etc. as you would traditionally do in a web.xml.
Spring provides a an implementation the SpringServletContainerInitializer which knows how to handle WebApplicationInitializer classes. Spring also provides a couple of base classes to extend to make your life easier and the AbstractAnnotationConfigDispatcherServletInitializer is one of those. It registers
a ContextLoaderlistener (optionally) and a DispatcherServlet and allows you to easily add configuration classes to load for both classes and to apply filters to the DispatcherServlet and to provide the servlet mapping.
The WebMvcConfigurerAdapter is for configuring Spring MVC, the replacement of the xml file loaded by the DispatcherServlet for configuring Spring MVC. The WebMvcConfigurerAdapter should be used for a #Configuration class.
#Configuration
#EnableWebMvc
public class WebConfiguration
extends WebMvcConfigurerAdapter implements WebApplicationInitializer
{ ... }
I wouldn't recommend mixing those as they are basically 2 different concerns. The first is for configuring the servlet container, the latter for configuring Spring MVC.
You would want to split those into 2 classes.
For the configuration.
#Configuration
#EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter { ... }
For bootstrapping the application.
public class MyWebApplicationInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer
{
protected Class<?>[] getRootConfigClasses() {
return new Class[] {RootConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[] {WebConfiguration .class};
}
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
An added advantage is that you now can use the convenience classes provided by Spring instead of manually configuring the DispatcherServlet and/or ContextLoaderListener.
To start from the beginning it is worth looking into how servlet container starts.
SpringServletContainerInitializer is bootstrapped automatically by any Servlet 3.0 container.
SpringServletContainerInitializer looks for classes implementing WebApplicationInitializer (link to spring.io; also well described in "Spring In Action" 4th edition by Craig Walls, p.135).
So to start - SpringServletContainerInitializer has to find the right class implementing WebApplicationInitializer. There are two ways of making it happen:
One is by implementing WebApplicationInitializer on its own; the interface was introduced in Spring 3.1
The second is by extending AbstractAnnotationConfigDispatcherServletInitializer class which also implements WebApplicationInitializer. The class was introduced in Spring 3.2 for convenience and it is "the preferred approach for applications that use Java-based Spring configuration." - see the link. It enables you to start servlet application context as well as root application context.
I would also like to higlight that WebMvcConfigurerAdapter you mention should not be confused with WebApplicationInitializer. As it name suggests - it has to do with configuring "Mvc". It is an adapter class that implements empty methods from WebMvcConfigurer. You use it when you configure your Mvc controller with #EnableWebMvc annotation.
Hope this helps.

Resources