在Spring MVC中,当子类扩展父类时,我们可以从父类路径调用@RequestMapping吗?

问题描述 投票:0回答:1

在一次面试中,我被问到一个问题;假设你有一个子控制器,它扩展了父控制器,就像下面的代码一样,我们想访问父类。@RequestMapping 方法。我们能做到吗?有什么办法吗?

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

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

Parent.java

package com.practice;

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

Child.java

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

索引.jsp

<a href="parent/hello">BaseHello</a>
<a href="child/hello">ChildHello </a>
<a href="child/details">ChildDetails</a>
java spring-mvc controller
1个回答
0
投票

也许这将工作。


//@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";
    }}

© www.soinside.com 2019 - 2024. All rights reserved.