Java – spring MVC @ requestmapping does not work
I have a strange situation where my controller is not invoked unless I map the scheduler servlet to the web / *. In XML I have defined a controller with requestmapping:
@Controller public class UserController { @RequestMapping(value = "/rest/users",method = RequestMethod.GET) public ModelAndView getUsers(HttpServletRequest request) throws RestException { ... } }
And application context:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> <context:component-scan base-package="com.test.rest.controller" />
Finally, this is mapped to the web In XML:
<servlet> <servlet-name>rest-servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/restContext.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>rest-servlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
This can work as expected and I can request / rest / users But if I put the web XML Mapping changed to:
<servlet-mapping> <servlet-name>rest-servlet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping>
I got an MVC error:
It seems strange because the error indicates that the request is mapped to the scheduler servlet, but the only way to change is the servlet mapping
Has anyone met this?
Solution
Dispatcher servlet is the main servlet of spring MVC It processes all requests, comes to your application, and sends them to the controller using its own routing engine If you change it
<url-pattern>/rest/*</url-pattern>
Then your request should rest / rest / user like this
Generic mode – allows the scheduling servlet to handle all incoming requests (the first configuration is valid)