Thursday, May 27, 2010

JSP Example:Scriptless

Going straight from the request to the JSP without going through a servlet...

Case1: Using param Attribute

STEP1: Create a “dynamic web” project named “FirstBean”.

STEP 2: Create a new package named” com.examp” under Src or Source Folder.

STEP 3: Create a new html file named “SampleHtml.html” under WebContent folder.

< html >
< head >
< title >Entry Page< /title >
< /head >

< body >
< form action="TestBean.jsp" >
name: < input type="text" name="Username" >
ID#: < input type="text" name="UserID" >
< input type="submit" >
< /form >
< /body >
< /html >

STEP 4: Create a new java class named “Person.java” under Src folder.

package com.examp;

public abstract class Person {
private String name;
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}}

STEP 5: Create a new java class named “Employee.java” under Src folder.

package com.examp;

public class Employee extends Person {
private int empID;
public void setEmpID(int empID) {
this.empID = empID;
}
public int getEmpID() {
return empID;
} }

STEP 6: Create a new JSP file named “TestBean.jsp” under WebContent folder.

< body  >
< jsp:useBean id="person" type="com.examp.Person" class="com.examp.Employee" >
< jsp:setProperty name="person" property="name" param="Username" / >
< jsp:setProperty name="person" property="empID" param="UserID" / >
< /jsp:useBean >

Person is:
< jsp:getProperty name="person" property="name" / >
ID is :
< jsp:getProperty name="person" property="empID" / >
< /body >

STEP7: Include below code in a Xml file “web.xml” under WEB-INF folder.

< welcome-file-list >
< welcome-file >SampleHtml.html< /welcome-file >
< welcome-file >TestBean.jsp< /welcome-file >
< /welcome-file-list >

STEP 8 Export the project” FirstBean” into a war file named ” FirstBean.war” and place it in the deploy folder of JBOSS server.

STEP 9:To see the output use this url ” http://localhost:8080/ FirstBean / SampleHtml.html ” where FirstBean is the .war file name and SampleHtml.html is specified in the of web.xmlfile.

Step 10: Sample output is

Person is: Ammu ID is : 1

Bean tags convert primitive properties automatically

 
Case2 :With out using param attribute

We need to do following modifications
1: SampleHtml.html:-change the entire request parameter names match the bean property names.

< body >
< form action="TestBean.jsp" >
name: < input type="text" name="name" >
ID#: < input type="text" name="empID" >
< input type="submit" >
< /form >
< /body >

2: TestBean.jsp:-Modify the type as Employee instead of Person

< body >
< jsp:useBean id="person" type="com.examp.Employee" class="com.examp.Employee" >
< jsp:setProperty name="person" property="*" / >
< /jsp:useBean >
Person is:
< jsp:getProperty name="person" property="name" / >
ID is :
< jsp:getProperty name="person" property="empID" / >
< /body >

JSPExample:- Using standard actions and scripting

STEP 1: Create a “dynamic web” project named “FirstBean”.

STEP 2: Create a new package named” com.examp” under Src or Source Folder.

STEP 3: Create a new html file named “SampleHtml.html” under WebContent folder.

< html >
< head >
< title>Sample< /title >
< /head >

< body >
< form action="TestBean.jsp" >
Name: < input type="text" name="Username" >
ID#: < input type="text" name="UserID" >
<  input type="submit"  >
< /form >
< /body >
< /html >

STEP 4: Create a new java class named “Person.java” under Src folder.

package com.examp;
public abstract class Person {
private String name;
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
}

STEP 5: Create a new java class named “Employee.java” under Src folder

package com.examp;
public class Employee extends Person {
private int empID;
public void setEmpID(int empID) {
this.empID = empID;
}
public int getEmpID() {
return empID;
} }

STEP 6: Create a new JSP file named “TestBean.jsp” under WebContent folder

We can do it with a combination of standard actions and scripting
< body >
< jsp:useBean id="person" type="com.examp.Employee" class="com.examp.Employee"/ >
< % person.setName(request.getParameter("Username ")); % >
< % person.setEmpID(Integer.parseInt(request.getParameter("UserID "))); % >

Person:
< jsp:getProperty name="person" property="name" / >
ID is :
< jsp:getProperty name="person" property="empID" / >
< /body >
Or
We can even do it with scripting INSIDE a standard action:

< body >
< jsp:useBean id="person" type="com.examp.Employee" class="com.examp.Employee" >
< % person.setEmpID(Integer.parseInt(request.getParameter("UserID"))); % >
< jsp:setProperty name="person" property="name" value="" / >
< /jsp:useBean >

< jsp:getProperty name="person" property="name" / >
< jsp:getProperty name="person" property="empID" / >
< /body >

STEP7: Include below code in a Xml file “web.xml” under WEB-INF folder

< welcome-file-list >
< welcome-file >SampleHtml.html< /welcome-file >
< welcome-file >TestBean.jsp< /welcome-file >
< /welcome-file-list >

STEP 8 Export the project” FirstBean” into a war file named ” FirstBean.war” and place it in the deploy folder of JBOSS server.

STEP 9:To see the output use this url ” http://localhost:8080/ FirstBean / SampleHtml.html ”where FirstBean is the .war file name and SampleHtml.html is specified in the of web.xmlfile.

Step 10: Sample output is
Person is: Ammu ID is : 1

Scripting and Scriptless+JSP


Without standard actions (using scripting)

Case1: Servlet Setting a String as attribute and getting that string using JSP

