【问题标题】:Use multiple child Controllers against @RequestMapping defined in Parent class对父类中定义的@RequestMapping 使用多个子控制器
【发布时间】:2013-01-30 15:35:52
【问题描述】:

我有一个父类 P,它定义了一个请求映射,如下所示:

public abstract class P {
 @RequestMapping(value = "/a/b/c", method = RequestMethod.POST)
    public String productLink(@RequestParam("abc") String json) throws Exception {
        return getProductLinks(json);
    }
}

我有几个孩子Controller 上课,ClassImpl 就是其中之一:

@Controller
public class ClassImpl extends P {
@RequestMapping(value = "/start", method = RequestMethod.GET)
    public String start(@RequestParam(value = "keyword", required = true) String keyword,
            @RequestParam(value = "keywordId", required = true) long keywordId) throws Exception {
     //Something
    }
}

如果我只使用一个子类运行此应用程序,它可以正常工作,但会导致多个子控制器出现问题。

当我运行我的应用程序时,我收到一条错误消息 "Cannot map handler ClassImpl to URL path [/a/b/c]: There is already handler [a.b.c.d.ClassImpl@a92aaa] mapped"

It seems that because of multiple child classes, it is unable to find the controller for this mapping which is understood.

在每个类(或一个单独的类)中定义@RequestMapping 是唯一的方法吗?我不想在所有地方都放类似的代码。是否有任何解决方法可以将其保留在父类中并继续使用它?

谢谢,

【问题讨论】:

  • 我觉得行不通。
  • 如果我告诉您您也可以在类级别声明 @RequestMapping 注释,会有帮助吗?
  • ^ 我不这么认为。我们最终会遇到同样的麻烦。

标签: java spring spring-mvc controller abstract


【解决方案1】:

在每个类(或一个单独的类)中定义@RequestMapping 是唯一的方法吗?

简短的回答是肯定的。我个人认为它属于一个单独的类。

你到底为什么要把productLink()放在父类中呢?它不是一个抽象方法,你也没有覆盖它,所以对我来说它没有多大意义。

【讨论】:

    【解决方案2】:

    你不应该在抽象类中使用@RequestMapping。这个注解是针对真实控制器的,所以具体的类。

    使用抽象类,因为它们打算使用,即分解代码,而不是完成工作。

    在这里您可以执行以下操作:

    public abstract class P {
    
        public String productLink(String json) throws Exception {
           return getProductLinks(json);
        }
    }
    

    然后

    @Controller
    public class ClassImpl extends P {
    
        @RequestMapping(value = "/start", method = RequestMethod.GET)
        public String start(@RequestParam(value = "keyword", required = true) String keyword,
            @RequestParam(value = "keywordId", required = true) long keywordId) throws     Exception {
             //Something
        }
    
        //here reusing the code from superclass
        @RequestMapping(value = "/a/b/c", method = RequestMethod.POST)
        public String productLink(@RequestParam("abc") String json) throws Exception {
            return super.getProductLinks(json);
        }
    }
    

    这添加了一些样板代码,但恕我直言,这是这样做的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      相关资源
      最近更新 更多