不要在JSP中這樣做。創建一個真正的Java類,如果需要Javabean的味道。
public class Father {
private static int count = 0;
public void incrementCount() {
count++;
}
public int getCount() {
return count;
}
}
,並使用一個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);
}
}
您在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>
,並創建/WEB-INF/father.jsp
如下:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2595687</title>
</head>
<body>
<p>${father2.count}
</body>
</html>
並通過http://localhost:8080/contextname/father
調用FatherServlet
。 ${father2.count}
將顯示返回值father2.getCount()
。
要了解有關正確編程JSP/Servlet的更多信息,我建議您通過those tutorials或this book。祝你好運。