Monday, July 14, 2014

Translation process

Now you are getting into the core of JSP. I think you have a little bit of idea about JSP life circle. In the processing time it is converted to the servlet and do the task and again converted to the JSP file. In this case you have to understand some translation parts of that process. 




Order of declaration 

In other programming language you have to think about the order of variables and methods. You are not allowed to use variable without any initialization. But in JSP you need not to worry about the order. Because it changes to servlet during the process. 

<html>
<body>

Now your age : <%=age%>
<br>
After five years you age : <%=age + 5%>

<%! int age=20; %>

</body>
</html>

Variable initialization 

In JSP you need not to worry about initialize variables. If you declare them in declaration tag, these variables are initialized to their default values. But if you declare these variables in scriptlet tag, you must initialized them before use. Look at the following example.

<html>
<body>

<%! int x; %>
<%  int y; %>

i : <%= x+1 %>
j : <%= j+1 %>

</body>
</html>


When you run this, you will be able to see a error message like this. Because I have declare x in declaration tag. But j in scriptlet tag.


Then you can comment 8th line (j : <%= j+1 %>) and run this. It works.


Flow control


In JSP it allows you to get easier your code with conditional and iterative statements. You can use HTML codes within JSP codes instead of using multiple out.println() statements. Look at the following programs to understand.

First program

<html>
<body>

<%  int x = 10;
 if(x==10){
%>
  <h1>Success</h1>
<% 
 }
 else{
%>
  <h1>Fail</h1>
<%
 }
%>
</body>
</html>


Second program

<html>
<body>

<%  int x = 10;
 if(x==10){
  out.println("<h1>Success</h1>");
 }
 else{
  out.println("<h1>Fail</h1>");
 }

%>
</body>
</html>




As you can see both of the programs are doing same thing using IF-ELSE statement. In this program you need to worry, because it has a simple code. But if you have a big code(multiple HTML codes) to execute, it is not easy to use multiple out.println() statements. At that time you can use HTML codes within JSP syntax.


Escape characters 


In JSP you can have several places that escape characters are used.  

  1. Within attribute
  2. Within scriptlet field
  3. Within text field
If you know how to use escape characters in Java, this is also very simple to understand. Following example demonstrate how to use escape characters in mentioned three types.

Within attribute

<%@ page info="Using ', \", \\, <\%, and %\> in JSP. " %>
<html><body>
<%= getServletInfo() %>
</body></html>


Within scriptlet field

<html><body>
<%= "Opening tag of a scriptlet <%" %>
</br>
<%= "Closing tag of a scriptlet %\>" %>
</body></html>

Within text field

<html><body>
The opening tag of a scriptlet <\%
</br>
The closing tag of a scriptlet %>
</body></html>