I have written a web application using spring mvc 3. It provides a single endpoint that returns JSON. I did having it running successfully using url paramters but now I need to change this to use path variables instead.
I changed my controller
from:
@Controller
public class DataController {
@Autowired
private IDataService dateService;
@RequestMapping(
value = "/some/data",
method = RequestMethod.GET,
produces = "application/json"
)
public @ResponseBody Data getDataByCode(@RequestParam String code) {
return versionService.getDataByCode(code);
}
}
to:
@Controller
public class DataController {
@Autowired
private IDataService dateService;
@RequestMapping(
value = "/some/data/{code}",
method = RequestMethod.GET,
produces = "application/json"
)
public @ResponseBody Data getDataByCode(@PathVariable String code) {
return versionService.getDataByCode(code);
}
}
and my web xml to map the url...
from:
<servlet>
<servlet-name>dataBycode</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/servlet-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dataBycode</servlet-name>
<url-pattern>/some/data</url-pattern>
</servlet-mapping>
to:
<servlet>
<servlet-name>dataBycode</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/servlet-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dataBycode</servlet-name>
<url-pattern>/some/data/*</url-pattern>
</servlet-mapping>
But I get a 404 for the http request: http://localhost/some/data/1234
Where I know that 1234 exists.
To top it off, the request never even gets to the controller method, so its got to be the web xml url pattern configuration.
As a test I tried changing the url pattern to exactly match a request with a code and it returned JSON as expected, so I know its the url pattern. I just dont know how to fix it.
I have tried:
Your url-pattern should be:
<servlet-mapping>
<servlet-name>dataBycode</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
In the second hand, can you try to access http://localhost/some/data/myTest and put a System.out.println in your getDataByCode method to see if the method is called.
If it works I think the problem come from Spring MVC which interprate "1234" as an integer and not a String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With