Servlet code 
String name = request.getParameter(“userName”);
request.setAttribute(“name”, name);)

JSP 
< %= request.getAttribute(“name”) % >

Case2: Servlet Setting an Object as attribute and getting that Object using JSP

Servlet code 
foo.Person p = new foo.Person();
p.setName(“Evan”);
request.setAttribute(“person”, p);
JSP 
< % foo.Person p = (foo.Person) request.getAttribute(“person”); % >
Person is: < %= p.getName() % >
Or
Person is:< %= ((foo.Person) request.getAttribute(“person”)).getName() % >


With standard actions (no scripting)

Case1: Servlet Setting an Object as attribute and getting that Object using beans in JSP

Servlet code
foo.Person p = new foo.Person();
p.setName(“Evan”);
request.setAttribute(“person”, p);

JSP

< jsp:getProperty >
<  jsp:useBean id=”person” class=”foo.Person” scope=”request” /  >
<  jsp:getProperty name=”person” property=”name” /  > 

Case 2: JSP Setting an Object as attribute using beans

< jsp:setProperty >
< jsp:useBean id=”person” class=”foo.Person” scope=”request” / >
< jsp:setProperty name=”person” property=”name” value=”Fred” / >

If you put your setter code (< jsp:setProperty >) inside the body of < jsp:useBean >, the property values will be set only if a new bean is created. If an existing bean with that scope and id are found, the body of the tag will never run, so the property won’t be reset from your JSP code.

< jsp:useBean id=”person” class=”foo.Person” scope=”page”  >
< jsp:setProperty name=”person” property=”name” value=”Fred” / >
< /jsp:useBean  >

Adding a type attribute to < jsp:useBean >

< jsp:useBean id=”person” type=”foo.Person” class=”foo.Employee” scope=”page” >

Generated servlet based on above JSP code
foo.Person person = null;
// code to get the person attribute
if (person == null){
person = new foo.Employee();}

The scope attribute defaults to “page”

If you don’t specify a scope in either the < jsp:useBean > or < jsp:getProperty > tags,the Container uses the default of “page”.This
< jsp:useBean id=”person” class=”foo.Employee” scope=”page”/ >
Is the same as this
< jsp:useBean id=”person” class=”foo.Employee”/ >

Note: Be SURE that you remember:
In < jsp:useBean > attribute
type == reference type
class == object type

Wednesday, May 26, 2010

Sample Html Program using getElementsByName

< !--Simple Html Program using getElementsByName -- >

< html >

< head >
< script type="text/javascript" >
function getElements(){ 
            var DispayVar=document.getElementsByName("SampleInput")
            alert("\""+DispayVar[0].value+ "\" is the value you have entered!")
   }
< /script >
< /head >

< body >
< form >
Enter any value
< input name="SampleInput" type="text" size="20" >
<  input name="SampleInput" type="text" size="20"  >
< br >< br >< center >
< input name="mybutton" type="button" onclick="getElements()" value="Display" >
< /center >
< /form >
< /body >

< /html >

Output:-
Let us consider we have entered " Hello" in the firsttextbox then a pop window with " Hello is the value you have entered" will appear

Note:- getElementsByName()method returns a collection of objects with the same NAME attribute value .

Properties and Functions of getElementsByName Method

1. item: item function accepts a parameter as index of the item you want to get from the array of specified HTML elements.
E.g.:
var DispayVar =document. getElementsByName( "SampleInput" ). item(0)
alert(DispayVar.value);
above code will return the first element from the array collection having name attribute value "SampleInput".

2. tags: tags function of getElementsByName method also accepts one parameter as name of the HTML element e.g.: input or img. It returns only the specified HTML element from the array collection.
E.g.:
document. getElementsByName( "SampleInput" ). tags("img").
This function is the clone of Javascript getElementsByTagName method.

3. length: length property returns the number of HTML elements with specified name retrieved from the document.
E.g.:
document. getElementsByName( "SampleInput" ). length

Tuesday, May 25, 2010

Initializing your JSP

STEP1: Create a “dynamic web project ” named “JSPSample”

STEP 2: Create a new JSP file named “Init.jsp” under WebContent folder..

< %@ page language="java" contentType="text/html" %  >
< %!
public void jspInit() {
ServletConfig sConfig = getServletConfig();
String emailAddr = sConfig.getInitParameter("email");
ServletContext ctx = getServletContext();
ctx.setAttribute("mail", emailAddr);
}
% >
< %= application.getAttribute("mail") % >

STEP 3: Include below code in a Xml file “web.xml” under WEB-INF folder

< welcome-file-list >
           < welcome-file >Init.jsp< /welcome-file >
< /welcome-file-list >
< servlet >
          < servlet-name > Init < /servlet-name >
          < jsp-file >/ Init.jsp < /jsp-file >
         < init-param >
                    < param-name >email< /param-name >
                    < param-value >lucky@custom.com< /param-value >
        
< /servlet >
< servlet-mapping >
         < servlet-name > Init < /servlet-name >
         < url-pattern >/ Init.jsp < /url-pattern >
< /servlet-mapping >

STEP 4: Export the project” JSPSample” into a war file named ” JSPSample.war” and place it in the deploy folder of JBOSS server.

STEP 5:To see the output use this url ” http://localhost:8080/ JSPSample /Init.jsp ”,where JSPSample is the .war file name and Init.jsp is specified in the < welcome-file >of web.xmlfile.

Step 6: Output is given below

lucky@custom.com

A JSP is just a servlet in the end

