<%!
class father {
static int s = 0;
}
%>
<%
father f1 = new father();
father f2 = new father();
f1.s++;
out.println(f2.s); // It must print "1"
%>
Run Code Online (Sandbox Code Playgroud)
当我运行该文件时,我收到此错误.谁能解释一下?
The field s cannot be declared static; static fields can only be declared in static or top level types.
Run Code Online (Sandbox Code Playgroud)
使用<%! ... %>
语法,您可以对内部类进行decalre,默认情况下它是非静态的,因此它不能包含static
字段.要使用static
字段,您应该将类声明为static
:
<%!
static class father {
static int s = 0;
}
%>
Run Code Online (Sandbox Code Playgroud)
但是,BalusC的建议是正确的.
不要在 JSP 中这样做。如果需要具有 Javabean 的风格,则创建一个真正的 Java 类。
public class Father {
private static int count = 0;
public void incrementCount() {
count++;
}
public int getCount() {
return count;
}
}
Run Code Online (Sandbox Code Playgroud)
并使用 Servlet 类来完成业务任务:
public class FatherServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Father father1 = new Father();
Father father2 = new Father();
father1.incrementCount();
request.setAttribute("father2", father2); // Will be available in JSP as ${father2}
request.getRequestDispatcher("/WEB-INF/father.jsp").forward(request, response);
}
}
Run Code Online (Sandbox Code Playgroud)
你映射web.xml
如下:
<servlet>
<servlet-name>fatherServlet</servlet-name>
<servlet-class>com.example.FatherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fatherServlet</servlet-name>
<url-pattern>/father</url-pattern>
</servlet-mapping>
Run Code Online (Sandbox Code Playgroud)
并创建/WEB-INF/father.jsp
如下:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2595687</title>
</head>
<body>
<p>${father2.count}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
并调用FatherServlet
by http://localhost:8080/contextname/father
。该${father2.count}
显示的返回值father2.getCount()
。
要了解有关以正确方式编程 JSP/Servlet 的更多信息,我建议您阅读这些教程或本书。祝你好运。
归档时间: |
|
查看次数: |
6334 次 |
最近记录: |