java - 抽象类中的 ModelAttribute 具有来自子类的值

标签 java jsp spring-mvc spring-annotations

我希望在抽象类中有一个注释为 @ModelAttribute 的通用方法,但具有来自子类的值。最终目标是检索 JSP 中变量的值。每个子类 Controller 中的值都不同,但我不想重复 @ModelAttribute 方法。

抽象类

public abstract class BaseController {

    protected String PATH = "";

    public void setPATH(String inPath) {
        PATH = inPath;
    }

    @PostConstruct
    private void init() {
        setPATH(PATH);      
    }

    @ModelAttribute("controllerPath")
    public String getControllerPath() {
        return PATH;
    }   
}

子类, Controller

@Controller
@RequestMapping(OneController.PATH)
public class OneController extends BaseController {

    protected static final String PATH = "/one";

    public OneController() {
        setPATH(PATH);      
    }
}

JSP

Value for controllerPath: ${controllerPath}

在 Spring 版本 4.0.9.RELEASE 中,${controllerPath} 的值始终为空,但在 Spring 版本 3.1.2.RELEASE 中可以正常工作(该值使用子类 Controller 的值设置)。 如何更新我的代码以使用 Spring 4?

最佳答案

您需要在抽象 Controller 中声明抽象 ModelAttribute 方法。

public abstract class BaseController {

    protected String PATH = "";

    public void setPATH(String inPath) {
        PATH = inPath;
    }

    @PostConstruct
    private void init() {
        setPATH(PATH);      
    }

    @ModelAttribute("controllerPath")
    public abstract String getControllerPath();
}

在每个扩展抽象 Controller 的 Controller 上:

@Controller
@RequestMapping(OneController.PATH)
public class OneController extends BaseController {

    protected static final String PATH = "/one";

    @Override
    public String getControllerPath(){
        return PATH;
    }
}

更新:

如果您不想在所有 Controller 中重复新方法:

在你的抽象 Controller 中

@ModelAttribute("controllerPath")
 public String getControllerPath(){
     return "";
 }

您想要覆盖该值的位置。添加覆盖注释

@Override
public String getControllerPath(){
    return PATH;
}

关于java - 抽象类中的 ModelAttribute 具有来自子类的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435459/

相关文章:

java - SmartGWT 时区

java - jsp/servlet 应用程序中的延迟作业

java - 如何在 java servlet 前端 Controller 中重构大型 if else block

java - Spring Data REST 不包括资源中的实体链接

java - Spring mvc 项目获取错误无效 LOC header

spring - 如何将 "a-b"查询映射到 Spring MVC 中的命令对象

java - 无法编译的源代码 - 错误的树类型错误和找不到符号错误

java - 如何更改此采样率转换代码以使声音变慢?

java - 我尝试运行该应用程序,但它因所需的 bean 而失败

apache - htaccess mod_headers 用于无缓存