The Container takes what you’ve written in your JSP, translates it into a servlet class source (.java) file, and then compiles that into a Java servlet class. After that, servlet runs in exactly the same way it would if you’d written and compiled the code yourself.

1:Scriptlet
Scriptlet code are just plain old Java that lands as-is within the generated servlet’s service method. The scriptlet code is between angle brackets with percent signs: < % and % >.

<  % out.println (Counter.getCount()); %  >
Where Counter is a class name and getCount () is a method present in Counter Class.

2:Expression
Expression code becomes the argument to a print () method. The expression adds an additional character to the start of the element—an equals sign (=).

<  %= Counter.getCount () %  >

When the Container sees above code then it turns it into this below code:

out.print (Counter.getCount ());
Note:-There is no need of semicolon at the end of Expression code

3: Declaration
JSP declarations are for declaring members of the generated servlet class. That means both variables and methods. In other words, anything between the tag is added to the class outside the service method. That means you can declare both static variables and methods.

< %! int count=0; % >
Note: using this we can create a counter that can increment each time we call the same page.

4: Use the page directive to import packages
A directive is a way for you to give special instructions to the Container at page translation time.
To import a single package: 
< %@ page import=”SamplePackage.*” % >

To import multiple packages:
< %@ page import=” SamplePackage.*, java.util.*” % >

Use a comma to separate the packages. The quotes go around the entire list of packages!

Directives come in three flavors: page, include, and taglib.
The taglib directive:-
Defines tag libraries available to the JSP.

< %@ taglib tagdir=”/WEB-INF/tags/hot” prefix=”hot” % >

The include directive:-
Defines text and code that gets added into the current page at translation time. This lets you build reusable chunks that can be added to each page without having to duplicate all that code in each JSP.

<  %@ include file=”SampleHeader.html” %  >

The page directive:-
Defines page-specific properties such as character encoding, the content type for this page’s response, and whether this page should have the implicit session object.

< %@ page import=”Sample.*” session=”false” % >

Main Attributes to the page directive

Import: -Defines the Java import statements that’ll be added to the generated servlet class.
isThreadSafe: -Defines whether the generated servlet needs to implement the SingleThreadModel. The default value is...”true”, which means, “My app is thread safe, so I do NOT need to implement SingleThreadModel, which I know is inherently evil.”
contentType : -Defines the MIME type (and optional character encoding) for the JSP response.
isELIgnored : -Defines whether EL expressions are ignored when this page is translated.
isErrorPage : -Defines whether the current page represents another JSP’s error page. The default value is “false”.
errorPage:-Defines a URL to the resource to which uncaught Throwables should be sent.

5:Expression Language
In order to avoid direct usage of java in Jsp, we can use Expression Language. The purpose of EL is to offer a simpler way to invoke Java code—but the code itself belongs somewhere else.

Example:-Please contact: ${applicationScope.mail}

6: Actions
They come in two flavors: standard and other action
Standard Action:
< jsp:include page=”Footer.jsp” / >
custom or Other Action:
< c:set var=”rate” value=”43” / >

Using < scripting-invalid >

You can make it invalid for a JSP to have scripting elements (Scriptlets, Java expressions, or declarations) by putting a tag in the DD:

< web-app ... > 
< jsp-config >< jsp-property-group >
< url-pattern > *.jsp< /url-pattern >
< scripting-invalid > true< /scripting-invalid >
< /jsp-property-group > < /jsp-config >
< /web-app >

A comment

You can put two different types of comments in a JSP:

<  !-- HTML comment --  > The Container just passes this straight on to the client, where the browser interprets it as a comment.

<  %-- JSP comment --%  >These are for the page developers, and just like Java comments in a Java source file, they’re stripped out of the translated page.

API for the generated servlet

The Container generates a class from your JSP that implements the HttpJspPage interface. This is the only part of the generated servlet’s API that you need to know.
All you need to know about are the three key methods:

jspInit()
  1. This method is called from the init() method.
  2. You can override this method. 
jspDestroy()
  1. This method is called from the servlet’s destroy() method.
  2. You can override this method as well.

_jspService()
  1. This method is called from the servlet’s service() method, which means it runs in a separate thread for each request. The Container passes the Request and Response objects to this method.
  2. You can’t override this method

Thursday, May 20, 2010

Song Of A Dream

Sarojinii Naidu was a great patriot, politician, orator and administrator. She had an integrated personality and could mesmerize audiences with her pure honesty and patriotism. She was a life-long freedom fighter, social worker and poet.

Words of Sarojini Naidu, in “Song Of A Dream”

Once in the dream of a night I stood
Lone in the light of a magical wood,
Soul-deep in visions that poppy-like sprang;
And spirits of Truth were the birds that sang,
And spirits of Love were the stars that glowed,
And spirits of Peace were the streams that flowed
In that magical wood in the land of sleep.

Lone in the light of that magical grove,
I felt the stars of the spirits of Love
Gather and gleam round my delicate youth,
And I heard the song of the spirits of Truth;
To quench my longing I bent me low
By the streams of the spirits of Peace that flow
In that magical wood in the land of sleep.

Wednesday, May 19, 2010

Rabindranath Tagore's Conversation with Albert Einstein

Tagore and Einstein met through a common friend, Dr. Mendel. Tagore visited Einstein at his residence at Kaputh in the suburbs of Berlin on July 14, 1930, and Einstein returned the call and visited Tagore at the Mendel home.

TAGORE: I was discussing with Dr. Mendel today the new mathematical discoveries which tell us that in the realm of infinitesimal atoms chance has its play; the drama of existence is not absolutely predestined in character.

