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

在一次采访中,有人问我一个问题-如果假设您的子控制器像下面的代码那样扩展了父控制器,并且我们想访问父类@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

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

index.jsp

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

先感谢您...

评论
顏小朵o
顏小朵o

也许这可以工作:


@RequestMapping("/parent")
public abstract class Parent {
    @RequestMapping("/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";
    }}

点赞
评论