是否可以在 Spring MVC 中动态设置 RequestMappings? [英] Is it possible to dynamically set RequestMappings in Spring MVC?

查看:49
本文介绍了是否可以在 Spring MVC 中动态设置 RequestMappings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 Spring MVC 三个月了.我正在考虑一种动态添加 RequestMapping 的好方法.这是因为需要将控制器部件放入库中,然后动态地添加它们.无论如何,我能想到的唯一方法就是像这样声明一个控制器:

I've been using Spring MVC for three months now. I was considering a good way to dynamically add RequestMapping. This comes from the necessity to put controller parts in a library and then add them dinamically. Anyway, the only way I can think of is to declare a controller like this:

@Controller
@RequestMapping("/mypage")
public class MyController {

@RequestMapping(method = RequestMethod.GET)
    public ModelAndView mainHandler(HttpServletRequest req) {
        return handleTheRest(req);
    }

}

这不好,因为基本上我没有使用 Spring.然后我不能使用表单绑定、注释等.我想动态地将 requestMappings 添加到可以像通常的 MVC 控制器一样注释的类的方法中,使用自动绑定,这样我就可以避免手动处理 HttpServletRequest.

Which is no good because basically I'm not using Spring. Then I cannot use form binding, annotations etc.. I'd like to add requestMappings dynamically to methods of classes that could be annotated like usual MVC controllers, with autobinding, so that I could avoid processing HttpServletRequest manually.

有什么想法吗?}

推荐答案

Spring MVC 使用 HandlerMapping 接口.通常开箱即用的是默认实现,即SimpleUrlHandlerMappingBeanNameUrlHandlerMappingDefaultAnnotationHandlerMapping.

Spring MVC performs URL mappings using implementations of the HandlerMapping interface. The ones usually used out of the box are the default implementations, namely SimpleUrlHandlerMapping, BeanNameUrlHandlerMapping and DefaultAnnotationHandlerMapping.

如果你想实现你自己的映射机制,这很容易做到——只需实现那个接口(或者,也许更有可能,扩展 AbstractUrlHandlerMapping),在你的上下文,当需要映射请求时,DispatcherServlet 会参考它.

If you want to implement your own mapping mechanism, this is fairly easy to do - just implement that interface (or, perhaps more likely, extend AbstractUrlHandlerMapping), declare the class as a bean in your context, and it will be consulted by DispatcherServlet when a request needs to be mapped.

请注意,您可以在一个上下文中拥有任意数量的 HandlerMapping 实现.将轮流咨询他们,直到其中一个匹配.

Note that you can have as many HandlerMapping implementations as you like in the one context. They will be consulted in turn until one of them has a match.

这篇关于是否可以在 Spring MVC 中动态设置 RequestMappings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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