EINSTEIN: The facts that make science tend toward this view do not say good-bye to causality.

TAGORE: Maybe not, yet it appears that the idea of causality is not in the elements, but that some other force builds up with them an organized universe.

EINSTEIN: One tries to understand in the higher plane how the order is. The order is there, where the big elements combine and guide existence, but in the minute elements this order is not perceptible.

TAGORE: Thus duality is in the depths of existence, the contradiction of free impulse and the directive will which works upon it and evolves an orderly scheme of things.

EINSTEIN: Modern physics would not say they are contradictory. Clouds look as one from a distance, but if you see them nearby, they show themselves as disorderly drops of water.

TAGORE: I find a parallel in human psychology. Our passions and desires are unruly, but our character subdues these elements into a harmonious whole. Does something similar to this happen in the physical world? Are the elements rebellious, dynamic with individual impulse? And is there a principle in the physical world which dominates them and puts them into an orderly organization?

EINSTEIN: Even the elements are not without statistical order; elements of radium will always maintain their specific order, now and ever onward, just as they have done all along. There is, then, a statistical order in the elements.

TAGORE: Otherwise, the drama of existence would be too desultory. It is the constant harmony of chance and determination which makes it eternally new and living.

EINSTEIN: I believe that whatever we do or live for has its causality; it is good, however, that we cannot see through to it.

TAGORE: There is in human affairs an element of elasticity also, some freedom within a small range which is for the expression of our personality. It is like the musical system in India, which is not so rigidly fixed as western music. Our composers give a certain definite outline, a system of melody and rhythmic arrangement, and within a certain limit the player can improvise upon it. He must be one with the law of that particular melody, and then he can give spontaneous expression to his musical feeling within the prescribed regulation. We praise the composer for his genius in creating a foundation along with a superstructure of melodies, but we expect from the player his own skill in the creation of variations of melodic flourish and ornamentation. In creation we follow the central law of existence, but if we do not cut ourselves adrift from it, we can have sufficient freedom within the limits of our personality for the fullest self-expression.

EINSTEIN: That is possible only when there is a strong artistic tradition in music to guide the people's mind. In Europe, music has come too far away from popular art and popular feeling and has become something like a secret art with conventions and traditions of its own.

TAGORE: You have to be absolutely obedient to this too complicated music. In India, the measure of a singer's freedom is in his own creative personality. He can sing the composer's song as his own, if he has the power creatively to assert himself in his interpretation of the general law of the melody which he is given to interpret.

EINSTEIN: It requires a very high standard of art to realize fully the great idea in the original music, so that one can make variations upon it. In our country, the variations are often prescribed.

TAGORE: If in our conduct we can follow the law of goodness, we can have real liberty of self-expression. The principle of conduct is there, but the character which makes it true and individual is our own creation. In our music there is a duality of freedom and prescribed order.

EINSTEIN: Are the words of a song also free? I mean to say, is the singer at liberty to add his own words to the song which he is singing?

TAGORE: Yes. In Bengal we have a kind of song-kirtan, we call it-which gives freedom to the singer to introduce parenthetical comments, phrases not in the original song. This occasions great enthusiasm, since the audience is constantly thrilled by some beautiful, spontaneous sentiment added by the singer.

EINSTEIN: Is the metrical form quite severe?

TAGORE: Yes, quite. You cannot exceed the limits of versification; the singer in all his variations must keep the rhythm and the time, which is fixed. In European music you have a comparative liberty with time, but not with melody.

EINSTEIN: Can the Indian music be sung without words? Can one understand a song without words?

TAGORE:  Yes, we have songs with unmeaning words, sounds which just help to act as carriers of the notes. In North India, music is an independent art, not the interpretation of words and thoughts, as in Bengal. The music is very intricate and subtle and is a complete world of melody by itself.

EINSTEIN: Is it not polyphonic?

TAGORE: Instruments are used, not for harmony, but for keeping time and adding to the volume and depth. Has melody suffered in your music by the imposition of harmony?

EINSTEIN: Sometimes it does suffer very much. Sometimes the harmony swallows up the melody altogether.

TAGORE: Melody and harmony are like lines and colors in pictures. A simple linear picture may be completely beautiful; the introduction of color may make it vague and insignificant. Yet color may, by combination with lines, create great pictures, so long as it does not smother and destroy their value.

EINSTEIN: It is a beautiful comparison; line is also much older than color. It seems that your melody is much richer in structure than ours. Japanese music also seems to be so.

TAGORE: It is difficult to analyze the effect of eastern and western music on our minds. I am deeply moved by the western music; I feel that it is great, that it is vast in its structure and grand in its composition. Our own music touches me more deeply by its fundamental lyrical appeal. European music is epic in character; it has a broad background and is Gothic in its structure.

EINSTEIN: This is a question we Europeans cannot properly answer, we are so used to our own music. We want to know whether our own music is a conventional or a fundamental human feeling, whether to feel consonance and dissonance is natural, or a convention which we accept.

TAGORE: Somehow the piano confounds me. The violin pleases me much more.

EINSTEIN: It would be interesting to study the effects of European music on an Indian who had never heard it when he was young.

TAGORE: Once I asked an English musician to analyze for me some classical music, and explain to me what elements make for the beauty of the piece.

EINSTEIN: The difficulty is that the really good music, whether of the East or of the West, cannot be analyzed.

TAGORE: Yes, and what deeply affects the hearer is beyond himself.

