Request Mapping returning error 404 - spring

This is my controller that maps a request to this url http://localhost:8080/SpringMVCJSON/rest/kfc/brands
contoller file
#Controller
#RequestMapping("/kfc/brands")
public class JSONController {
#RequestMapping(value = "{name}", method = RequestMethod.GET)
public #ResponseBody
Shop getShopInJSON(#PathVariable String name) {
Shop shop = new Shop();
shop.setName(name);
shop.setStaffName(new String[] { "name1", "name2" });
return shop;
}
this is the web.xml with the servlet request that dispatches the request/response along with the url
<display-name>Spring Web MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Assuming that everything is alright, when I launch my app on this url it returns error 404 http://localhost:8080/SpringMVCJSON/rest/kfc/brands
My server console returns this warning
Apr 26, 2016 12:14:47 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringMVCJSON/rest/kfc/brands] in DispatcherServlet with name 'mvc-dispatcher'
Please why is tomcat not mapping request to the server?

You configured your controller to be available on /kfc/brands/{name} URL but trying to access it on /kfc/brands.
Here you can find more information about using #RequestMapping: http://docs.spring.io/autorepo/docs/spring/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping

Related

404 Error from REST Endpoint in SpringMVC for DispatcherServlet

RESOLVED PER THIS ANSWER
Spring invokes wrong controller mapping
Spring #Controllers URLs are always interpreted relative the the Spring Dispatcher Servlet that handles them. So if you map the dispatcher servlet to /api/ in web.xml then the URL to your controller above is /api/api/choice
The double string service/service/1234 was working.
ORIGINAL POST
Accessing a REST resource endpoint gives me a 404 error although everything seems to be defined correctly:
Log output:
DEBUG DispatcherServlet with name 'mvc-dispatcher' processing GET request for [/myapp/service/1234]
DEBUG Looking up handler method for path /1234
DEBUG Did not find handler method for [/1234]
WARN No mapping found for HTTP request with URI [/myapp/service/1234] in DispatcherServlet with name 'mvc-dispatcher'
web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
SpringMVC Controller
#RestController
#RequestMapping("/service")
public class RESTController {
#RequestMapping(value="/{id}", method=RequestMethod.GET)
public String getResult ( #PathVariable String id )
{
//... get JSON result
}
}
Expected invocation: myapp/service/1234
Also tried these options:
1) Don't define a class RequestMapping, just do a Method Request Mapping
#RequestMapping("/service/{id}")
2) as well as
#RequestMapping("/service*/{id}")
#RequestMapping("/service**/{id}")
Keep getting a 404 with the log above.
update your web.xml file :
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

404 error with "/" request

ihave a problem with my project yous when i put: http://localhost:8080/yous/cc it's works but with http://localhost:8080/yous/ i got 404 error
déc. 26, 2013 8:37:26 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
Avertissement: No mapping found for HTTP request with URI [/yous/] in DispatcherServlet with name 'appServlet'
My controller:
#RequestMapping(value = "/cc")
public String printWelcome() {
System.out.println("Hello");
return "/WEB-INF/pages/hello.jsp";
}
#RequestMapping(value = "/")
public String printIndex() {
return "index.html";
}
My web.xml
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>appServlet-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
my appServlet-servlet.xml
<context:component-scan base-package="controller"/>
<mvc:annotation-driven />
We resolve the problem with
#RequestMapping(value="/index")
It seems that /index handle /, can somebody explain me why ?

how to handle url that are not mapped in spring

