How can I serve static html from spring boot?
Static files should be served from resources, not from a controller.
Spring Boot will automatically add static web resources located within
any of the following directories:/META-INF/resources/
/resources/
/static/
/public/
refs:
https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot
https://spring.io/guides/gs/serving-web-content/
how to serve static content in springboot 2.2.6?
Starting with a simple spring boot initializer
... we can place static (html) files into one of:
- (src/main/resources:)
- static
- resources
- public
- META-INF
- resources
which results in the default (class path) locations, configured via the spring.resources.static-locations
property.
These will be exposed through the value of spring.mvc.static-path-pattern
-property (ref), by default: /**
.
So a static index.html file in one of the above mentioned folders, with default config, will be accessible at:
- http:localhost:8080/ (due to "welcome file mapping" -> static mapping)
- and http://localhost:8080/index.html (due to the static mapping)
Accordingly: no problem with http://localhost:8080/test.html ...
Checkout at github.
So this, at least answers the "question title" "how to serve static content in springboot 2.2.6?".
The order of spring.resources.static-locations
appears (index.html preferred from META-INF/resources) also to be the "precedence" of static file locations (left-to-right, first match wins).
When we add @EnableWebMvc
..."evertyhing gets broken" (context loads, but) only:
WARN ... o.s.web.servlet.PageNotFound : No mapping for GET /
WARN ... o.s.web.servlet.PageNotFound : No mapping for GET /index.html
WARN ... o.s.web.servlet.PageNotFound : No mapping for GET /test.html
..please aslo consider this: why spring-boot application doesn't require @EnableWebMvc
With "non-default config", You would have to provide more details, to find a specific solution.
But for "newbie in Springboot": starting with an intializer and "the defaults" sounds optimal! From here on, you can re-fine your configuration based on a working one.
And if you want/need the @EnableWebMvc
annotation for some reason, this will result in the "previous" behavior again/restore the (2.2.6) default static content handling:
@EnableWebMvc
@SpringBootApplication
public class DemoApplication implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/");
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
(Assuming no conflicts with existing configuration/resource handlers)
How to serve .html files with Spring
The initial problem is that the the configuration specifies a property suffix=".jsp"
so the ViewResolver implementing class will add .jsp
to the end of the view name being returned from your method.
However since you commented out the InternalResourceViewResolver
then, depending on the rest of your application configuration, there might not be any other ViewResolver registered. You might find that nothing is working now.
Since .html
files are static and do not require processing by a servlet then it is more efficient, and simpler, to use an <mvc:resources/>
mapping. This requires Spring 3.0.4+.
For example:
<mvc:resources mapping="/static/**" location="/static/" />
which would pass through all requests starting with /static/
to the webapp/static/
directory.
So by putting index.html
in webapp/static/
and using return "static/index.html";
from your method, Spring should find the view.
Spring Boot - how to serve one static html file for multiple routes in specified root
I found this solution:
// application.properties
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html
// Controller for index.html
@Controller
public class IndexController {
@RequestMapping({"/login", "/main/**"})
public String index() {
return "index";
}
}
Serve To Html From Spring RestController
The @RestController will return the response in Rest Style(default json). So if you are building single page application and calling your Rest webservice using ajax call then RestController will be useful.
If you want to show complete new page for products then you can use @Controller which will redirect you to appropriate view using viewResolver and you can show the data stored in ModelAndView.
For using html you can use Thymeleaf which uses html file but have more options to render complex object and supports El.
sample code:
@Controller
public class MainController {
//Get CommandInterpreter object
private CommandInterpreter ci = new CommandInterpreter();
private List <Vehicle> vehicles;
MainController() throws Exception {
//Set up list of vehicles from JSON
vehicles = ci.parseJsonVehicles();
}
@RequestMapping("/vehicles-by-price")
public ModelAndView getVehiclesByPrice() {
vehicles = ci.getVehiclesByPrice(vehicles);
ModelAndView mv = new ModelAndView();
mv.add("vehicles", vehicles);
mv.setViewName("vehiclesByPrice");
return mv;
}
}
Sample resources/static/vehiclesByPrice.html template:
<!DOCTYPE HTML>
<html
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<table>
<tr th:each="vehicle : ${vehicles}">
<td th:text="${vehicle}">1</td>
</tr>
</table>
</body>
</html>
The spring boot project cannot access static files
I have found your error. You use the root context path spring-demo
which is not applied to the relative path as needed
You must change it into
<link href="/spring-demo/static/js/chunk-vendors.365b8cfb.js" rel="preload" as="script">
Serve static html files omitting the .html extension in the url
To return html static file without extension is the same as return view name from any of templates engines (jsp, theamleaf, freemarker), the thing here you do not need to run any templates processing on view file, you just return it as it is.
Add code below to your Spring configuration:
@Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("pages/");
internalResourceViewResolver.setSuffix(".html");
return internalResourceViewResolver;
}
Be careful /pages
folder should be inside your ResourceLocation
, that means ResourceLocation + "/pages/" + pageName.html
in browser should give you desired file (if you already configured servicing of static files it will not be a problem for you to find your ResourceLocation, check method addResourceHandlers
in your WebMvcConfigurer)
Now at your WebMvcConfigurer you can add:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/admin").setViewName("admin");
registry.addViewController("/contact").setViewName("contact");
registry.addViewController("/error").setViewName("index");
}
or just use it, as you would use it in usual view resolver within MVC controller
@GetMapping("/")
public String greeting() {
return "index";
}
Related Topics
Io Error: the Network Adapter Could Not Establish the Connection
How to Read File from End to Start (In Reverse Order) in Java
Why Do I Get the "Unhandled Exception Type Ioexception"
Rationale for Matcher Throwing Illegalstateexception When No 'Matching' Method Is Called
How to Split a Java String at Backslash
Multi-Project Test Dependencies with Gradle
How to Force Selenium Webdriver to Click on Element Which Is Not Currently Visible
Sorting Arraylist in Alphabetical Order (Case Insensitive)
Jackson and Generic Type Reference
How to Have Explained the Difference Between an Interface and an Abstract Class
Using Java with Nvidia Gpus (Cuda)
Reversing a Linked List in Java, Recursively
When Should I Use File.Separator and When File.Pathseparator
How to Go About Formatting 1200 to 1.2K in Java