我有一个 Spring mvc (3.1.1) 应用程序,我想定义 RequestMapping 中可用的条件之外的条件。我有几件事想用它来做。
首先,如果我可以为不同的用户类型显示不同的主页,那就太好了:
@Controller
public class HomepageController {
@RequestMapping(value = "/")
@CustomCondition(roles = Guest.class)
public String guestHome() { /*...*/ }
@RequestMapping(value = "/")
@CustomCondition(roles = Admin.class)
public String adminHome() { /*...*/ }
}
其次,我希望该应用程序既可以用作网站又可以用作 REST 服务(例如对于移动应用程序),所以我想让该网站同时访问 html 和 json 操作,并且只允许该服务(不同的子域)访问 json 操作(某种
@CustomCondition(web = true)
仅匹配网站网址)这可以用于我计划的两种用途中的任何一种吗?
我发现关于自定义条件的文档很少,但我确实找到了 one example那个implements custom conditions这可能是我想要的,但它使用了
@Configuration
类而不是我正在使用的 XML 配置,我不想将我的整个 spring xml 定义移动到 @Configuration
类(class)。我可以为
RequestMappingHandlerMapping
定义一个 customMethodCondition 吗?在 XML 中?我尝试子类化
RequestMappingHandlerMapping
并覆盖 getCustomMethodCondition
, 返回我的自定义 RequestCondition
,但它没有用 - getMatchingCondition()
在我的情况下没有开火。任何帮助将不胜感激!
更新
我读了一点,它看起来像
RequestMappingHandlerMapping
是一个新类(自 3.1 版起)。我的应用程序中发生的事情是 @Configuration 试图覆盖并重新定义
requestMappingHandlerMapping
bean 实际上有效,但是 url 映射(@RequestMapping
s 中的 @Controller
方法)似乎被处理了两次,一次由子类 ExtendedRequestMappingHandlerMapping
处理。还有一次由原版RequestMappingHandlerMapping
--首先使用自定义条件,然后再不使用它。底线是我的自定义条件被简单地忽略了。
这应该是一种高级模式,但 IMO 应该很常见......
评论有人吗?
最佳答案
Spring MVC已经提供了区分json和html的机制,RequestMapping注解采用了consumes属性来查看请求的内容类型...
// REST version, Content-type is "application/json"
@RequestMapping(value = "/", consumes = "application/json")
public void myRestService() {
...
// HTML version, Content-type is not "application/json"
@RequestMapping(value = "/", consumes = "!application/json")
public void myHtmlService() {
...
使用相同 url 但具有不同方法的另一种方法是使用 param 或 headers 属性...
// the url is /?role=guest
@RequestMapping(value = "/", param = "role=guest")
public void guestService() {
// the url is / with header role=admin
@RequestMapping(value = "/", headers = "role=admin")
public void adminService() {
我认为您会想要不同的网址以确保安全。通常,使用 Spring Security 之类的东西,您会将所有管理功能放在/admin 下并让框架管理所有这些...
<http auto-config="true">
<intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
...
这对于您的用例是否足够?
关于spring - 在 Spring mvc 3.1 中添加自定义 RequestCondition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10073695/