如何让 Spring MVC 在运行时(在方法中)返回静态资源?
解释得更好。我配置了我的应用程序(spring-mvc 3.2.4)来处理一些静态资源并使用两个视图解析器,FreeMaker 和 Json。我希望在控制器方法中我能够对 spring-mvc 说他必须将文件放入静态资源中,尽管其中一个视图解析器尝试使用 hadle。
我的配置类如下所示:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.xxxx", excludeFilters = @Filter(Configuration.class)})
public class WebConfig extends WebMvcConfigurerAdapter {
...
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app.js").addResourceLocations("/app.js");
}
...
@Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
// Define the view resolvers
List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
JsonViewResolver jsonViewResolver = new JsonViewResolver();
FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
freeMarkerViewResolver.setSuffix("rtl");
resolvers.add(jsonViewResolver);
resolvers.add(freeMarkerViewResolver);
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
resolver.setViewResolvers(resolvers);
return resolver;
}
}
我的控制器:
@Controller
@RequestMapping("/")
public class JSViewController {
@RequestMapping(value="*.js")
public String resolveArquivo(HttpServletRequest request){
// Here I would be able to say to sprint to return a static resource instead of hadle it with one of the View Resolvers.
return request.getRequestURI().replace(request.getContextPath(),"");
}
}