[英]ModelAttribute in abstract class with value from subclass
I want to have a common method annoted @ModelAttribute in an abstract class but with value from subclasses. 我想在一个抽象类中有一个批注@ModelAttribute的通用方法,但是要有子类的值。 The final goal is to retrieve the value of a variable in JSP. 最终目标是在JSP中检索变量的值。 The value is different in each subclass controller but I don't want to duplicate the @ModelAttribute method. 每个子类控制器中的值都不同,但是我不想重复@ModelAttribute方法。
The abstract class 抽象类
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;
}
}
The sublass, a controller 底盘,控制器
@Controller
@RequestMapping(OneController.PATH)
public class OneController extends BaseController {
protected static final String PATH = "/one";
public OneController() {
setPATH(PATH);
}
}
JSP JSP
Value for controllerPath: ${controllerPath}
The value of ${controllerPath} is always empty with Spring version 4.0.9.RELEASE but works (the value is set with the value from the subclass controller) with Spring version 3.1.2.RELEASE. 在Spring 4.0.9.RELEASE版本中,$ {controllerPath}的值始终为空,但在Spring 3.1.2.RELEASE版本中,该值有效(使用子类控制器的值进行设置)。 How do I update my code to work with Spring 4 ? 如何更新代码以与Spring 4配合使用?
You need to declare abstract the ModelAttribute method in your abstract controller. 您需要在抽象控制器中声明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();
}
And on each controller which extends the abstract controller: 在扩展抽象控制器的每个控制器上:
@Controller
@RequestMapping(OneController.PATH)
public class OneController extends BaseController {
protected static final String PATH = "/one";
@Override
public String getControllerPath(){
return PATH;
}
}
UPDATE: 更新:
If you dont want to repeat the new method in all Controllers: 如果您不想在所有Controller中重复新方法:
In your abstract controller 在您的抽象控制器中
@ModelAttribute("controllerPath")
public String getControllerPath(){
return "";
}
Where you want to override the value. 您要覆盖该值的位置。 Add Override annotation 添加替代注释
@Override
public String getControllerPath(){
return PATH;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.