EINSTEIN: The same uncertainty will always be there about everything fundamental in our experience, in our reaction to art, whether in Europe or in Asia. Even the red flower I see before me on your table may not be the same to you and me.

TAGORE: And yet there is always going on the process of reconciliation between them, the individual taste conforming to the universal standard.

Monday, May 17, 2010

Cookie

A cookie is nothing more than a little piece of data (a name/value String pair) exchanged between the client and server. The server sends the cookie to the client, and the client returns the cookie when the client makes another request

Simple Custom Cookie Example

Step 1:Create a java class named "CookieTest " under src folder---> Servlet that creates and SETS the cookie

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CookieTest extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType(“text/html”);
String name = request.getParameter(“username”);
Cookie cookie = new Cookie(“username”, name);
cookie.setMaxAge(30*60);
response.addCookie(cookie);
RequestDispatcher view = request.getRequestDispatcher(“cookieresult.jsp”); view.forward(request, response);
} }

Step 2: Create a new JSP file named "cookieresult.jsp under WEB-INF folder --->JSP to render the view from this servlet.

< html >< body >
 < a href=”checkcookie.do” >click here< /a >
< /body >< /html >

Step 3: Create a java class named "CheckCookie" under src folder---> Servlet that GETS the cookie.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CheckCookie extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
Cookie[] cookies = request.getCookies();
if ( cookies != null ) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookie.getName().equals(“username”)) {
String userName = cookie.getValue(); out.println(“Hello “ + userName);
 break;
} } }} }

 Step 4 : Create a html file  named "Form.html" under WEB-INF folder---> Client to select username

< html >
< head >< meta http-equiv="Content-Type" content="text/html; " >
< title >User Selection< /title >
< /head >
< body >
< h1 align="center" >UserName SelectionPage< /h1 >
< form method="POST" action="CookieTest " >
Select any user< p >
User:
< select name="user" size="1" >
< option value="John" > John < /option >
< option value="Antony" > Antony< /option >
< option value="Rocky" > Rocky < /option >
< option value="Nicey" > Nicey< /option >
< /select >< br >< br >
< center >< input type="SUBMIT" >< /center >
< /form >< /body >< /html >

STEP 5: Include below code in a Xml file “web.xml” under WEB-INF folder.

<  web-app >
< welcome-file-list >
< welcome-file >Form.html< /welcome-file >
< welcome-file >cookieresult.jsp < /welcome-file >
< /welcome-file-list >
< servlet >
< servlet-name >CookieTest < /servlet-name >
< servlet-class >com.examp.CookieTest < /servlet-class >
< /servlet >
< servlet-mapping >
< servlet-name >CookieTest < /servlet-name >
< url-pattern >/CookieTest < /url-pattern >
< /servlet-mapping >
< servlet >
< servlet-name >CheckCookie< /servlet-name >
< servlet-class >com.examp.CheckCookie < /servlet-class >
< /servlet >
< servlet-mapping >
< servlet-name >CheckCookie< /servlet-name >
< url-pattern >/CheckCookie< /url-pattern >
< /servlet-mapping >
< /web-app >

STEP 6: Export the project” FirstSample” into a war file named ” FirstSample.war” and place it in the deploy folder of JBOSS server.

STEP 7: To see the output use this url ” http://localhost:8080/ FirstSample /Form.html”

Session Management

The HTTP protocol uses stateless connections. The client browser makes a connection to the server, sends the request, gets the response, and closes the connection. In other words, the connection exists for only a single request/response. Because the connections don’t persist, the Container doesn’t recognize that the client making a second request is the same client from a previous request. As far as the Container’s concerned, each request is from a new client. In order to recognize the another request from the same client we are using unique session id .

The idea is simple: on the client’s first request, the Container generates a unique session ID and gives it back to the client with the response. The client sends back the session ID with each subsequent request. The Container sees the ID, finds the matching session, and associates the session with the request. Somehow, the Container has to get the session ID to the client as part of the response, and the client has to send back the session ID as part of the request. The simplest and most common way to exchange the info is through cookies.

Below code is to know whether the session already existed or was just created.
HttpSession session = request.getSession();
if (session.isNew()) {
out.println(“This is a new session.”);
} else {
out.println(“Welcome back!”);
}

Checking whether the session is pre-existing one
HttpSession session = request.getSession(false);
if (session==null) {  
out.println(“no session was available”);  
out.println(“making one...”);  
session = request.getSession();  
} else {  
out.println(“there was a session!”);  
}

URL Rewriting:

URL rewriting adds the session ID to the end of all the URLs in the HTML that you write to the response.
If you use the session code—calling getSession() on the request—the Container tries to use cookies. If cookies aren’t enabled, it means the client will never join the session. In other words, the session’s isNew() method will always return true. In order to avoid this scenario we can use URL Rewriting


PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String id=session.getId();
out.println("< html >< body >");
out.println("< a href=\"" + response.encodeURL("Form.html")+" topic="+id +"\" >click me< /a >");

out.println("< /body >< /html >");

Note :-URL rewriting works with sendRedirect() is given below
response. encodeRedirectURL(“/output.jsp”);


Three ways a session can die: 
  • It times out 
  • You call invalidate() on the session object
  • The application goes down (crashes or is undeployed)
Configuring session timeout in the DD
<  web-app ... > 
< servlet
< /servlet
 < session-config >  
<  session-timeout >15&lt; /session-timeout >
<  /session-config
<  /web-app>


 Setting session timeout for a specific session
