Wednesday, 18 September 2013

(2) include directive

(2) include directive

Fig: jsp3.jpg

Similarly the include directive will have include as the name in the 2nd element after the tags i.e: <%@ include file=....%.>
Can we say include file= "whatever file you want to include in this page. Lets take an example
we know that in any web applications there will be a number of different pages, for example i have 100 pages in my web applications and often times there are certain common areas in every page. Those common areas would be headers and footers regions so most of the times I will have the same header and same footer in all the pages.
And writing the code for header and footer in each and every page in order best practice because if you want to change the header so most of the times I have the same header or footer text anything in the header or footer you will basically have make changes each and every page which is not a best thing to do so what you basically do is you write a separate header ( ex: Hello<=userName%> )and footer page (Example:
<table><tr>
<td>Contact Details</td>
<tr></table>

    And you put whatever text you want to in the header and footer and if at all if you want to make any changes in the header or footer you simply change the  header.jsp or footer.jsp you have done, and you are only make change at one place as post to making changes in 100 places. And what you do then you add this header and footer pages in every page you want to make use of it so you basically include these header and footer pages and iyou can include these pages using the inlcude directive so this definately is very effective and it saves a lot of time for us.
One thing to note here is the inlcudsion of header and footer files or inclusion of the soft files into the main file is done at the translation time. So what is this translation time? time where your jsp translated to a servlet.
So the first time I write my Main page add the header and footer files i.e <%@ include file=header.jsp> , <%@ include file=footer.jsp>.  and I compile it now it is going to translate the time of call it is going to translate my jsp pages to a servlet page , and my servlet is going to be loaded into the memory.
But let's say that one issue here that could occur this let us say that I included my header and footer to my main page and I rended the page now later if I had to change the header.jsp file , initially it was "Hello.userName", and I want to change it into "HI. userName" so I simply modify the header .jsp and save it. Will this effect my main page? Will I see "Hi userName " here in main page? No , because my main page was translated into a servlet even before the header.jsp made its change.
So whatever changes made in header.jsp, that is not reflected my main page so if I want that change reflected to my main page , what I need to do is? again need to recompile my main page so that it is going to take whatever it is latest from the subpages that is header.jsp or footer.jsp and then it is going to be translated into servlet again then render that the user where I will see " Hi. userName"
So this is the jsp inlcude directive


Directive: page directive:

(1).  page directive:

Whatever you put in page directive is basically applied to the current jsp pages on which we are currently associated to
When it comes to directives the second element is also very important, so whatever you put the jsp directive tag is important as well. i.e :  <%@ page ......"%> //here page is 2nd element.
Here I put here "page" that means that it is page directive tell that what kind of element it is, that is here page directive element. So if I say percentage at the rate(@) page that means that this is the page directive.

Ex:
<%@ page import = "{IMPORTED_CLASSES}"
     contentType = "{CONTENT_TYPE}"
     isThreadSafe = "{true/false}"
     session = "{true/false}"
     buffer = "{BUFFER_SIZE}"
autoflush = "{true/false}"
extends = "{EXTENDS_FROM_PAGE}"
info = "{PAGE_INFO}"
errorPage = "{ERROR_PAGE_NAME}"
isErrorPage = "{true/false}"
language = "{LANGUAGE}"


We can provide number of predefined attributes values in a page directive and this is going to effect the page and the servlet at the end
These are the few of the attributes ,important attributes which we use in page directive elements
And we will see how it will effective the jsp page, after the application of this page directive:

1. So first thing is page import: so basically whenever you want to import certain classes files into your jsp you use the page directive import attribute. Lets say that you are working on some business logic in your servlet class and you are using packages and classes in the util package and some other classes. What do you do when you use them basically you import those classes whatever you are using in your file. Similarly we know that jsp ultimately converted into servlet and we do write  scriptlets in your jsps where we use certain other classes and utility packages as well. As a earlier example we saw probably have used ArrayList class in my jsp scriptlet when it is converted to a servlet, there is no error but it is probably going to give a error because Im using a ArrayList class but not imported that class, so how do we import? In the jsp we import by using the page directive:

(ii). contentType:

The default content Type would be html. Because most of the time whatever you sent back to the client is html page but you need to know that not only html but you can send back to the client bunch of different files that you can send like jar, image, video, zip and number of other file types which you can send to the client.
And the content type basically determines what type file you are sending back to the client.

(iii). isThreadSafe:

isThreadSafe ! What does it mean? we know that servlets are multithreaded environment, that means that only one servlet instance whenever new request comes in for the servlet it basically respond multiple threads and it is basically assume that bydefault your thread safe, it is thread safe because it is assume that you are writing your code in thread safe manner so that one particular change is made in one thread does not effect the other thread so there are any instance variables in threads in the servlets is trying to modify those variables so change made by one thread is visible to other thread in that case your servlet is not thread safe. So by default it is assumed that you implement some best practices in your code and you dont do such things and your servlets are thread safe but if you feel that your servlet is not thread safe, you would say that isThreadSafe is false, so if you dont want to make a thread safe is false and when you say that what the engine is going to do that engine is going to implement single thread module for your particular servelet which is generated by the jsp. It is basically is going to make the service() method synchronization that means only one thread can enter the service() method at one particular time.

4. session:

It determines for that you can use the current http session or  not? so by default it is true, and if you dont want to use the session, you can make it as false.

5. buffer, 6. autoflush, 7. extends,8. info are the attributes.: and another important attribute is errorPage, isErrorPage attribute.

When you say errorPage, you give some jsp page name( your html page name) whenever there is a error in current jsp page, it is going to take you to that particular error page defined the error page attribute. And how does it know that particular page is error page or not? if i say errorPage= ERROR.jsp, and when I write my error.jsp, i have to give page directive attribute isErrorPage and value of "true" but by default it is false so that means that every page is considered as a normal jsp page.
But if you want to make your jsp page an error page will have to say isErrorPage = true then it is treated as an error page.

So these are some of the attributes you can use in a jsp page directive and we just saw that how one application of these  directives we can change the behaviour of the generated servlet.

JSP Directives

Lets talk about the JSP Directives.

Similart to other JSP Elements which we discussed earlier, jsp directive elements also have their own tags . ie.: <%@...%> so whatever you put in these tags will be considered as jsp directives.
These JSP Directives are certain preprocessing commands given to the JSP Engine. These commands should be processed before the jsp can be translated to a servlet.
So unlike the jsp elements you do not write java code or any kind of business logic in jsp directives
But you give some commands to the jsp engine.
Now we are going to see what are the commands, how do we implement them and what are the uses of it. We just said that we are using just providing commands to the jsp engine.

Why do we need JSP Directives?
To incorporate some additional features into the jsp so how the jsp basically behaves . When we say that incorporate some additional features into the jsp, mean that we modifying the servlet behaviour generated.
So we know that ultimately a jsp translated into a servlet. So jsp in term it does not have any meaning. When we are saying we are modying something jsp means we are actually changing certain behaviour in the servlet.
We can include some certain html files and we can provide tag libraries. We are going to see what tag libraries are and how do we use them?

Example: <%@ page import="java.util.ArrayList"%>

The above example is jsp page directive where Im importing the java.util.ArrayList class file.

Types of JSP Directives:

There are 3 different types in jsp directives: (

(1).  page directive:

Whatever you put in page directive is basically applied to the current jsp pages on which we are currently associated to
When it comes to directives the second element is also very important, so whatever you put the jsp directive tag is important as well. i.e :  <%@ page ......"%> //here page is 2nd element.
Here I put here "page" that means that it is page directive tell that what kind of element it is, that is here page directive element. So if I say percentage at the rate(@) page that means that this is the page directive.

Ex:
<%@ page import = "{IMPORTED_CLASSES}"
    contentType = "{CONTENT_TYPE}"
    isThreadSafe = "{true/false}"
    session = "{true/false}"
    buffer = "{BUFFER_SIZE}"
autoflush = "{true/false}"
extends = "{EXTENDS_FROM_PAGE}"
info = "{PAGE_INFO}"
errorPage = "{ERROR_PAGE_NAME}"
isErrorPage = "{true/false}"
language = "{LANGUAGE}"


We can provide number of predefined attributes values in a page directive and this is going to effect the page and the servlet at the end
These are the few of the attributes ,important attributes which we use in page directive elements
And we will see how it will effective the jsp page, after the application of this page directive:

1. So first thing is page import: so basically whenever you want to import certain classes files into your jsp you use the page directive import attribute. Lets say that you are working on some business logic in your servlet class and you are using packages and classes in the util package and some other classes. What do you do when you use them basically you import those classes whatever you are using in your file. Similarly we know that jsp ultimately converted into servlet and we do write  scriptlets in your jsps where we use certain other classes and utility packages as well. As a earlier example we saw probably have used ArrayList class in my jsp scriptlet when it is converted to a servlet, there is no error but it is probably going to give a error because Im using a ArrayList class but not imported that class, so how do we import? In the jsp we import by using the page directive:

(ii). contentType:

The default content Type would be html. Because most of the time whatever you sent back to the client is html page but you need to know that not only html but you can send back to the client bunch of different files that you can send like jar, image, video, zip and number of other file types which you can send to the client.
And the content type basically determines what type file you are sending back to the client.

(iii). isThreadSafe:

isThreadSafe ! What does it mean? we know that servlets are multithreaded environment, that means that only one servlet instance whenever new request comes in for the servlet it basically respond multiple threads and it is basically assume that bydefault your thread safe, it is thread safe because it is assume that you are writing your code in thread safe manner so that one particular change is made in one thread does not effect the other thread so there are any instance variables in threads in the servlets is trying to modify those variables so change made by one thread is visible to other thread in that case your servlet is not thread safe. So by default it is assumed that you implement some best practices in your code and you dont do such things and your servlets are thread safe but if you feel that your servlet is not thread safe, you would say that isThreadSafe is false, so if you dont want to make a thread safe is false and when you say that what the engine is going to do that engine is going to implement single thread module for your particular servelet which is generated by the jsp. It is basically is going to make the service() method synchronization that means only one thread can enter the service() method at one particular time.

4. session:

It determines for that you can use the current http session or  not? so by default it is true, and if you dont want to use the session, you can make it as false.

5. buffer, 6. autoflush, 7. extends,8. info are the attributes.: and another important attribute is errorPage, isErrorPage attribute.

When you say errorPage, you give some jsp page name( your html page name) whenever there is a error in current jsp page, it is going to take you to that particular error page defined the error page attribute. And how does it know that particular page is error page or not? if i say errorPage= ERROR.jsp, and when I write my error.jsp, i have to give page directive attribute isErrorPage and value of "true" but by default it is false so that means that every page is considered as a normal jsp page.
But if you want to make your jsp page an error page will have to say isErrorPage = true then it is treated as an error page.

So these are some of the attributes you can use in a jsp page directive and we just saw that how one application of these  directives we can change the behaviour of the generated servlet.


(2) include directive


Fig: jsp3.jpg

Similarly the include directive will have include as the name in the 2nd element after the tags i.e: <%@ include file=....%.>
Can we say include file= "whatever file you want to include in this page. Lets take an example
we know that in any web applications there will be a number of different pages, for example i have 100 pages in my web applications and often times there are certain common areas in every page. Those common areas would be headers and footers regions so most of the times I will have the same header and same footer in all the pages.
And writing the code for header and footer in each and every page in order best practice because if you want to change the header so most of the times I have the same header or footer text anything in the header or footer you will basically have make changes each and every page which is not a best thing to do so what you basically do is you write a separate header ( ex: Hello<=userName%> )and footer page (Example:
<table><tr>
<td>Contact Details</td>
<tr></table>

    And you put whatever text you want to in the header and footer and if at all if you want to make any changes in the header or footer you simply change the  header.jsp or footer.jsp you have done, and you are only make change at one place as post to making changes in 100 places. And what you do then you add this header and footer pages in every page you want to make use of it so you basically include these header and footer pages and iyou can include these pages using the inlcude directive so this definately is very effective and it saves a lot of time for us.
One thing to note here is the inlcudsion of header and footer files or inclusion of the soft files into the main file is done at the translation time. So what is this translation time? time where your jsp translated to a servlet.
So the first time I write my Main page add the header and footer files i.e <%@ include file=header.jsp> , <%@ include file=footer.jsp>.  and I compile it now it is going to translate the time of call it is going to translate my jsp pages to a servlet page , and my servlet is going to be loaded into the memory.
But let's say that one issue here that could occur this let us say that I included my header and footer to my main page and I rended the page now later if I had to change the header.jsp file , initially it was "Hello.userName", and I want to change it into "HI. userName" so I simply modify the header .jsp and save it. Will this effect my main page? Will I see "Hi userName " here in main page? No , because my main page was translated into a servlet even before the header.jsp made its change.
So whatever changes made in header.jsp, that is not reflected my main page so if I want that change reflected to my main page , what I need to do is? again need to recompile my main page so that it is going to take whatever it is latest from the subpages that is header.jsp or footer.jsp and then it is going to be translated into servlet again then render that the user where I will see " Hi. userName"
So this is the jsp inlcude directive

(3.) taglib directive

This is the last and most important directive
Basially we provide certain tags in your jsp pages and implementing the taglib directive is going to help a lot because it is going to clean up your jsp page, it is going to look more pretty it is going to get a lot of loat of your shoulder as well.
So lot of common custom logic which you have in your application can be written in a taglib directive and you simply use the taglib directive in your jsp pages instead of again writing all those logic repeatedly in each of the page .

syntax: <%@ taglib uri="{TLD_FILE}" prefix="{PREFIX}"%>

It starts angular brackets percentage atTheRate and followed by taglib and we have uri and prefix, we will see what is really mean?
Components of taglib Libraries:

1. Tag handler class (2) Descriptor configuration file (3) taglib directive

1. Tag handler class
Now let's say that we have a common functionality used in each and every page in my application so what I do this, I put this common chunk of code in certain file and I will use this common code in multiple jsp pages.
So that common place where I'm puttin the common logic is the Tag Handler class. This is the place where I put the common custom logic and html generation.
And I use the taglib directive in my jsp page to invoke the class which is implementing the common logic now they have to be some bridge between the taglib directive and my jsp file and actual tag handler class so for that reason I have the Descriptor configuration file.
Descriptor configuration file is nothing but the property mapping file which has got information about the taglib directive and the tag handler class and what are the different property you can set for the tag libraries

overview of taglib directive:


jsp4.jpg
//test.jsp
<%@taglib uri="sharmanjTags" prefix ="sharmanj"%>
<sharmanj:txtbox length="10" name="userName"/>
....

//sharmanj-taglib.tld
<tag>
<name>txtBox</name>
<tagclass>TextBoxTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
....
</tag>


//web.xml
<web-app>
<taglib>
<taglib-uri>sharmanTags<taglib-uri>
<taglib-location>
sharmanj-taglib.tld
</taglib-location>
</taglib>
</web-app>

/*TxtBoxTag.java*/
public class TxtBoxTag extends TagSupport
{
   public int doStartTag()
   {
     ----
   }
 }

See here an example i will show all the different pages  classes and files involved in a tag library and how each file is connected to the other file

//test.jsp
<%@taglib uri="sharmanjTags" prefix ="sharmanj"%>
......
<sharmanj:txtbox length="10" name="userName"/>
....

So first thing is my test.jsp, here What I did is? I have a common logic for displaying the text box so in my application whenever someone wants to use a text box in a jsp page they should not use the predefined text box present in html whatever input. But they have to use the jsp tag called sharmanj:txtbox to add a text box in their html or jsp file.
Lets say that I have provided some logic for that and that logic is present in the TxtBoxTag.java
We will have a look at the whole life cycle of tag handlers and all those things, what are the different tag handlers we can have? and whole life cycle of tag handlers and the next future class we will discuss tag libraries more details but here I just wanted to show you the different components we have placed tag libraries and how communication takes place?  between these components.
So my custom logic for the text box representation goes in the TxtBoxTag which is nothing but the tag handler class ( we just discussed).

/*TxtBoxTag.java*/
public class TxtBoxTag extends TagSupport
{
 public int doStartTag()
 {
  ----
 }
}

Lets say that I have that logic is placed in doStartTag() method
Now in my jsp I need to use the logic present in the TxtBoxTag.java to represent my text box.

//test.jsp
<%@taglib uri="sharmanjTags" prefix ="sharmanj"%>
......
<sharmanj:txtbox length="10" name="userName"/>
....

So here I say I get the taglib directive and I say:" uri=sharmanjTags and prefix=sharmanj. When I say uri? it means that path to the tag libraries which I will be using and this path will be present in the web.xml, and which is the configuration for your servlets and jsps
web.xml is the configuration file for your servlet and jsps

//web.xml
<web-app>
<taglib>
<taglib-uri>sharmanTags<taglib-uri>
<taglib-location>
sharmanj-taglib.tld
</taglib-location>
</taglib>
</web-app>
So when I say taglib uri="sharmanj", What the container is going to do is? The Web Container finds the sharmanTags in the web.xml file under the <taglib> element
So web container is going to find the taglib uri with the name "sharmanjTags", so it finds a match now.
Once the web container finds the match in web.xml file
Now web container is going to see the <taglib-location>, so taglib-location is "sharmanj-taglib.tld"
Now web container goes to sharmanj-taglib.tld location which is a configuration file again where we provide certain different configurations for the tag libraries

//sharmanj-taglib.tld
<tag>
<name>txtBox</name>
<tagclass>TxtBoxTag</tagclass>
<bodycontent>EMPTY</bodycontent>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
....
</tag>
And within the sharmanj-taglibraries , I have different tag attributes I can use in this particular tablibraries i.e sharmanj-taglib.tld
And before that let me complete the text.jsp

//test.jsp
<%@taglib uri="sharmanjTags" prefix ="sharmanj"%>
......
<sharmanj:txtbox length="10" name="userName"/>
....
I said that Im using the sharmanjTags lib and prefix can be anything example: sharmanj
So whatever I put prefix I should use that prefix certain feature in the taglib that is when I say prefix "sharmanj", Iam using prefix sharmanj on every element where I want to use the taglib. That is when I say sharmanj:txtbox, so here Iam trying to use  txtbox.
We know that taglib directive match to this particular location (i.e sharmanj-taglib.tld)  now Im going to use the "txtbox" taglib. Now it is going to search "txtbox" in the <name> tag in the file sharmanj-taglib.tld
Going to see what is the corresponding <tagclass> and it sees that tag class is "TxtBoxTag " and it is going to find that "TxtBoxTag" class , implement the basically call the methods in the TxtBoxTag.java

/*TxtBoxTag.java*/
public class TxtBoxTag extends TagSupport
{
 public int doStartTag()
 {
  ----
 }
}
So I put all my custom logic difining the TxtBox in my page.
So this is how the flow navigates in the different components and how your tag handler class is identified by the jsp pages .

Now finished the jsp taglibs

JSP Expressions:

JSP Expressions:


Basically whatever you put in JSP Expressions the code is evaluated and you get the value as a output so let's  say that I have a variable called int i=10 when I put variable i in JSP Expressions tags it is going to print 10 as a output but not variable i. So basically expressions whatver you put expressions in the expression tags and displays output value.

Explanation about the Expressions:

What are Expressions?
Ans: Whatever goes inside the "<%={java code here}>". Onething you have to note in jsp Expressions is whenever you put some in jsp expressions you do not put a semi colon( ;) at the end so that is not allowed.
Lets say if you want to print the value of variable i you can not say like this . <%=i;%>//invalid because of semicolon,
<%=i%>//ok
Code inside jsp expressions is evaluated, and output is displayed
Whatever you put inside expressions should evaluate to a value.
Basically sometimes you will need to print a certain texts on to the page, on to your web page, lets say the user logs in and after successfully login in on the login page or main page, we are going to display "Welcome username" , so while going to display this dynamic username you can not do it in static html because whatever you put in static html page will remain same for each and every user and you can not really change that value there so inorder to do that you need to insert dynamic content, whatever you enter the username we need to display that username in the main page so you can do that using scriptlets since you said that scriptlets whatever you code you put in scriptlets the expression is evaluated as a output  is displayed .

Example: <%=localVar %>
So eventhough we saw that how we can completely perform all the business logic processing and my java code within jsps it is not really recommended to do bulk of business logic of in your jsps because as we talk many times main role of jsp is it should be for presentation logic and not business logic. The role of the business logic is played by the servlets and its supporting classes and not by jsps . So jsp is only should use for presentation logic so inorder to present the jsp a webpage the user , inorder to present the dynamic web page to the user whatever dynamic certain amount of logic or certain amount of business logic we need to write in your jsp you can put that otherwise all the hard code business logic process should be done in servlets and other supporting java classes and we are going to simply call those methods from jsps .


JSP Directives

It is one of the important jsp element we have. JSP Directives basically commands to the JSP Engine. We will have complete details in future class.


Example for jsp elements:

<html><head><title>JSP Elements Example</title>
</head>
<body>
<%! int userCnt=0;%>  //declaration element

//scriptles
<%
    String name="Rajendra";
     userCnt++;
 %> //end of the scriptlet

<table>
 <tr><td>
  Welcome <%=name%> //here within <%=..%> is Expression element
     Your are user number<%=userCnt%>//Expression element
  </td></tr>
 </table>
</body>
</html>

/* output*/
Welcome Rajendra you are user number2

Explanation: here im the second person who has accessed web page it is going to display welcome Rajendra and you are user  number 2, lets say that some other guys comes in access this web page, is going to display: Welcome Rajendra you are user number 3. So for each request that comes it into this web page for everyone who login simple this web page and it is going to increase the userCont by one. By this time you would have triggered  at which place in this dynamic web page and it is use jsp elements and what type of jsp elements .

So we know that the variable userCnt is shared across multiple requests , in the same web page somebody else has to remember whats the previous count and it has to increase that count. So we know that using declaration elements we can share the variable across multiple requests . So im going to declare the userCnt variable  in the jsp declarations .
Next I have defined the value of Rajendra the variable called name, and this goes into the service() method, so for every new request this will be a new name, here simply I have defined Rajendra, but in real time, we need to fetch, whatever the user enter his username, that has to be displayed. And after each request increasing the userCnt by one.
And ultimately Iam goint to display the username and the userCnt. We know that we have to display value on to the screen we have to use JSP Expressions so I used jsp Expressions to display the name and the userCnt.


I hope you understood the jsp elements concepts.

JSP Scriptlets

JSP Scriptlets




  • Whatever code you put in Scriptlet it goes into the service() method so most of the time you would be writing scriptlet in your jsp pages because you know that when you are coding servlet at that time what you are doing is you are overriding the doGet() method or doPost() method which is similar to overriding the service() method.
  • Whatever you code write within these tags i.e: <%........> are treated as scriptlets.
  • In servlets most of the time you are overriding the doGet() or doPost() methods.
  • What do you do in the doGet() or doPost) method? you basically add your business logic to achieve the functionality that is to achieve the dynamic functionality. Similarly even in JSP whenever you want to add some java code most of the time you will be adding some business logic in your jsp pages and all your business logic is kept in the service() method because every new request, the service() method will be invoked and you want particular code to be executed whenever new request comes to the jsp page.


Explanations about the Scriptlets:

All the business logic which you want to put in java code in your jsp it could be in the scriptlets. We know that everything you write in scriptlets goes in the service(). Treat variables in scriptlets as method/local varialbes.
If I define any variables inside the scriptlets it could have gone in the service() so when I define variable i =10  in service2 , this variable i scope only in service2 only and it will not be visible in other service () methods  thus treat them as local variable or method level .

What do you put in scriptlets?
Ans:
Business logic in JSP are in scriptlets. Set of java statements.

Why do you need scriptlets?
Ans: 1. Need to perform some small business logic (if logic is complex, do in java). 2. Need to perform some basic validations.


So only reason is introduced java, in html was to produce dynamic pages content and when we say when we want to produce some dynamic content we need to perform some kind of validations, some kind of busines logic processing we can generate an output based on the the user input for that we need some kind of business logic that is the whole picture of scriptlets.

Example: <% int localVar=10;%>


JSP Declarations:

JSP Declarations:

Whatever you put the code in JSP Declarations that code goes out side the service() method.
Where did the service() method come from? we know that service () is present in servlets then How did we get service() method in jsp? becoz jsp is nothing but a servlet, so whatever code you put in your jsp at the end it is going to be converted servlet. And whatever you put in JSP  , it goes outside the service() method so what does it mean? Let's say that you have some method you want to define that can be used by at many different places. You dont want to put that same logic at multiple places in your code so in turn you want to reuse your code, so you put that reusable code in that a different method from different places so how can you achieve that? you can achieve that using jsp declarations. So declare a method using jsp declarations which will put that method outside the service method so basically it is a class level method and alternatively you can even have certain varaibles define in outside the service() method which will be used by through out the class.

1. What are JSP Declarations?
Ans: Whatever goes inside the "<%!{java code here}%>" tags  is called a declaration. Everything you write in a declarations goes outside the service(). Treat them as instance methods and instance variables.

2. Advantages of using JSP Declarations?
Ans: variable declaration is you can reuse the value across the multiple places.

3. What do you declare in declarations?
Ans: you can declare methods and variables in declarations.

4. Why do you need JSP Declarations?
Ans: If you have a variable that needs to be shared across different requests. You have repeated common code in you jsp, declare with in a method.

Ex: <%! int instanceVar=10;%>

Here the same value of 10 is reflected  when someother requests comes as well and how is it possible, how does the value retained across multiple requests you know that ultimately a jsp converts into a servlet. So whenever a new request servlet comes in, the service() method is invoked only. And  the state of that particular class remains the same that particular object remains the same we know that servlet is a multithreading environment so whenever you make a new request a new thread is born and the service() is invoked. And whatever the outside the service() whatever instance variable in your class will be shared across multiple requests.
you have repeated common code in your jsp, declare it in a method.. Ex: <%! int instanceVar=10;%>, so lets see how really works.



  • Here I have 3 requests, and lets assume that this page is one jsp page, and ultimately it got converted into a servlet, we know that servlets are multithreaded for every new request one new thread is called but the same servlet object.
  • So when request1 comes in it sponsores a new thread so basically I have a new service() method. When request2 comes in again I have new service() and ultimately when request 2 comes in, Im going to have a new service() method for request 3 as well. 
  • For each request it has it own service() method. So whatever is there within the service() method is not been shared across these three requests, different for each of the requests. Each request is unique now.
  • but when you come to declarations whatever you have in declarations is being shared by all these three requests . That is request 1 is going to share the same value, request 2 is going to share the same value, and request3 is going to shared the same value which you have in declarations.
  • So lets say that I have declared variable i and its value is 10 when its request 1 now when request 3 comes in tries to get the value of i , that is going to see the value of i that is 10 because declarations shared multiple requests.
  • Similarly if I would have put this value i=10 in service2() method, when i make the request 3 and I will not see the value 10 again that would be the default value probably zero.. Here if you declared any variables in side the service() methods that can not be shared multiple requests

jsp elements in details


 JSP elements


Lets we talk about jsp elements now in details
we learnt that jsp is nothing but html with some java code
we know how to build html pages,
How do you put the java code in the html page? Answer is we can do that by using jsp elements
with the introduction of jsp elements, we can put java code in  your static html page, which will makes yours static pages, dynamic web pages
we can build dynamic web pages using jsp elements in your static html files which static html pages, jsp pages means dynamic pages

TYPES OF JSP ELEMENTS

1. JSP Declarations
2. JSP Scriptlets
3. JSP Expressions
4. JSP Directives

1. Why do we have 4 different jsp elements?
Ans:
 Whenever you want to put java in your html page we use jsp elements. Could not be nice to have only one jsp element? and whenever i use java in my html page again simple i put that jsp element in my html page.  Basically each one of JSP Element has its own significance.

JSP Declarations:

Whatever you put the code in JSP Declarations that code goes out side the service() method.
Where did the service() method come from? we know that service () is present in servlets then How did we get service() method in jsp? becoz jsp is nothing but a servlet, so whatever code you put in your jsp at the end it is going to be converted servlet. And whatever you put in JSP  , it goes outside the service() method so what does it mean? Let's say that you have some method you want to define that can be used by at many different places. You dont want to put that same logic at multiple places in your code so in turn you want to reuse your code, so you put that reusable code in that a different method from different places so how can you achieve that? you can achieve that using jsp declarations. So declare a method using jsp declarations which will put that method outside the service method so basically it is a class level method and alternatively you can even have certain varaibles define in outside the service() method which will be used by through out the class.

1. What are JSP Declarations?
Ans: Whatever goes inside the "<%!{java code here}%>" tags  is called a declaration. Everything you write in a declarations goes outside the service(). Treat them as instance methods and instance variables.

2. Advantages of using JSP Declarations?
Ans: variable declaration is you can reuse the value across the multiple places.

3. What do you declare in declarations?
Ans: you can declare methods and variables in declarations.

4. Why do you need JSP Declarations?
Ans: If you have a variable that needs to be shared across different requests. You have repeated common code in you jsp, declare with in a method.

Ex: <%! int instanceVar=10;%>

Here the same value of 10 is reflected  when someother requests comes as well and how is it possible, how does the value retained across multiple requests you know that ultimately a jsp converts into a servlet. So whenever a new request servlet comes in, the service() method is invoked only. And  the state of that particular class remains the same that particular object remains the same we know that servlet is a multithreading environment so whenever you make a new request a new thread is born and the service() is invoked. And whatever the outside the service() whatever instance variable in your class will be shared across multiple requests.
you have repeated common code in your jsp, declare it in a method.. Ex: <%! int instanceVar=10;%>, so lets see how really works.


Figure: jsp2.jpg


  • Here I have 3 requests, and lets assume that this page is one jsp page, and ultimately it got converted into a servlet, we know that servlets are multithreaded for every new request one new thread is called but the same servlet object.
  • So when request1 comes in it sponsores a new thread so basically I have a new service() method. When request2 comes in again I have new service() and ultimately when request 2 comes in, Im going to have a new service() method for request 3 as well. 
  • For each request it has it own service() method. So whatever is there within the service() method is not been shared across these three requests, different for each of the requests. Each request is unique now.
  • but when you come to declarations whatever you have in declarations is being shared by all these three requests . That is request 1 is going to share the same value, request 2 is going to share the same value, and request3 is going to shared the same value which you have in declarations.
  • So lets say that I have declared variable i and its value is 10 when its request 1 now when request 3 comes in tries to get the value of i , that is going to see the value of i that is 10 because declarations shared multiple requests.
  • Similarly if I would have put this value i=10 in service2() method, when i make the request 3 and I will not see the value 10 again that would be the default value probably zero.. Here if you declared any variables in side the service() methods that can not be shared multiple requests



JSP Scriptlets




  • Whatever code you put in Scriptlet it goes into the service() method so most of the time you would be writing scriptlet in your jsp pages because you know that when you are coding servlet at that time what you are doing is you are overriding the doGet() method or doPost() method which is similar to overriding the service() method.
  • Whatever you code write within these tags i.e: <%........> are treated as scriptlets.
  • In servlets most of the time you are overriding the doGet() or doPost() methods.
  • What do you do in the doGet() or doPost) method? you basically add your business logic to achieve the functionality that is to achieve the dynamic functionality. Similarly even in JSP whenever you want to add some java code most of the time you will be adding some business logic in your jsp pages and all your business logic is kept in the service() method because every new request, the service() method will be invoked and you want particular code to be executed whenever new request comes to the jsp page.


Explanations about the Scriptlets:

All the business logic which you want to put in java code in your jsp it could be in the scriptlets. We know that everything you write in scriptlets goes in the service(). Treat variables in scriptlets as method/local varialbes.
If I define any variables inside the scriptlets it could have gone in the service() so when I define variable i =10  in service2 , this variable i scope only in service2 only and it will not be visible in other service () methods  thus treat them as local variable or method level .

What do you put in scriptlets?
Ans:
Business logic in JSP are in scriptlets. Set of java statements.

Why do you need scriptlets?
Ans: 1. Need to perform some small business logic (if logic is complex, do in java). 2. Need to perform some basic validations.


So only reason is introduced java, in html was to produce dynamic pages content and when we say when we want to produce some dynamic content we need to perform some kind of validations, some kind of busines logic processing we can generate an output based on the the user input for that we need some kind of business logic that is the whole picture of scriptlets.

Example: <% int localVar=10;%>

JSP Expressions:


Basically whatever you put in JSP Expressions the code is evaluated and you get the value as a output so let's  say that I have a variable called int i=10 when I put variable i in JSP Expressions tags it is going to print 10 as a output but not variable i. So basically expressions whatver you put expressions in the expression tags and displays output value.

Explanation about the Expressions:

What are Expressions?
Ans: Whatever goes inside the "<%={java code here}>". Onething you have to note in jsp Expressions is whenever you put some in jsp expressions you do not put a semi colon( ;) at the end so that is not allowed.
Lets say if you want to print the value of variable i you can not say like this . <%=i;%>//invalid because of semicolon,
<%=i%>//ok
Code inside jsp expressions is evaluated, and output is displayed
Whatever you put inside expressions should evaluate to a value.
Basically sometimes you will need to print a certain texts on to the page, on to your web page, lets say the user logs in and after successfully login in on the login page or main page, we are going to display "Welcome username" , so while going to display this dynamic username you can not do it in static html because whatever you put in static html page will remain same for each and every user and you can not really change that value there so inorder to do that you need to insert dynamic content, whatever you enter the username we need to display that username in the main page so you can do that using scriptlets since you said that scriptlets whatever you code you put in scriptlets the expression is evaluated as a output  is displayed .

Example: <%=localVar %>
So eventhough we saw that how we can completely perform all the business logic processing and my java code within jsps it is not really recommended to do bulk of business logic of in your jsps because as we talk many times main role of jsp is it should be for presentation logic and not business logic. The role of the business logic is played by the servlets and its supporting classes and not by jsps . So jsp is only should use for presentation logic so inorder to present the jsp a webpage the user , inorder to present the dynamic web page to the user whatever dynamic certain amount of logic or certain amount of business logic we need to write in your jsp you can put that otherwise all the hard code business logic process should be done in servlets and other supporting java classes and we are going to simply call those methods from jsps .


JSP Directives

It is one of the important jsp element we have. JSP Directives basically commands to the JSP Engine. We will have complete details in future class.


Example for jsp elements:

<html><head><title>JSP Elements Example</title>
</head>
<body>
<%! int userCnt=0;%>  //declaration element

//scriptles
<%
    String name="Rajendra";
     userCnt++;
 %> //end of the scriptlet

<table>
 <tr><td>
  Welcome <%=name%> //here within <%=..%> is Expression element
     Your are user number<%=userCnt%>//Expression element
  </td></tr>
 </table>
</body>
</html>

/* output*/
Welcome Rajendra you are user number2

Explanation: here im the second person who has accessed web page it is going to display welcome Rajendra and you are user  number 2, lets say that some other guys comes in access this web page, is going to display: Welcome Rajendra you are user number 3. So for each request that comes it into this web page for everyone who login simple this web page and it is going to increase the userCont by one. By this time you would have triggered  at which place in this dynamic web page and it is use jsp elements and what type of jsp elements .

So we know that the variable userCnt is shared across multiple requests , in the same web page somebody else has to remember whats the previous count and it has to increase that count. So we know that using declaration elements we can share the variable across multiple requests . So im going to declare the userCnt variable  in the jsp declarations .
Next I have defined the value of Rajendra the variable called name, and this goes into the service() method, so for every new request this will be a new name, here simply I have defined Rajendra, but in real time, we need to fetch, whatever the user enter his username, that has to be displayed. And after each request increasing the userCnt by one.
And ultimately Iam goint to display the username and the userCnt. We know that we have to display value on to the screen we have to use JSP Expressions so I used jsp Expressions to display the name and the userCnt.


I hope you understood the jsp elements concepts.