我刚刚开始学习JSP技术,并遇到了障碍.
如何从<%!中的方法输出HTML?...%> JSP声明块?
这不起作用:
<%!
void someOutput() {
out.println("Some Output");
}
%>
...
<% someOutput(); %>
Run Code Online (Sandbox Code Playgroud)
服务器说没有"出局".
U:我知道如何用这个方法重写代码来重写一个字符串,但有没有办法在<%!中执行此操作.void(){}%>?虽然它可能不是最佳的,但它仍然很有趣.
Ash*_*cer 29
您不能在指令内使用'out'变量(也不能使用任何其他"预先声明的"scriptlet变量).
JSP页面由您的Web服务器转换为Java servlet.例如,在tomcats内部,scriptlet中的所有内容(以"<%"开头)和所有静态HTML一起被转换为一个巨大的Java方法,它将您的页面逐行写入名为"out"的JspWriter实例.这就是您可以直接在scriptlet中使用"out"参数的原因.另一方面,指令(以"<%!"开头)被转换为单独的Java方法.
举个例子,一个非常简单的页面(我们称之为foo.jsp):
<html>
<head/>
<body>
<%!
String someOutput() {
return "Some output";
}
%>
<% someOutput(); %>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
最终会看起来像这样(为了清晰起见,忽略了很多细节):
public final class foo_jsp
{
// This is where the request comes in
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
// JspWriter instance is gotten from a factory
// This is why you can use 'out' directly in scriptlets
JspWriter out = ...;
// Snip
out.write("<html>");
out.write("<head/>");
out.write("<body>");
out.write(someOutput()); // i.e. write the results of the method call
out.write("</body>");
out.write("</html>");
}
// Directive gets translated as separate method - note
// there is no 'out' variable declared in scope
private String someOutput()
{
return "Some output";
}
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*ave 13
<%!
private void myFunc(String Bits, javax.servlet.jsp.JspWriter myOut)
{
try{ myOut.println("<div>"+Bits+"</div>"); }
catch(Exception eek) { }
}
%>
...
<%
myFunc("more difficult than it should be",out);
%>
Run Code Online (Sandbox Code Playgroud)
试试这个,它对我有用!
par*_*oja 10
我想这会有所帮助:
<%!
String someOutput() {
return "Some Output";
}
%>
...
<%= someOutput() %>
Run Code Online (Sandbox Code Playgroud)
无论如何,在视图中使用代码并不是一个好主意.
您需要做的就是将JspWriter对象作为参数传递给您的方法,即
void someOutput(JspWriter stream)
Run Code Online (Sandbox Code Playgroud)
然后通过以下方式调用
<% someOutput(out) %>
Run Code Online (Sandbox Code Playgroud)
writer对象是_jspService中的局部变量,因此您需要将其传递给实用程序方法.这同样适用于所有其他内置引用(例如请求,响应,会话).
查看最新情况的一个好方法是使用Tomcat作为您的服务器,并深入到"工作"目录中查找从"jsp"页面生成的".java"文件.或者在weblogic中,您可以使用'weblogic.jspc'页面编译器来查看请求页面时生成的Java.
一个简单的替代方案如下:
<%!
String myVariable = "Test";
pageContext.setAttribute("myVariable", myVariable);
%>
<c:out value="myVariable"/>
<h1>${myVariable}</h1>
Run Code Online (Sandbox Code Playgroud)
你可以在jsp代码中以任何方式简单地使用变量
归档时间: |
|
查看次数: |
150352 次 |
最近记录: |