session.setMaxInactiveInterval(20*60) where arg in seconds

Friday, May 14, 2010

ServletContextListener Example

Context parameters can’t be anything except Strings. So if we want to run some such as database connection before running the rest of application, then the scope of “listeners” come into picture.

If we wants to listen for a context initialization event, so that we can get the context init parameters and run some code before the rest of the application can service a client. In this case we need a listener named “ServletContextListener” 

ServletContextListener Class Structure 

We can make a separate class, not a servlet or JSP, that can listen for the two key events in a ServletContext’s life— initialization (creation) and destruction. That separate class implements javax.servlet.ServletContextListener.  

We need a separate object that can: 

Get notified when the context is initialized (app is being deployed). 
  • Get the context init parameters from the ServletContext. 
  • Use the init parameter lookup name to make a database connection. 
  • Store the database connection as an attribute, so that all parts of the web app can access it.  
Get notified when the context is destroyed (the app is undeployed or goes down). 
  •  Close the database connection.
 ServletContextListener Example:-

STEP1: Create a “dynamic web” project named “ListenerSample”. 

STEP 2: Create a new package named” com.examp” under Src or Source Folder.

STEP 3: ServletContextListener :-Create a new java class named “MyServletContextListener” under Src folder. This class implements ServletContextListener, gets the context init parameters, creates the DBconnection object and sets that object as context attribute.

package com.examp;

import javax.servlet.*;
public class MyServletContextListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent event) {
//code to initialize the database connectionand store it as a context attribute 
ServletContext sc = event.getServletContext();
 String Dbname = sc.getInitParameter("DbName");
 DBconnection d = new DBconnection( Dbname);
 sc.setAttribute("Database", d);
 }

 public void contextDestroyed(ServletContextEvent event) {
// close db connection
 }
 }

 STEP 4: Attribute class: Create a new java class named “DBconnection”. This class job is to be the attribute value that the ServletContextListener instantiates and sets in the ServletContext, for the servlet to retrieve.

package com.examp;

public class DBconnection {
private String DbName;
public DBconnection(String DbName) {
 this.DbName = DbName;
 }
 public String connection() {
 //write code for DB connection here
 this.DbName=DbName.concat("is connected");
 return DbName;
 }
 }

STEP 5: Servlet Progarm :-Create new Java program namer "ServletController" under Src folder.

package com.examp;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletController extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("test context attributes set by listener
"); out.println("
");

DBconnection Db = (DBconnection) getServletContext().getAttribute("Database");
out.println("Database is: " + Db.connection());
}

STEP 6: Include below code in a Xml file “web.xml” under WEB-INF folder:

< web-app > 
< context-param  > 
< param-name >DbName< /param-name > 
< param-value >MyDatabase< /param-value > 
< /context-param > 
< listener > 
< listener-class > com.examp.MyServletContextListener< /listener-class >
 < /listener >
 < /web-app >

STEP 7: Export the project” ListenerSample” into a war file named ” ListenerSample” and place it in the deploy folder of JBOSS server.

STEP 8:To see the output use this url ” http://localhost:8080/ ListenerSample/Hello” ,where ListenerSample is the .war file name and Hello is specified in the < url-pattern >of web.xmlfile.

 STEP 9: Output :-

 Test context attributes set by listener
 Database is: MyDatabaseis connected

Thursday, May 13, 2010

Swami Vivekananda’s Speech in Chicago

 
Swami Vivekananda's opening talk is a benchmark, in that he was one of the earlier teachers to come to America from the East, and the first swami to visit America. Most notably, this was his first talk in America. After the welcome address of the opening of the World Parliament of religions, Swami Vivekananda spoke, and started with these few words: “Sisters and Brothers of America.” The 7,000 people in the audience, immediately feeling the depth of his sincerity, rose to their feet and according to reports, “went into inexplicable rapture with standing ovation and clapping that lasted for more than three minutes.”

Swami Vivekananda’s message on September 11, 1893:

“Sisters and Brothers of America,

It fills my heart with joy unspeakable to rise in response to the warm and cordial welcome which you have given us. I thank you in name of the most ancient order of monks in the world; I thank you in the name of the mother of religions; and I thank you in the name of millions and millions of Hindu people of all classes and sects.

My thanks,also,to some of the speakers on this platform who, referring to the delegates from the Orient, have told you that these men from far-off nations may well claim the honor of bearing to different lands the idea of toleration.

I am proud to belong to a religion which has taught the world both tolerance and universal acceptance. We believe not only in universal toleration but we accept all religions as true. I am proud to belong to a nation which has sheltered the persecuted and the refugees of all religions and all nations of the earth. I am proud to tell you that we have gathered in our bosom the purest remnant of the Israelites who came to Southern India and took refuge with us in very year in which their holy temple was shattered to pieces by Roman tyranny. I am proud to belong to the religion which has sheltered and is still fostering the remnant of the grand Zoroastrian nation.

I will quote to you brethren a few lines from a hymn which I remember to have repeated from my earliest childhood, which is every day repeated by millions of human beings: 'As the different streams having their sources in different places all mingle their water in the sea, so, O Lord, the different paths which men take through different tendencies, various though they appear, crooked or straight, all lead to Thee.'

The present convention, which is one of the most august assemblies ever held, is in itself a vindication, a declaration to the world of the wonderful doctrine preached in the Gita: 'Whosoever comes to me, though whatsoever form, I reach him; all men are struggling through paths which in the end lead to me.'

