java 使用 jsp:setProperty 在另一个 bean 中设置一个 bean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4887282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jsp:setProperty to set one bean in other bean
提问by Hans
I would like to know how to use jsp:setProperty in the following scenario. Here is a simple example of two java classes.
我想知道如何在以下场景中使用 jsp:setProperty。这是两个 java 类的简单示例。
public class MyExample {
private MyName myNameExample = new MyName();
public MyExample() {}
public MyName getMyNameExample() {
return myNameExample;
}
public void setMyNameExample(MyName setTo) {
myNameExample = setTo;
}
}
public class MyName {
private String firstName;
public MyName() {}
public String getFirstName() {
return firstName;
}
public String setFirstName(String setTo) {
firstName = setTo;
}
}
I was trying to use something like:
我试图使用类似的东西:
<jsp:useBean id="example" class="MyExample" scope="page"/>
<jsp:setProperty name="example" property="????" value="aFirstName"/>
The important part here is that I want to reference the MyName object from within MyExample. Therefore, creating a bean to directly access MyName will not help me. So I am not looking for this answer:
这里的重要部分是我想从 MyExample 中引用 MyName 对象。因此,创建一个 bean 来直接访问 MyName 对我没有帮助。所以我不是在寻找这个答案:
<jsp:useBean id="name" class="MyName" scope="page"/>
<jsp:setProperty name="name" property="firstName" value="aFirstName"/>
采纳答案by BalusC
You could just create both beans and set one in other by ${}
.
您可以只创建两个 bean 并通过${}
.
<jsp:useBean id="myName" class="MyName" scope="page" />
<jsp:setProperty name="myName" property="firstName" value="aFirstName" />
<jsp:useBean id="myExample" class="MyExample" scope="page" />
<jsp:setProperty name="myExample" property="myExampleName" value="${myName}" />
Unrelated to the concrete problem, I'd suggest to invest time in learning servlets and MVC. The above is a pretty old fashioned and tight-coupled way of controlling the models in the view.
与具体问题无关,我建议花时间学习 servlets 和 MVC。以上是一种非常老式的紧耦合方式来控制视图中的模型。
Note that using packageless classes may not work in all circumstances (since they are invisible for normal classes inside a package). Only in certain Apache Tomcat configurations it will work. Rather put your classes inside a package in order to be not dependent of that.
请注意,使用无包类可能不适用于所有情况(因为它们对于包内的普通类是不可见的)。只有在某些 Apache Tomcat 配置中它才能工作。而是将您的类放在一个包中,以便不依赖于它。