Spring MVC dynamic view + handling non existing vi

2019-07-25 13:57发布

问题:

I'm going to implement a Spring MVC controller which uses dynamic view passed as a parameter to view:

@Controller
@RequestMapping("/page")
public class PageController  {

    @RequestMapping(value = "/{page}", method = {RequestMethod.GET})
    public ModelAndView page(@PathVariable("page")String page) {
        System.out.println("page = " + page);

        return new ModelAndView(page);
    }
}

Views are resolved by UrlBasedViewResolver:

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
    <property name="cache" value="false"/>
</bean> 

Is there any way to return a default view when non-existing view requested? Maybe to do check if there's no view exists, then return new ModelAndView('requested_page_not_found')?

回答1:

Not with UrlBasedViewResolver and friends. Once the chain has reached it, you're committed -- if the view doesn't exist, you're going to be directed to whatever 404 page your container has configured.

Note: When chaining ViewResolvers, a UrlBasedViewResolver always needs to be last, as it will attempt to resolve any view name, no matter whether the underlying resource actually exists.