Sectarianism, bigotry, and it's horrible descendant, fanaticism, have long possessed this beautiful Earth. They have filled the earth with violence, drenched it often and often with human blood, destroyed civilization, and sent whole nations to despair. Had it not been for these horrible demons, human society would be far more advanced than it is now.

But their time is come; and I fervently hope that the bell that tolled this morning in honor of this convention may be the death-knell of all fanaticism, of all persecutions with the sword or with the pen, and of all uncharitable feelings between persons wending their way to the same goal."

Difference between servlet init parameters and context init parameters

Context init parameters work just like servlet init parameters, except context parameters are available to the entire webapp, not just a single servlet. So that means any servlet and JSP in the app automatically has access to the context init parameters, so we don’t have to worry about configuring the Deployment Descriptor for every servlet, and when the value changes, you only have to change it one place!.

Difference No#1:- Deployment Descriptor

Context init parameter 
Within the < web-app > element but NOT within a specific < servlet > element

< web-app >
< context-param >
< param-name >Country< /param-name >
< param-value >India
< /context-param >
< !-- other stuff including servlet declarations -- >
< /web-app >
 Servlet init parameters
Within the < servlet > element for each specific servlet

< servlet>
< servlet-name >ServletController< /servlet-name >
< servlet-class >com.examp.ServletController< /servlet-class >
< init-param >
< param-name >Country< /param-name >
< param-value >India< /param-value >
< /init-param >
< /servlet >

 
Difference No#2 :- Servlet code

 
Context init parameter
getServletContext().getInitParameter(“foo”);

Servlet init parameters
getServletConfig().getInitParameter(“foo”);

Difference No#3:- Availability

Context init parameter
To any servlets and JSPs that are part of this web app.

Servlet init parameters
To only the servlet for which the was configured. Although the servlet can choose to make it more widely available by storing it in an attribute.

ServletConfig :initialization parameters

      Main job of ServletConfig is to give you init parameters

Example for one init parameter

Step1: Insert below code in the Deployment descriptor web.xml. .Just make sure it’s inside the < servlet > element in the DD.

< servlet >
< servlet-name >ServletController< /servlet-name >
< servlet-class >com.examp.ServletController< /servlet-class >
< init-param >
< param-name >Country< /param-name >
< param-value >India< /param-value >
< /init-param >
< /servlet >

Step2: Insert the following code in the Servlet program’

PrintWriter out = response.getWriter();
out.println(getServletConfig().getInitParameter(“Country”));

Step 3: Output is given below

India

Example for more than one init parameter

Step1: Insert below code in the Deployment descriptor web.xml.  Just make sure it’s inside the < servlet > element in the DD.

< servlet >
< servlet-name >ServletController< /servlet-name >
< servlet-class >com.examp.ServletController< /servlet-class >
< init-param >
< param-name >Country< /param-name >
< param-value >India< /param-value >
< /init-param >
< init-param >
< param-name >State< /param-name >
< param-value >Kerala< /param-value >
< /init-param >
< /servlet >

Step2: Insert the following code in the Servlet program

PrintWriter out = response.getWriter();

//getting parameter name
java.util.Enumeration e = getServletConfig().getInitParameterNames();

while(e.hasMoreElements()) {
String element=(String) e.nextElement();
out.println(""+element+ getServletConfig().getInitParameter(element));
out.println("< br >");
}

Step3: Output is given below

Country India
State Kerala

Wednesday, May 12, 2010

Sparks :---Chetan Bhagat Speech

Speech given at the orientation program for the new batch of MBA students Symbiosis, Pune, July 24, 2008

Good Morning everyone and thank you for giving me this chance to speak to you. This day is about you. You, who have come to this college, leaving the comfort of your homes (or in some cases discomfort), to become something in your life. I am sure you are excited. There are few days in human life when one is truly elated. The first day in college is one of them. When you were getting ready today, you felt a tingling in your stomach. What would the auditorium be like, what would the teachers be like, who are my new classmates – there is so much to be curious about. I call this excitement, the spark within you that makes you feel truly alive today. Today I am going to talk about keeping the spark shining. Or to put it another way, how to be happy most, if not all the time.

Where do these sparks start? I think we are born with them. My 3-year old twin boys have a million sparks. A little Spiderman toy can make them jump on the bed. They get thrills from creaky swings in the park. A story from daddy gets them excited. They do a daily countdown for birthday party – several months in advance – just for the day they will cut their own birthday cake.

I see students like you, and I still see some sparks. But when I see older people, the spark is difficult to find. That means as we age, the spark fades. People whose spark has faded too much are dull, dejected, aimless and bitter. Remember Kareena in the first half of Jab We Met vs the second half? That is what happens when the spark is lost. So how to save the spark?

Imagine the spark to be a lamp’s flame. The first aspect is nurturing – to give your spark the fuel, continuously. The second is to guard against storms.

To nurture, always have goals. It is human nature to strive, improve and achieve full potential. In fact, that is success. It is what is possible for you. It isn’t any external measure – a certain cost to company pay package, a particular car or house.

Most of us are from middle class families. To us, having material landmarks is success and rightly so. When you have grown up where money constraints force everyday choices, financial freedom is a big achievement. But it isn’t the purpose of life. If that was the case, Mr. Ambani would not show up for work. Shah Rukh Khan would stay at home and not dance anymore. Steve Jobs won’t be working hard to make a better iPhone, as he sold Pixar for billions of dollars already. Why do they do it? What makes them come to work everyday? They do it because it makes them happy. They do it because it makes them feel alive Just getting better from current levels feels good. If you study hard, you can improve your rank. If you make an effort to interact with people, you will do better in interviews. If you practice, your cricket will get better. You may also know that you cannot become Tendulkar, yet. But you can get to the next level. Striving for that next level is important.

