Unable to find controller in spring web mvc
Solution 1
You have to enable MVC in Spring. In xml config you can do it in such way:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
</beans>
and in JavaConfig:
@Configuration
@EnableWebMvc
public class WebConfig {
}
Please refer to Spring documentation
Solution 2
if you are referring to an mkyong tutorial, I didn't use the annotations: @Configuration @EnableWebMvc, problem is you are using both annotations and xml declaration.
Annotation for setting the url:
@Controller
@RequestMapping("/hello")
you should remove this part:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
and you'll be able to visit the url:
http://localhost:8080/SpringMiddle/hello
Also make sure you have this in your web.xml:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
the dispatcher-servlet.xml is where the component scanning is declared
Ritesh
Updated on June 04, 2022Comments
-
Ritesh about 2 years
It seems that dispatcher-servlet unable to perform component scan using.
<context:component-scan base-package="abc" />
In my controller file (HelloController.java) under package abc. Code is written as follows:
@Controller @RequestMapping("/hello") public class HelloController { @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute("message", "Hello Spring MVC Framework!"); return "hello"; //I have already made hello.jsp in web-inf/jsp/ } }
My Application name is SpringMiddle. When try url as:
http://localhost:8080/SpringMiddle/hello.htm
I do have following url pattern in web.xml
<servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>
It shows me error HTTP 404 not found.
EDIT: : it shows me warning
WARNING: No mapping found for HTTP request with URI [/SpringMiddle/hello.htm] in DispatcherServlet with name 'dispatcher'