|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
SlickEdit: Code in over 40 languages across 7 platforms. SlickEdit’s unmatched power, speed, and flexibility allows even the most accomplished developers to write better code faster. Download a free trial today! |
|
#1
|
|||
|
|||
|
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
|
|||
|
|||
|
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. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Java Help > Declare variable in Scriplet or Declaration? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|