Spring Controller用于处理与其他控制器不匹配的所有请求 [英] Spring Controller to handle all requests not matched by other Controllers

查看:185
本文介绍了Spring Controller用于处理与其他控制器不匹配的所有请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列带有请求映射的控制器,它们匹配某些URL。我还想要一个控制器,它将匹配其他控制器不匹配的任何其他URL。
有没有办法在Spring MVC中执行此操作?例如,我可以使用带有@RequestMapping(value =**)的控制器并更改Spring控制器的处理顺序,以便最后处理此Controller以捕获所有不匹配的请求吗?或者有另一种方法来实现这种行为吗?

I have a series of Controllers with Request Mappings that match certain URL's. I also want a Controller that will match any other URL not matched by the other Controllers. Is there a way to do this in Spring MVC? For example, could i have a controller with @RequestMapping(value="**") and change the order in which Spring Controllers are processed so this Controller is processed last to catch all unmatched requests? Or is there another way to achieve this behaviour?

推荐答案

如果你的基本网址是这样的= http:// localhost / myapp / 其中myapp是你的上下文,然后myapp / a.html,myapp / b.html myapp / c.html将被映射到以下控制器中的前3个方法。但其他任何东西都会达到匹配**的最后一种方法。请注意,如果您将**映射方法放在控制器的顶部,那么所有请求都将达到此方法。

If your base url is like that= http://localhost/myapp/ where myapp is your context then myapp/a.html, myapp/b.html myapp/c.html will get mapped to the first 3 method in the following controller. But anything else will reach the last method which matches **. Please note that , if you put ** mapped method at the top of your controller then all request will reach this method.

然后此控制器将满足您的要求:

Then this controller servrs your requirement:

@Controller
@RequestMapping("/")
public class ImportController{

    @RequestMapping(value = "a.html", method = RequestMethod.GET)
    public ModelAndView getA(HttpServletRequest req) {
        ModelAndView mv;
        mv = new ModelAndView("a");
        return mv;
    }

    @RequestMapping(value = "b.html", method = RequestMethod.GET)
    public ModelAndView getB(HttpServletRequest req) {
        ModelAndView mv;
        mv = new ModelAndView("b");
        return mv;
    }

    @RequestMapping(value = "c.html", method = RequestMethod.GET)
    public ModelAndView getC(HttpServletRequest req) {
        ModelAndView mv;
        mv = new ModelAndView("c");
        return mv;
    }

@RequestMapping(value="**",method = RequestMethod.GET)
public String getAnythingelse(){
return "redirect:/404.html";
}

这篇关于Spring Controller用于处理与其他控制器不匹配的所有请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