Search code examples
springspring-mvcurl-mapping

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


Solution

  • 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/