My dispatcher servlet mapping
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springconfig/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
And the controller has handler like
#RequestMapping("moduleone")
public class ApplicationController {
#RequestMapping(value="Login.html",method=RequestMethod.GET)
public ModelAndView showLoginPage(){
ModelAndView mv=new ModelAndView("../moduleone/Login");
mv.addObject("loginForm", new LoginForm());
return mv;
}
#RequestMapping(value="Home.html", method = RequestMethod.GET)
public ModelAndView showHome(HttpServletRequest request) {
ModelAndView mv=new ModelAndView("Home");
mv.addObject("customerName",appCon.getFirstName() );
return mv;
}
}
Is it possible to handler request that are not mapped in controller
like
http://localhost:8090/Project/moduleone/invalidpage.html
http://localhost:8090/Project/moduleone/invalidurl/invalidpage
I have tried #RequestMapping(value="*",method=RequestMethod.GET) but doest work
As 404 (page not found) actually produces an exception on web container level, containers usually provide an exception handling mechanism, thus you can try exception (or so called error) handling, as shown below;
First create a controller
#Controller
public class PageNotFoundErrorController {
#RequestMapping(value="/pageNotFound.html")
public String handlePageNotFound() {
// do something
return "pageNotFound";
}
}
and configure web.xml in order to map the error to the controller written above;
<error-page>
<error-code>404</error-code>
<location>/pageNotFound.html</location>
</error-page>
you can also extend it by simply adding 403, 500 and other error-codes to web.xml and mapping them to any controller.
What is even more fascinating is that you can also map any exception (even the ones created by your code); here you can find a nice example about it http://www.mkyong.com/spring-mvc/spring-mvc-exception-handling-example/
I try the code block and if change your scenario a bit i can handle it.
//This one is OK
http://localhost:8090/Project/moduleone/invalidpage.html
//add invalid.html not a folder it should be file
http://localhost:8090/Project/moduleone/invalidurl/invalidpage.html
HomeController.java
#RequestMapping(value = {"*/*.html","*.html"}, method = RequestMethod.GET)
public String test(HttpServletResponse response) throws IOException {
return new String("home");
}
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>TestSpringMVC</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springconfig/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
I can handle both request with this way.
I think you should define an exception page for your second scenario.
Also you can read this issue

Custom HTTP Error 404 - Annotation based setting Spring 3.2

Is it possible to implement annotation based custom HTTP 404 error page using Spring 3.2.1?
I looked for ways in various forums but couldn't find any clear answer.
I also tried configuring using web.xml but it is not working when I access unmapped URL.
Any help please?
Log output
7259 [DEBUG] org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'spring-test' processing GET request for [/spring-test/ss]
7261 [DEBUG] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /ss
7262 [DEBUG] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Did not find handler method for [/ss]
7262 [WARN ] org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/spring-test/ss] in DispatcherServlet with name 'spring-test'
7262 [DEBUG] org.springframework.web.servlet.DispatcherServlet - Successfully completed request
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="rest" version="3.0" metadata-complete="true">
<!-- The definition of the Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>main.java.net.bornil.config</param-value>
</context-param>
<!-- Processes application requests -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>main.java.net.bornil.config</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file />
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/errors/404</location>
</error-page>
</web-app>
Controller
#Controller
#RequestMapping(value = "/errors")
public class CommonExceptionHandler {
private static Logger log = Logger.getLogger(CommonExceptionHandler.class.getName());
#RequestMapping(method = RequestMethod.GET, value = "/{code}")
public ModelAndView handleException(#PathVariable int code) {
if (log.isDebugEnabled()) {
log.debug("ERROR CODE IS: " + code);
}
return new ModelAndView("errors/404");
}
}
I had the same issue. I've a simple webapp, single page and, after spending a morning on the Spring forum (so nice you cannot search '404' there because it's just 3 chars long) and Google this is the best solution I found.
Assuming you have a index.jsp and a 404.jsp, my #Configuration' has:
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/*").setViewName("404");
}

How can I redirect the user to a servlet instead of an index file on initial page load?

Here is what I have configured in web.xml :
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
But if I change it to a servlet :
<welcome-file-list>
<welcome-file>myservlet</welcome-file>
</welcome-file-list>
I receive a 404 error message.
How can I redirect the user to a servlet instead of an index file on initial page load ?
THe servlet is based on Spring :
#Controller
public class MyController {
#RequestMapping(value="redirect")
public String displaySearch(Model model) {
model.addAttribute("test" , "test");
return "mypage";
}
}
I just need the "redirect" servlet to be invoked by default.
Edit : the spring dispatcher servlet is mapped on the '/' url pattern, is this incorrect also ?
<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>
Via a servlet mapping, e.g.:
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

Resources