I have a Spring Boot app setup as a REST api. I now also want to be able to serve simple HTML pages to the client, without the use on any template engine like Thymeleaf. I want access to the HTML pages to fall under the same security constraints setup by Spring Security with the use of WebSecurityConfigurerAdapter, already present in my app.
What I've tried is having a Controller:
#Controller
public class HtmlPageController {
#RequestMapping(value = "/some/path/test", method = RequestMethod.GET)
public String getTestPage() {
return "test.html";
}
}
and placing the test.html file in /resources/test.html or /webapp/WEB-INF/test.html.
Every time I try to access the page at localhost:8080/some/path/test a 404 is returned.
How do I make this work?
Okey so apparently Spring Boot supports this without any additional configuration or controllers.
All I had to do was to place the HTML file in the correct directory /resources/static/some/path/test.html and it can be reached at localhost:8080/some/path/test.html.
In my attempts to change the directory from which the file is served I was unsuccessful. It seems that providing a separate #EnableWebMvc (needed for configuring the resource handlers) breaks the Spring Boot configuration. But I can live with using the default /static directory.
There is a Spring MVC mecanism that exists to provide static resources.
In the config class, overide this method :
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("some/path/*.html")
.addResourceLocations("/static/");
}
And place your html files in the src/main/webapp/static/ folder.
If you request some/path/test.html (note the .html), it will return the test.html file located in static folder.
You can obviously use a different folder or a more sofiticated directory structure.
This way you don't have to create a controller. Note that your config class should implements WebMvcConfigurer.
Your html, js and css files should be under the src/main/resources/static directory. and your return statement you can try removing .html.
#RestController
public class HtmlPageController {
#GetMapping("/some/path/test")
public String getTestPage() {
return "test";
}
}
See tutotrial example how to define html view in Spring MVC configuration
#Bean
public InternalResourceViewResolver htmlViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/html/");
bean.setSuffix(".html");
bean.setOrder(2);
return bean;
}
setOrder is set to 2 because it include also JSP support in example
Also you need to change to return without .html suffix
return "test.html";
I'm writing a Spring MVC application deployed on Tomcat. See the following minimal, complete, and verifiable example
public class Application extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { };
}
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { SpringServletConfig.class };
}
protected String[] getServletMappings() {
return new String[] { "/*" };
}
}
Where SpringServletConfig is
#Configuration
#ComponentScan("com.example.controllers")
#EnableWebMvc
public class SpringServletConfig {
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setPrefix("/WEB-INF/jsps/");
vr.setSuffix(".jsp");
return vr;
}
}
Finally, I have a #Controller in the package com.example.controllers
#Controller
public class ExampleController {
#RequestMapping(path = "/home", method = RequestMethod.GET)
public String example() {
return "index";
}
}
My application's context name is Example. When I send a request to
http://localhost:8080/Example/home
the application responds with an HTTP Status 404 and logs the following
WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI `[/Example/WEB-INF/jsps/index.jsp]` in `DispatcherServlet` with name 'dispatcher'
I have a JSP resource at /WEB-INF/jsps/index.jsp I expected Spring MVC to use my controller to handle the request and forward to the JSP, so why is it responding with a 404?
This is meant to be a canonical post for questions about this warning message.
Your standard Spring MVC application will serve all requests through a DispatcherServlet that you've registered with your Servlet container.
The DispatcherServlet looks at its ApplicationContext and, if available, the ApplicationContext registered with a ContextLoaderListener for special beans it needs to setup its request serving logic. These beans are described in the documentation.
Arguably the most important, beans of type HandlerMapping map
incoming requests to handlers and a list of pre- and post-processors
(handler interceptors) based on some criteria the details of which
vary by HandlerMapping implementation. The most popular implementation
supports annotated controllers but other implementations exists as
well.
The javadoc of HandlerMapping further describes how implementations must behave.
The DispatcherServlet finds all beans of this type and registers them in some order (can be customized). While serving a request, the DispatcherServlet loops through these HandlerMapping objects and tests each of them with getHandler to find one that can handle the incoming request, represented as the standard HttpServletRequest. As of 4.3.x, if it doesn't find any, it logs the warning that you see
No mapping found for HTTP request with URI [/some/path] in DispatcherServlet with name SomeName
and either throws a NoHandlerFoundException or immediately commits the response with a 404 Not Found status code.
Why didn't the DispatcherServlet find a HandlerMapping that could handle my request?
The most common HandlerMapping implementation is RequestMappingHandlerMapping, which handles registering #Controller beans as handlers (really their #RequestMapping annotated methods). You can either declare a bean of this type yourself (with #Bean or <bean> or other mechanism) or you can use the built-in options. These are:
Annotate your #Configuration class with #EnableWebMvc.
Declare a <mvc:annotation-driven /> member in your XML configuration.
As the link above describes, both of these will register a RequestMappingHandlerMapping bean (and a bunch of other stuff). However, a HandlerMapping isn't very useful without a handler. RequestMappingHandlerMapping expects some #Controller beans so you need to declare those too, through #Bean methods in a Java configuration or <bean> declarations in an XML configuration or through component scanning of #Controller annotated classes in either. Make sure these beans are present.
If you're getting the warning message and a 404 and you've configured all of the above correctly, then you're sending your request to the wrong URI, one that isn't handled by a detected #RequestMapping annotated handler method.
The spring-webmvc library offers other built-in HandlerMapping implementations. For example, BeanNameUrlHandlerMapping maps
from URLs to beans with names that start with a slash ("/")
and you can always write your own. Obviously, you'll have to make sure the request you're sending matches at least one of the registered HandlerMapping object's handlers.
If you don't implicitly or explicitly register any HandlerMapping beans (or if detectAllHandlerMappings is true), the DispatcherServlet registers some defaults. These are defined in DispatcherServlet.properties in the same package as the DispatcherServlet class. They are BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping (which is similar to RequestMappingHandlerMapping but deprecated).
Debugging
Spring MVC will log handlers registered through RequestMappingHandlerMapping. For example, a #Controller like
#Controller
public class ExampleController {
#RequestMapping(path = "/example", method = RequestMethod.GET, headers = "X-Custom")
public String example() {
return "example-view-name";
}
}
will log the following at INFO level
Mapped "{[/example],methods=[GET],headers=[X-Custom]}" onto public java.lang.String com.spring.servlet.ExampleController.example()
This describes the mapping registered. When you see the warning that no handler was found, compare the URI in the message to the mapping listed here. All the restrictions specified in the #RequestMapping must match for Spring MVC to select the handler.
Other HandlerMapping implementations log their own statements that should hint to their mappings and their corresponding handlers.
Similarly, enable Spring logging at DEBUG level to see which beans Spring registers. It should report which annotated classes it finds, which packages it scans, and which beans it initializes. If the ones you expected aren't present, then review your ApplicationContext configuration.
Other common mistakes
A DispatcherServlet is just a typical Java EE Servlet. You register it with your typical <web.xml> <servlet-class> and <servlet-mapping> declaration, or directly through ServletContext#addServlet in a WebApplicationInitializer, or with whatever mechanism Spring boot uses. As such, you must rely on the url mapping logic specified in the Servlet specification, see Chapter 12. See also
How are Servlet url mappings in web.xml used?
With that in mind, a common mistake is to register the DispatcherServlet with a url mapping of /*, returning a view name from a #RequestMapping handler method, and expecting a JSP to be rendered. For example, consider a handler method like
#RequestMapping(path = "/example", method = RequestMethod.GET)
public String example() {
return "example-view-name";
}
with an InternalResourceViewResolver
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setPrefix("/WEB-INF/jsps/");
vr.setSuffix(".jsp");
return vr;
}
you might expect the request to be forwarded to a JSP resource at the path /WEB-INF/jsps/example-view-name.jsp. This won't happen. Instead, assuming a context name of Example, the DisaptcherServlet will report
No mapping found for HTTP request with URI [/Example/WEB-INF/jsps/example-view-name.jsp] in DispatcherServlet with name 'dispatcher'
Because the DispatcherServlet is mapped to /* and /* matches everything (except exact matches, which have higher priority), the DispatcherServlet would be chosen to handle the forward from the JstlView (returned by the InternalResourceViewResolver). In almost every case, the DispatcherServlet will not be configured to handle such a request.
Instead, in this simplistic case, you should register the DispatcherServlet to /, marking it as the default servlet. The default servlet is the last match for a request. This will allow your typical servlet container to chose an internal Servlet implementation, mapped to *.jsp, to handle the JSP resource (for example, Tomcat has JspServlet), before trying with the default servlet.
That's what you're seeing in your example.
I resolved my issue when in addition to described before:`
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver vr = new InternalResourceViewResolver();
vr.setPrefix("/WEB-INF/jsps/");
vr.setSuffix(".jsp");
return vr;
}
added tomcat-embed-jasper:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
`
from: JSP file not rendering in Spring Boot web application
In my case, I was following the Interceptors Spring documentation for version 5.1.2 (while using Spring Boot v2.0.4.RELEASE) and the WebConfig class had the annotation #EnableWebMvc, which seemed to be conflicting with something else in my application that was preventing my static assets from being resolved correctly (i.e. no CSS or JS files were being returned to the client).
After trying a lot of different things, I tried removing the #EnableWebMvc and it worked!
Edit: Here's the reference documentation that says you should remove the #EnableWebMvc annotation
Apparently in my case at least, I'm already configuring my Spring application (although not by using web.xml or any other static file, it's definitely programmatically), so it was a conflict there.
Try to amend your code with the following change on your config file. Java config is used instead of application.properties.
Do not forget to enable configuration in configureDefaultServletHandling method.
WebMvcConfigurerAdapter class is deprecated, so we use WebMvcConfigurer interface.
#Configuration
#EnableWebMvc
#ComponentScan
public class WebConfig implements WebMvcConfigurer {
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/views/", ".jsp");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
I use gradle, your should have the following dependencies in pom.xml:
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.3.0.RELEASE'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-jasper', version: '9.0.35'
}
I came across another reason for the same error. This could also be due to the class files not generated for your controller.java file. As a result of which the the dispatcher servlet mentioned in web.xml is unable to map it to the appropriate method in the controller class.
#Controller
Class Controller{
#RequestMapping(value="/abc.html")//abc is the requesting page
public void method()
{.....}
}
In eclipse under Project->select clean ->Build Project.Do give a check if the class file has been generated for the controller file under builds in your workspace.
Clean your server. Maybe delete the server and add the project once again and Run.
Stop the Tomcat server
Right click the server and select "Clean"
Right click server again and select "Clean Tomcat Work Directory"
In my case using a tutorial for SpringBoot(2.7.3) RestController, startup failed with java.lang.ClassNotFoundException: javax.validation.ParameterNameProvider
I thought that Spring REST does not use WebMvc so I removed 'spring-boot-starter-web' and that resolved the startup problem. However, POST requests failed with the '404 Not Found' issue described here and spent several hours experimenting with
server.servlet.context-path
#RestController vs #Controller etc, and
SecurityConfig options
I finally resolved the 404 issue by
restoring dependency 'spring-boot-starter-web'
adding dependency
javax.validation
validation-api
and after undoing my 101 debug hacks it worked.
Very painful because even with root logger at DEBUG, there were no server-side logs to help.
For me, I found that my target classes were generated in a folder pattern not same as source. This is possibly in eclipse I add folders for containing my controllers and not add them as packages. So I ended up defining incorrect path in spring config.
My target class was generating classes under app and I was referring to com.happy.app
<context:annotation-config />
<context:component-scan
base-package="com.happy.app"></context:component-scan>
I added packages (not folders) for com.happy.app and moved the files from folders to packages in eclipse and it resolved the issue.
In my case, I was playing around with import of secondary java config files into a main java config file. While making secondary config files, I had changed the name of the main config class, but I had failed to update the name in web.xml. So, every time that I had restarted my tomcat server, I was not seeing mapping handlers noted in the Eclipse IDE console, and when I tried to navigate to my home page I was seeing this error:
Nov 1, 2019 11:00:01 PM org.springframework.web.servlet.PageNotFound
noHandlerFound WARNING: No mapping found for HTTP request with URI
[/webapp/home/index] in DispatcherServlet with name 'dispatcher'
The fix was to update the web.xml file so that the old name "WebConfig" would be instead "MainConfig", simply renaming it to reflect the latest name of the main java config file (where "MainConfig" is arbitrary and the words "Web" and "Main" used here are not a syntax requirement). MainConfig was important, because it was the file that did the component scan for "WebController", my spring mvc controller class that handles my web requests.
#ComponentScan(basePackageClasses={WebController.class})
web.xml had this:
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.lionheart.fourthed.config.WebConfig
</param-value>
</init-param>
web.xml file now has:
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.lionheart.fourthed.config.MainConfig
</param-value>
</init-param>
Now I am seeing the mapping in the console window:
INFO: Mapped "{[/home/index],methods=[GET]}" onto public
org.springframework.web.servlet.ModelAndView
com.lionheart.fourthed.controller.WebController.gotoIndex()
And my web page is loading again.
In my case, I had created Config.java (class) and also config.xml and mapping was done partially in both of them. And since config.java uses #Configuration annotation , it was considered priority. And was not considering config.xml.
If anyone gets in trouble like this , just delete config.java with annotation and try to keep config.xml , it works fine.
For me, the issue was hidden in the web.xml file.
Inside the servlet tag, you'll find:
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/todo-servlet.xml</param-value>
</init-param>
Make sure that in the <param-value> you have kept the correct location of the dispatcher servlet (aka Front Controller).
I had kept an incorrect location, hence I was able to view the homepage but all other pages were giving HTTP 404 error.
I had same problem as **No mapping found for HTTP request with URI [/some/path] in DispatcherServlet with name SomeName**
After I analyzed for 2 to 4 days I found out the root cause. Class files was not generated after I run the project. I clicked the project tab.
Project-->CloseProject-->OpenProject-->Clean-->Build project
Class files for source code have been generated. It solved my problem. To check whether class files have been generated or not, Please check the Build folder in your project folder.
So the problem can be as simple as an additional space in the path of the project. Make sure that there is no space in the path which took me quite some time to solve.
Let's assume I have Spring Rest API called application and its requests mapped on /api . It means I call for example GET method to get list of users:
localhost:8080/application/api/users
Working well. My goal is to have simple static html files alongside this API able to refer to each other. I need to find the index.html file and make it as the homepage.
localhost:8080/application/
It correctly shows me index.html using:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String homePage(ModelMap model) {
return "home";
}
and
#Configuration
#ComponentScan(basePackages = "net.nichar.application")
#EnableWebMvc
public class ApplicationConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".html");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
Where I struggle is to navigate with <a href=...> over another files in the same folder index2.html, index3.html without need to explicitely write the suffix html. I try to achieve to access the webpages like
localhost:8080/application/index2
without using another #RequestMapping (except the first one mapping the home page).
One more question, is there a way to "skip" a folder in the path navigation? For clarity, I want to put these html files to webapp/static folder, however I have to access them like
localhost:8080/application/static/...
I have tried to follow a number of tutorials shortly about the Spring resources mapping, however noone of them described the solution of any similar problem. I don't use Spring Boot.
Thank you for any help.
Shortly:
How to access files in --> with:
webapp/WEB-INF/pages/index.html --> localhost:8080/application
webapp/static/index2.html --> localhost:8080/application/index2
webapp/static/index3.html --> localhost:8080/application/index3
You can use something like that,
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/welcome").setViewName("welcome");
registry.addViewController("/about").setViewName("about");
registry.addViewController("/contact").setViewName("contact");
}
where login is mapped to login.html, and welcome is mapped welcome.html. It does not require #RequestMapping, but still require an explicit mapping.
The Problem
My spring-boot application recently changed routing from host/endpoint to host/middle/endpoint. Since the change, I am running into an issue where the resources are not being found relative to the new url structure. Before, I could reference resources like css stylesheets like link(rel='stylesheet', href='css/style.css'), but now the logger shows an error saying it can't find the resource at /middleman/css/style.css.
From my research, I have found that what I need to do is use a resource handler registry. I have created one (as shown below) but it doesn't seem to be working. I think the problem is that even though I now have the resource registry, I am not referencing resources in the registry. What is the proper way to solve this problem and have all resources point load from the same place regardless of the endpoint? I very well may be missing some obvious piece of SOP
Note: This is all a dumbed down representation of my project in order to give the idea of what is going on without giving unnecessary information.
Project Structure
src
main
java
com.mystuff.cool
configurations
ResourceConfiguration.java
controllers
RoutingController.java
application
Application.java
resources
static
css
footer.css
style.css
images
place1.png
location1.png
spot1.png
favicon.ico
javascripts
layout.js
templates
home.jade
Application Class
#ComponentScan(basePackages = {"my.packages"})
#EnableAutoConfiguration
#EnableSAMLSSO
#Configuration
public class Application
{
public static void main(String[] args)
{
SpringApplication.run(new Object[]{ Application.class, ServiceConfig.class, ResourceConfiguration.class}, args);
}
}
Resource Configuration
#EnableWebMvc
#Configuration
public class ResourceConfiguration extends WebMvcConfigurerAdapter
{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}
Controller
#Controller
public class RoutingController
{
#RequestMapping("/house/home")
public String home(Model model)
{
model.addAttribute("title", "Home is where the heart is");
commonModelTribs(model);
return "home";
}
}
Home Page
doctype html
html
title Place-spedia #{title}
link(rel='icon', href='images/favicon.ico')
link(rel='stylesheet', href='css/style.css')
script(src='javascripts/layout.js')
link(rel='stylesheet', href='css/footer.css')
body
div#footer-icons
a(href='place1')
img#place1(src="images/place1.png")
a(href='location1')
img#location1(src="images/location1.png")
a(href='spot1')
img#spot1(src='images/spot1.png')
If you are using spring boot, you don't need to worry about the resource configuration since you are already configuring the resource directory through the auto configuration. The default behavior for the autoconfiguration is to look within resources/static.
Your issue is with your href values, try inserting a leading forward slash:
link(rel='icon', href='/images/favicon.ico')
link(rel='stylesheet', href='/css/style.css')
script(src='javascripts/layout.js')
link(rel='stylesheet', href='/css/footer.css')
Spring is routing your application to a new relative path, so by putting the leading / in your href attributes, you are telling the router to look absolutely within the static directory instead of relatively from the middle directory.
I am developing a website with Spring, and am trying to serve resources that are not .jsp files (.html for example)
right now i have commented out this part of my servlet configuration
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
And tried to return fromthe controller the full path to the resource.
#Controller
public class LandingPageController {
protected static Logger logger = Logger.getLogger(LandingPageController.class);
#RequestMapping({"/","/home"})
public String showHomePage(Map<String, Object> model) {
return "/WEB-INF/jsp/index.html";
}
}
the index.html file exists in that folder.
NOTE: when I change the index.html to index.jsp my server now serves the page correctly.
Thank you.
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.
I'd just add that you don't need to implement a controller method for that as you can use the view-controller tag (Spring 3) in the servlet configuration file:
<mvc:view-controller path="/" view-name="/WEB-INF/jsp/index.html"/>
Background of the problem
First thing to understand is following: it is NOT spring which renders the jsp files. It is JspServlet (org.apache.jasper.servlet.JspServlet) which does it. This servlet comes with Tomcat (jasper compiler) not with spring. This JspServlet is aware how to compile jsp page and how to return it as html text to the client. The JspServlet in tomcat by default only handles requests matching two patterns: *.jsp and *.jspx.
Now when spring renders the view with InternalResourceView (or JstlView), three things really takes place:
get all the model parameters from model (returned by your controller handler method i.e. "public ModelAndView doSomething() { return new ModelAndView("home") }")
expose these model parameters as request attributes (so that it can be read by JspServlet)
forward request to JspServlet. RequestDispatcher knows that each *.jsp request should be forwarded to JspServlet (because this is default tomcat's configuration)
When you simply change the view name to home.html tomcat will not know how to handle the request. This is because there is no servlet handling *.html requests.
Solution
How to solve this. There are three most obvious solutions:
expose the html as a resource file
instruct the JspServlet to also handle *.html requests
write your own servlet (or pass to another existing servlet requests to *.html).
For complete code examples how to achieve this please reffer to my answer in another post: How to map requests to HTML file in Spring MVC?
You can still continue to use the same View resolver but set the suffix to empty.
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix="" />
Now your code can choose to return either index.html or index.jsp as shown in below sample -
#RequestMapping(value="jsp", method = RequestMethod.GET )
public String startJsp(){
return "/test.jsp";
}
#RequestMapping(value="html", method = RequestMethod.GET )
public String startHtml(){
return "/test.html";
}
I faced the same issue and tried various solutions to load the html
page from Spring MVC, following solution worked for me
Step-1 in server's web.xml comment these two lines
<!-- <mime-mapping>
<extension>htm</extension>
<mime-type>text/html</mime-type>
</mime-mapping>-->
<!-- <mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
-->
Step-2 enter following code in application's web xml
<servlet-mapping>
<servlet-name>jsp</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
Step-3 create a static controller class
#Controller
public class FrontController {
#RequestMapping("/landingPage")
public String getIndexPage() {
return "CompanyInfo";
}
}
Step-4 in the Spring configuration file change the suffix to .htm
.htm
Step-5 Rename page as .htm file and store it in WEB-INF and build/start the server
localhost:8080/.../landingPage
Java configuration for html files (in this case index.html):
#Configuration
#EnableWebMvc
public class DispatcherConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/index.html").addResourceLocations("/index.html");
}
}
change p:suffix=".jsp" value acordingly otherwise we can develope custom view resolver
http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/UrlBasedViewResolver.html
It sounds like you are trying to do something like this:
Static HTML views
Spring controllers serving AJAX
If that is the case, as previously mentioned, the most efficient way is to let the web server(not Spring) handle HTML requests as static resources. So you'll want the following:
Forward all .html, .css, .js, .png, etc requests to the
webserver's resource handler
Map all other requests to spring controllers
Here is one way to accomplish that...
web.xml - Map servlet to root (/)
<servlet>
<servlet-name>sprung</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
...
<servlet>
<servlet-mapping>
<servlet-name>sprung</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring JavaConfig
public class SpringSprungConfig extends DelegatingWebMvcConfiguration {
// Delegate resource requests to default servlet
#Bean
protected DefaultServletHttpRequestHandler defaultServletHttpRequestHandler() {
DefaultServletHttpRequestHandler dsrh = new DefaultServletHttpRequestHandler();
return dsrh;
}
//map static resources by extension
#Bean
public SimpleUrlHandlerMapping resourceServletMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
//make sure static resources are mapped first since we are using
//a slightly different approach
mapping.setOrder(0);
Properties urlProperties = new Properties();
urlProperties.put("/**/*.css", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.js", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.png", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.html", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.woff", "defaultServletHttpRequestHandler");
urlProperties.put("/**/*.ico", "defaultServletHttpRequestHandler");
mapping.setMappings(urlProperties);
return mapping;
}
#Override
#Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
//controller mappings must be evaluated after the static resource requests
handlerMapping.setOrder(1);
handlerMapping.setInterceptors(this.getInterceptors());
handlerMapping.setPathMatcher(this.getPathMatchConfigurer().getPathMatcher());
handlerMapping.setRemoveSemicolonContent(false);
handlerMapping.setUseSuffixPatternMatch(false);
//set other options here
return handlerMapping;
}
}
Additional Considerations
Hide .html extension - This is outside the scope of Spring if you are delegating the static resource requests. Look into a URL rewriting filter.
Templating - You don't want to duplicate markup in every single HTML page for common elements. This likely can't be done on the server if serving HTML as a static resource. Look into a client-side *VC framework. I'm fan of YUI which has numerous templating mechanisms including Handlebars.
In case you use spring boot, you must not set the properties spring.mvc.view.prefix and spring.mvc.view.suffix in your application.properties file, instead configure the bean ViewResolver from a configuration class.
application.properties
# Configured in #Configuration GuestNav
#spring.mvc.view.prefix=/WEB-INF/views/
#spring.mvc.view.suffix=.jsp
# Live reload
spring.devtools.restart.additional-paths=.
# Better logging
server.tomcat.accesslog.directory=logs
server.tomcat.accesslog.file-date-format=yyyy-MM-dd
server.tomcat.accesslog.prefix=access_log
server.tomcat.accesslog.suffix=.log
Main method
#SpringBootApplication
public class WebApp extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(WebApp.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(WebApp.class, args);
}
}
Configuration class
#Configuration
#EnableWebMvc
public class DispatcherConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/views/**").addResourceLocations("/views/");
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/notinuse/");
viewResolver.setSuffix("");
return viewResolver;
}
}
A controller class
#Controller
public class GuestNav {
#GetMapping("/")
public String home() {
return "forward:/views/guest/index.html";
}
}
You must place your files in the directory /webapp/views/guest/index.html, be careful, the webapp directory is outside of the resources directory.
In this way you may use the url patterns of spring-mvc but serve static context.