为什么我不能使用< jsp:getProperty>没有< jsp:useBean>吗? [英] Why I can't use <jsp:getProperty> without <jsp:useBean>?
问题描述
说有一个具有代码的servlet:
Say there is servlet that has code:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
foo.Person p = new foo.Person("Evan");
req.setAttribute("person", p);
RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
view.forward(req, resp);
}
,然后转到result.jsp
以打印给定名称(Evan).这是它的外观图(源Head First Servlet和JSP):
, that goes to result.jsp
to print given name (Evan). Here is a picture of how it would look (source Head First Servlets and JSP):
我知道<jsp:useBean>
通过调用getAttribute()
-返回相同的Person对象,因为它们在相同的请求范围中.另一方面,<jsp:getProperty>
会调用findAttribute()
来逐字地尝试查找值"person" ..的属性,并最终打印 Evan .
I know that <jsp:useBean>
returns same Person object by calling getAttribute()
- since they are in same request scope. While on the other side, <jsp:getProperty>
will call findAttribute()
to literally try to find attribute of value "person".. and eventually print Evan.
但是,如果我不使用<jsp:useBean>
怎么办?这是否意味着我无法访问个人"信息?范围 request 的属性?我的意思是,即使我不使用<jsp:useBean>.
,它仍然会存在,那为什么我在两个 id 中的 id 中必须具有相同的 value ("person") c1>和 name 在<jsp:getProperty>
里面?简单删除<jsp:useBean>
会破坏我的程序.
But what if I didn't use <jsp:useBean>
? Does that mean I couldn't access "person" attribute at scope request? I mean it would still be there, even if I didn't use <jsp:useBean>.
So why I must have same value("person") inside both id in <jsp:useBean>
and name inside <jsp:getProperty>
? Simple removing <jsp:useBean>
breaks my program.
知道<jsp:getProperty>
会调用findAttribute()
,如果只有一个属性(如 attribute-name )会被用作查找属性的参数,那么逻辑会更合逻辑吗?在范围 page> request> session> application 中?为什么我必须绑"这两个标签:<jsp:useBean>
和<jsp:getProperty>
?
Knowing that <jsp:getProperty>
calls findAttribute()
, wouldn't it be more logical if there was a single attribute (like attribute-name), that will be used as an argument to find attributes in scopes page>request>session>application? Why I must "tie" those two tags: <jsp:useBean>
and <jsp:getProperty>
?
推荐答案
您如何看待以下代码?
public class Main {
public static void main(String[] args) {
System.out.println(person);
}
}
您必须已经正确地猜到它不会成功编译.
You must have already correctly guessed that it won't be compiled successfully.
现在,下面的代码呢?
public class Main {
public static void main(String[] args) {
Person person = new Person();// Declaring person
System.out.println(person);
}
}
当然,它将成功编译 1 ,因为现在编译器可以理解person
是什么.
Of course, it will be compiled successfully1 because now the compiler understands what person
is.
类似地,使用
<jsp:getProperty name="person" property="name">
没有将person
声明为
<!-- Declaring person -->
<jsp:useBean id="person" class="foo.Person" scope="request" />
不会成功编译.
1假设存在Person.class
.
这篇关于为什么我不能使用< jsp:getProperty>没有< jsp:useBean>吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!