Nature designed with a random set of genes and circumstances in which we were born. To be happy, we have to accept it and make the most of nature’s design. Are you? Goals will help you do that. I must add, don’t just have career or academic goals. Set goals to give you a balanced, successful life. I use the word balanced before successful. Balancedmeans ensuring your health, relationships, mental peace are all in good order.

There is no point of getting a promotion on the day of your breakup. There is no fun in driving a car if your back hurts. Shopping is not enjoyable if your mind is full of tensions.

You must have read some quotes – Life is a tough race, it is a marathon or whatever. No, from what I have seen so far, life is one of those races in nursery school, where you have to run with a marble in a spoon kept in your mouth. If the marble falls, there is no point coming first. Same with life, where health and relationships are the marble. Your striving is only worth it if there is harmony in your life. Else, you may achieve the success, but this spark, this feeling of being excited and alive, will start to die.

One last thing about nurturing the spark – don’t take life seriously. One of my yoga teachers used to make students laugh during classes. One student asked him if these jokes would take away something from the yoga practice. The teacher said – don’t be serious, be sincere. This quote has defined my work ever since. Whether its my writing, my job, my relationships or any of my goals. I get thousands of opinions on my writing everyday. There is heaps of praise, there is intense criticism. If I take it all seriously, how will I write? Or rather, how will I live? Life is not to be taken seriously, as we are really temporary here. We are like a pre-paid card with limited validity. If we are lucky, we may last another 50 years. And 50 years is just 2,500 weekends. Do we really need to get so worked up? It’s ok, bunk a few classes, goof up a few interviews, fall in love. We are people, not programmed devices.

I’ve told you three things – reasonable goals, balance and not taking it too seriously that will nurture the spark. However, there are four storms in life that will threaten to completely put out the flame. These must be guarded against. These are disappointment, frustration, unfairness and loneliness of purpose.

Disappointment will come when your effort does not give you the expected return. If things don’t go as planned or if you face failure. Failure is extremely difficult to handle, but those that do come out stronger. What did this failure teach me? is the question you will need to ask. You will feel miserable. You will want to quit, like I wanted to when nine publishers rejected my first book. Some IITians kill themselves over low grades – how silly is that? But that is how much failure can hurt you. But it’s life. If challenges could always be overcome, they would cease to be a challenge. And remember – if you are failing at something, that means you are at your limit or potential. And that’s where you want to be.

Disappointment’ s cousin is Frustration, the second storm. Have you ever been frustrated? It happens when things are stuck. This is especially relevant in India. From traffic jams to getting that job you deserve, sometimes things take so long that you don’t know if you chose the right goal. After books, I set the goal of writing for Bollywood, as I thought they needed writers. I am called extremely lucky, but it took me five years to get close to a release. Frustration saps excitement, and turns your initial energy into something negative, making you a bitter person. How did I deal with it? A realistic assessment of the time involved – movies take a long time to make even though they are watched quickly, seeking a certain enjoyment in the process rather than the end result – at least I was learning how to write scripts, having a side plan – I had my third book to write and even something as simple as pleasurable distractions in your life – friends, food, travel can help you overcome it. Remember, nothing is to be taken seriously. Frustration is a sign somewhere, you took it too seriously.

Unfairness – this is hardest to deal with, but unfortunately that is how our country works. People with connections, rich dads, beautiful faces, pedigree find it easier to make it – not just in Bollywood, but everywhere. And sometimes it is just plain luck. There are so few opportunities in India, so many stars need to be aligned for you to make it happen. Merit and hard work is not always linked to achievement in the short term, but the long term correlation is high, and ultimately things do work out. But realize, there will be some people luckier than you. In fact, to have an opportunity to go to college and understand this speech in English means you are pretty damm lucky by Indian standards. Let’s be grateful for what we have and get the strength to accept what we don’t. I have so much love from my readers that other writers cannot even imagine it. However, I don’t get literary praise. It’s ok. I don’t look like Aishwarya Rai, but I have two boys who I think are more beautiful than her. It’s ok. Don’t let unfairness kill your spark.

Finally, the last point that can kill your spark is Isolation. As you grow older you will realize you are unique. When you are little, all kids want Ice cream and Spiderman. As you grow older to college, you still are a lot like your friends. But ten years later and you realize you are unique. What you want, what you believe in, what makes you feel, may be different from even the people closest to you. This can create conflict as your goals may not match with others. And you may drop some of them. Basketball captains in college invariably stop playing basketball by the time they have their second child. They give up something that meant so much to them. They do it for their family. But in doing that, the spark dies. Never, ever make that compromise. Love yourself first, and then others.

There you go. I’ve told you the four thunderstorms – disappointment, frustration, unfairness and isolation. You cannot avoid them, as like the monsoon they will come into your life at regular intervals. You just need to keep the raincoat handy to not let the spark die.

I welcome you again to the most wonderful years of your life. If someone gave me the choice to go back in time, I will surely choose college. But I also hope that ten years later as well, your eyes will shine the same way as they do today. That you will Keep the Spark alive, not only through college, but through the next 2,500 weekends. And I hope not just you, but my whole country will keep that spark alive, as we really need it now more than any moment in history. And there is something cool about saying – I come from the land of a billion sparks.

Thank You.