[英]ModelAttribute in abstract class with value from subclass
我想在一個抽象類中有一個批注@ModelAttribute的通用方法,但是要有子類的值。 最終目標是在JSP中檢索變量的值。 每個子類控制器中的值都不同,但是我不想重復@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
@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版本中,該值有效(使用子類控制器的值進行設置)。 如何更新代碼以與Spring 4配合使用?
您需要在抽象控制器中聲明ModelModelAttribute方法。
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
@RequestMapping(OneController.PATH)
public class OneController extends BaseController {
protected static final String PATH = "/one";
@Override
public String getControllerPath(){
return PATH;
}
}
更新:
如果您不想在所有Controller中重復新方法:
在您的抽象控制器中
@ModelAttribute("controllerPath")
public String getControllerPath(){
return "";
}
您要覆蓋該值的位置。 添加替代注釋
@Override
public String getControllerPath(){
return PATH;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.