How serve web-folder in Spring Boot out from /resources/ - java

I need help, my Spring Boot 2 Server from a first web generate other web site (folder with html,css ext ext) from a template, but these web sites/html aren't accessible, Spring give me error 404, not found.
I will build the project with Maven in .jar
The gerarchy of the project is this:
---
|_folder (Directory with webapps generated, NOT DELIVERED)
. |_webapp1
. |_webapp2
|_src
. |_main
. . |_java
. . |_resources
. . . |_public (With first web)
. . . |_static (Template used to generate other web site, i simply copy this directoy in other directory, doing templateServices.copyDirectory("target/classes/static/", "folder/webapp1");
---
I tried with this configuration, but dont work.
#Configuration
#EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/", FileController.uploadingDir};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
}

If the web server is going to generate websites, as you said, then you should save the files outside the Spring Boot scope; just in a folder of your filesystem. An example could be:
#Configuration
#EnableWebMvc
public class AppConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("file:/var/www/websites/");
}
}
If you have dynamic websites (you said it depends on the users) you can inside the method get all users in the system, and add ResourceHandlers for them in specific locations.

Related

Spring 5 add static file directory webapp

I have a Spring 5 (not Spring Boot) web application. I have one controller that outputs html. I output a string which is HTML and it works, however the relative paths the JS content do not work. I will layout my structure as follows:
src
main
java
resources
webapp
css
js
img
WEB-INF
index.html
test
java
resources
When I output my html text, all the relative locations cannot be found:
if I call:
http://localhost:8080/myapp/controller?{some parameters}
I would expect
http://localhost:8080/myapp/js/myjsfile.js
would be there. When I build and deploy the WAR, the exploded WAR file has all the right code. So I would expect the file to be there and found. However, I expect from what I've been reading that static files can be served out differently. So, I have two questions:
1) What is the standard way of serving static files from a Spring 5 web application? Do I change the structure this way:
src
main
java
resources
static
css
js
img
webapp
WEB-INF
index.html
test
java
resources
And then I am presuming I have to do the webconfig as such:
#Configuration
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/resources/**")
.addResourceLocations("static/js", "static/css", "static/img")
.setCachePeriod(31556926);
}
}
2) OR, can I use the existing structure and then change the WebConfig to add those static locations as follows:
#Configuration
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/webapp/**")
.addResourceLocations("/js", "css", "img")
.setCachePeriod(31556926);
}
}
But if putting these files under webapp doesn't work, I can understand moving them to /resources if that is the standard way of doing thing.
So, if I could get any help with this, that will be fine. I am fine with either way as long as it works. Thanks!
Try to use the resources/static folder to provide your view files. And add the following configuration to your WebMvcConfigurer:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
It will map all static files requested in the "/" URL to redirect to resources/static folder.
Option 1 is the way to go, place your folder under resources directory (name it as you wish):
src/main/java/resources
myStaticResourcesFolder
css
js
img
Then just do this:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**") // map to whatever url you need
.addResourceLocations("myStaticResourcesFolder/"); //
}

Spring Boot static resources are not available

Files in resources/static are not available. How I can fix it?
Hierarchy:
resources/
db/
static/
image.png
templates/
application.properties
But if I open localhost:8081/image.png I get error.
My WebConfig:
#Configuration
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/webjars/**")
.addResourceLocations("/webjars/");
}
}
You should add below line to your existing resource mapping:
registry.addResourceHandler("/**")
.addResourceLocations("resources/static/");
You have configured the webjars resourceHandler to serve client side script or stylesheet dependencies. but custom handler is not added to serve your image file.
Since you are overriding the addResourceHandlers (ResourceHandlerRegistry registry) method, you should provide all the resourceLocation and handler mapping in your implementation.
Please check serving-static-web-content-with-spring-boot article to have more clear idea.
Note:
If you are using spring-boot you shouldn't be overriding the above method untill explicitly required as its already taken care in WebMvcAutoConfiguration.java.
Please check below default implementation:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache()
.getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry
.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(
registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(
this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl));
}
}
Here give path of your image:
registry.addResourceHandler("/**").addResourceLocations("file:/path/to/your/image/");
If you would prefer to serve static content (including web pages, js, pdf, css, pdf, doc etc.) from outside of the WAR, may be that is usefull. if you wanna changed any that static contents, just you can put changed file to your content path on application server easly and serving that without deploying or restarting you application server. If you prefer this way, you can do it with a small configuration on your application server.

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

SpringBoot not automatically serving static files

I have SpringBoot 1.3.3 and a working Java API exposed on port 8080. However, along with this API I would like to expose an index.html file located directly under {projectName}/src/main/resources/, according to the Springboot documentation this should be served up automatically but when I navigate to http://localhost:8080/index.html I get a 404. I am not using #EnableWebMVC anywhere and have tried adding my own configuration file like below, however nothing has worked so I'm kind of at a loss. Any help would be much appreciated!
#Configuration
#EnableWebMvc
#ComponentScan
public class ServerConfiguration extends WebMvcAutoConfiguration {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
}
Put the files in /src/main/resources/public/

404 resolving view in spring servlet

I have a Spring (4) MVC servlet running on Tomcat 8 in Eclipse. When I start tomcat, there are no errors in the console and all the correct request mappings for my controllers are logged. If I try to access localhost:8080/app/login my controller method executes (checked via debugging), but I get a 404 page with the following:
message /app/WEB-INF/jsp/login.jsp
description The requested resource is not available.
My project has the following directory structure:
project-root
|-src
|-WebContent
|-WEB-INF
|-jsp
|-login.jsp
My configuration class:
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = "com.example")
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureViewResolvers(final ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/jsp/", ".jsp").viewClass(JstlView.class);
}
//Other stuff
}
Controller:
#Controller
#RequestMapping("/login")
public class AuthnRequestController {
#RequestMapping(value = "", method = RequestMethod.GET)
public ModelAndView getLoginPage() {
return new ModelAndView("login");
}
//Other stuff
}
The application was working fine in the past, but I was screwing around with my workspace/projects working on something else, and am unable to get this working again now that I'm coming back to it.
AFAIK, By default in a maven war project the jsp files are expected under /src/main/resources/. Since you have given a jsp file prefix of /WEB-INF/jsp/ in your config, please try moving the jsp files to the below location.
/src/main/webapp/WEB-INF/jsp/
Assumptions:
a mapping to root/WebContent is not provided in Web deployment assembly.
a mapping to /src/main/webapp is present in Web deployment assembly.
your eclipse is using maven war plugin

Categories