amol
amol

Reputation: 125

Unable to resolve static resources in Spring MVC

I know this question has a lot of answers but i cannot solve mine so that is why i decided to put up the question I want to resolve both jsp and html files. Below is my spring resolver configuration

@Bean
public ViewResolver getViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix("");
    return resolver;
}

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/views/static");
}

and controller class is below:

@RequestMapping("/testApi2")
@Controller
public class TestController2 
{
   @RequestMapping("/showHomePage")
    public ModelAndView showHome(){
      return new ModelAndView("/static/about.html");
    }

}

I have also attached screen shot of my directory structure, it is giving 404 on every request

enter image description here

Upvotes: 2

Views: 915

Answers (2)

amol
amol

Reputation: 125

After some efforts , thanks to lot of documentation on Spring , i was able to resolve the issue

I found a solution(searched on net) with which we can use both JSP and HTML as views

Forget the question , below are the new settings

Static resources (.css,.js,.jpg) are placed in webapp/assets/

HTML files are in /WEB-INF/static/

Here is my configuration file :

@Bean
public ViewResolver getViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix("");
    return resolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

    registry.addResourceHandler("/assets/**") //
            .addResourceLocations("/assets/").setCachePeriod(31556926);

}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

Please note i have used resolver.setSuffix("") both HTML and JSP

HTML code :

<link rel="stylesheet" href="/taxi/assets/css/theme-pink.css" />

Here taxi is the context root , means name of the project

Now if i run the below URL , it will fetch the image or CSS of js

localhost:8080/taxi/assets/css/icons.css

Upvotes: 1

Sergei Belonosov
Sergei Belonosov

Reputation: 21

I think that you should add to your web resolver config class one very special handling configurer:

@Override
public void configureDefaultServletHandling(

DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

This method enables static resources processing.

Upvotes: 2

Related Questions