Related
I just started learning spring boot and learned about rest services.
I have a doubt that how spring is so fast to find that exact path('') class file in multiple jars.
Like I am sure it does not traverse the whole codebase. So does it maintain an index file with every URL and class file name?
Example: Below is given index function which is present in TestController.java file which should be called when /index is called. But if I have multiple jars in my project how the Spring knows that a getMapping of Greetings is defined in that class.
package com.example.springboot;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloController {
#GetMapping("/Greetings")
public String index() {
return "Greetings from Spring Boot!";
}
}
when you start spring boot application it scans for the classes which are annotated with stereotype annotation like #Controller, #Restcontroller,#Bean,#service.
when a class is annotated with #Controller it means it handles web requests. After the component scan it creates a bean for that class and stores it in spring Ioc container.
when a web request is made to the server it looks for the requested url is presented in that bean and serves the request.
A Bean is a simple object of that class.
I'm working in Spring Framework 5 in Eclipse and I need to add a prefix to many of my #RestControllers, so I found that placing this: #RequestMapping("${foo.bar}") at the beginning of the class and adding a new file application.properties to main/java/resources will solve my problem.
The content of application.properties is:
foo.bar=/test
But it doesn't work because when I try to access on my web explorer to: localhost:8080/project/test I get a 404 Error. It works only if I access with localhost:8080/project/$%7Bfoo.bar%7D. I really don't know what I'm doing wrong. I don't know if Spring will detect automatically the properties file or not.
Can someone help me?
The values from the properties file are accessed from the spring bean. But the #Restcontroller is used to register the bean that provides the restful service.
And for request mapping the controller, you just have to hardcode the value like this as at this point you can't get the message resource object yet.
#RestController
#RequestMapping(value = "/test")
Just for the information, to access labels from the properties file inside the controller you have to #Autowired a MessageResource object in the RestController
#Autowired
private MessageResource;
and access the labels of the properties file like this in any of the controller methods.
message = messageResource.getMessage("foo.bar");
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.
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.
I have a following project structure
-Project
|-config
| |-modules
| |-admin
| |-web
|- platform
Platform is the project that contains the spring-boot start class,
Platform has a dependency on config and config had dependencies on everything in the directory modules
Platform is also the module that gets started with the mvn spring-boot:run command.
The thing I am trying to accomplish is that the modules admin and web (both web apps) have their own mapping like
/admin
/web
The following code represents an controller in the admin module, the web module also contains a similar controller (thats the point)
#Controller
public class AdminController {
#RequestMapping("/")
public String adminController() {
return "admin";
}
}
Here some code for the configuration of the admin module
#Configuration
public class Config implements EmbeddedServletContainerCustomizer {
#Autowired
protected WebApplicationContext webApplicationContext;
#Autowired
protected ServerProperties server;
#Autowired(required = false)
protected MultipartConfigElement multipartConfig;
protected DispatcherServlet createDispatcherServlet() {
AnnotationConfigEmbeddedWebApplicationContext webContext = new AnnotationConfigEmbeddedWebApplicationContext();
webContext.setParent(webApplicationContext);
webContext.scan("some.base.package");
return new DispatcherServlet(webContext);
}
protected ServletRegistrationBean createModuleDispatcher(DispatcherServlet apiModuleDispatcherServlet) {
ServletRegistrationBean registration =
new ServletRegistrationBean(apiModuleDispatcherServlet,
"/admin");
registration.setName("admin");
registration.setMultipartConfig(this.multipartConfig);
return registration;
}
#Bean(name = "adminsServletRegistrationBean")
public ServletRegistrationBean apiModuleADispatcherServletRegistration() {
return createModuleDispatcher(createDispatcherServlet());
}
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setContextPath("/admin");
}
}
Something similar goes for the web module
I have tried the implement the some of the given answers.
Using multiple dispatcher servlets / web contexts with spring boot
Spring Boot (JAR) with multiple dispatcher servlets for different REST APIs with Spring Data REST
And lots of googling
When I let the component scan, scan both modules (removing the ComponentScan filter)
I get an a Ambiguous mapping found exception, saying that both controller methods dispatch to the same path "/"
But when disabling the component scan on one of the modules, then indeed the admin modules get mapped to /admin.
when I disable both controllers, I see that the /web and /admin dispatchServlets get mapped.
So I understand the exception but I dont understand how to resolve this.
For me its a must that I can do this per module and I dont want to map it using
#RequestMapping("/admin")
on the controller class
I also tried specifying the contextPath and servletPath in the application.properties
So my question is: what would be the best approach to reach my goal, or am I trying to use spring-boot for something it was not ment for.
Edit
A Proof of concept would be nice
So I found the solution.
You can take a look here at this link
You`ll have to register the dispatcher servlets in the main application and dont use the #SpringBootApplication annotation.
For a complete example just checkout the project and check the code
EDIT: later this week ill provide a detailed answer
What you should do is that put your AdminController and WebController in separate packages.
some.base.admin.package
some.base.web.package
And in the corresponding configurations scan only your required package to register the DispatcherServlet
Admin Config
webContext.scan("some.base.admin.package");
Web Config
webContext.scan("some.base.web.package");
This way in the corresponding WebApplicationContext for each DispatcherServlet only one mapping will be available for "/"