#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2001
    Posts
    181
    Rep Power
    13

    Declare variable in Scriplet or Declaration?


    When I declare variable in Scriptlet
    Code:
    <%
    	java.util.Date a = new java.util.Date();
    %>
    current time is <%=a%>
    When Refresh browser I get different outout

    current time is Mon Jun 17 19:44:14 ICT 2002
    current time is Mon Jun 17 19:44:26 ICT 2002
    current time is Mon Jun 17 19:44:34 ICT 2002
    current time is Mon Jun 17 19:44:42 ICT 2002

    but when I declare variable in Declaration
    Code:
    <%
    	java.util.Date a = new java.util.Date();
    %>
    current time is <%=a%>
    When Refresh browser I get same out.put

    current time is Mon Jun 17 19:45:19 ICT 2002
    current time is Mon Jun 17 19:45:19 ICT 2002
    current time is Mon Jun 17 19:45:19 ICT 2002
    current time is Mon Jun 17 19:45:19 ICT 2002

    I see many code, some code declare in Declaration, some code declare in Scriptlet

    Which application or Which situation should declare in Declaration, and declare in Scriptlet?
  2. #2
  3. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Location
    Lincoln, NE. USA
    Posts
    2,353
    Rep Power
    117
    Correct me if I'm wrong, but your code samples are identical. What I think you are saying is creating a variable in a scriptlet tag (<% %>) vs a Declaration tag (<%! %>).

    The difference in the two tags is where the variable is created. The scope of the variable when it is converted into a servlet.

    Everything put in scriptlet tags are put directly into the jsp_service method. This is the mthod called each time the JSP is accessed by the server. Everything in the Declaration tag is made into a class variable. These are made only the first time the jsp is accessed.

    Using your examples (if they were listed as you intended), this is where the variables would end up in the source:
    Code:
    <%!
    	java.util.Date a1 = new java.util.Date();
    %>
    current time is <%=a1%>
    
    ----------------
    vs
    ----------------
    
    <%
    	java.util.Date a2 = new java.util.Date();
    %>
    current time is <%=a2%>
    (Note, code is not complete)
    Code:
    public class jsp_name extends HttpJspBase {
      public java.util.Date a1 = new java.util.Date();
      ..more code...
      public _jspService(..vars..) {
        java.util.Date a2 = new java.util.Date();
        ...more code....
      }
    }
    As you can see, scriptlets tags are local to the service method and thus are redeclared every access. Declarations tags are local to the servlet itself, and thus are declared only the first time the servlet is accessed. Hope that helps.

IMN logo majestic logo threadwatch logo seochat tools logo