【问题标题】:Can we call @RequestMapping from Parent class path when Child class extends it in Spring MVC?当 Child 类在 Spring MVC 中扩展它时,我们可以从父类路径调用 @RequestMapping 吗?
【发布时间】:2020-05-09 09:14:59
【问题描述】:

在一次采访中,我被问到一个问题;假设您有一个子控制器,它像下面的代码一样扩展父控制器,并且我们想要访问父类 @RequestMapping 方法。我们可以这样做吗?有什么办法吗?

当我尝试下面的代码并单击 BaseHello 链接时,我收到警告- 如果我在 Parent 类中写 @Controller 那么同样的警告也会出现

May 09, 2020 2:18:53 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /Projectname/parent/hello

父类.java

package com.practice;

@RequestMapping("/parent")
public abstract class Parent {
    @RequestMapping("/hello")
    public String world() {
        return "hellopage";
    }
}

子.java

package com.practice;
@Controller
@RequestMapping("/child")
public class Child extends Parent {
    @RequestMapping("/detail")
    public String info() {
        return "detailpage";
    }
}

index.jsp

<a href="parent/hello">BaseHello</a>
<a href="child/hello">ChildHello </a>
<a href="child/details">ChildDetails</a>

【问题讨论】:

    标签: java spring-mvc controller


    【解决方案1】:

    也许这会起作用:

    
    //@RequestMapping("/parent") remove conflicts child path
    public abstract class Parent {
        @RequestMapping("parent/hello")
        public String world() {
            return "hellopage";
        }}
    
    @Controller 
    // @RequestMapping("/child") // remove this, add child to the method, because abstract class already have one.
    public class Child extends Parent {
        @RequestMapping("/child/detail")
        public String info() {
            return "detailpage";
        }}
    
    

    【讨论】:

    猜你喜欢
    • 2014-10-22
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 2017-10-04
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多