Showing posts with label servlets. Show all posts
Showing posts with label servlets. Show all posts

June 12, 2012

Exercises -- J2EE


Exercises: Getting Started
Do items 1-4 in order, then try whichever of the remaining exercises grab your interest and you
have time for. See C:\Servlets+JSP\Exercise-Solutions\lecture1 for solutions.
1. Open the C:\Servlets+JSP\ directory and double-click the icon to start Tomcat. Verify that the
server is running by opening http://localhost/ in your browser.
2. Open http://archive.coreservlets.com in your browser (or use your local copy if you have one),
then right-click on HelloWorld.java (Chapter 2) to download it to the C:\Servlets+JSP directory.
Compile it using “javac HelloWorld.java” (DOS Window) or with “javac “%f”” (from
the UltraEdit Advanced/DOS Command menu), and copy the .class file to
tomcat_install_dir\webapps\ROOT\WEB-INF\classes (there should be a shortcut in C:\Servlets+
JSP to make this task easier). Then, check that the servlet is working by using the URL
http://localhost/servlet/HelloWorld.
3. Download HelloWWW.java into the C:\Servlets+JSP directory, edit it so that it outputs “Hello
YourName”, compile it, and copy the .class file to the shortcut to .../WEB-INF/classes. Execute
the servlet with http://localhost/servlet/HelloWWW.
4. Create a “coreservlets” directory within C:\Servlets+JSP. Open http://archive.coreservlets.com
in your browser (or use your local copy if you have one), then right-click on Servlet-
Utilities.java and HelloWWW3.java (Chapter 2) in order to download them to that directory.
Compile HelloWWW3.java and copy both HelloWWW3.class and ServletUtilities.class to
tomcat_install_dir\webapps\ROOT\WEB-INF\classes\coreservlets.
The easiest way is to just copy the entire coreservlets directory into
tomcat_install_dir\webapps\ROOT\WEB-INF\classes. Do this by using the right mouse to
drag the coreservlets directory onto the shortcut to the WEB-INF\classes directory and selecting
“Copy.”
Verify that the process works by invoking http://localhost/servlet/coreservlets.HelloWWW3.
5. Create a subdirectory called “exercise1” within C:\Servlets+JSP, put a simple servlet in it (be
sure to have the package name correspond to the directory name), compile it, and copy the
.class file to the appropriate location within the Tomcat directory. The easiest approach is to
copy the entire exercise1 directory onto the shortcut to the WEB-INF\classes directory. If you
want to use ServletUtilities, either copy ServletUtilities to your directory and change “package
coreservlets” to “package yourPackage”, or (better!) add “import coreservlets.*” to whichever
of your servlets use ServletUtilities.
6. Create a servlet that uses a loop to output an HTML table with 25 rows. For instance, each row
could contain “RowX, Col1”, “RowX Col2”, and “RowX Col3”, where X is the current row
number.

Exercises: Form Data
Try the first exercise and whichever others best fit your interests, background, and available
time.
1. Download ThreeParamsForm.html from the Core Servlets and JSP archive site and
install it in tomcat_install_dir\webapps\ROOT. Load it by means of the URL
http://localhost/ThreeParamsForm.html. Install the ThreeParams servlet and verify
that you can send data to it.
2. Change the ThreeParams servlet to reside in your package/directory. Make appropriate
changes to the form that sends data to it. Test it.
3. Change the ThreeParams form and servlet to use POST instead of GET. If you aren’t
very familiar with HTML, see the METHOD attribute on page 391 of Core Servlets
and JavaServer Pages. What changes do you need to make to your servlet to have it
accept POST instead of GET?
4. Make a “registration” form that collects a first name, last name, and email address.
Send the data to a servlet that displays it. Feel free to modify the ThreeParams
HTML form and servlet to accomplish this. Next, modify the servlet to use a default
value (or send an error message) if the user omits any of the three required parameters.
5. Use the ThreeParams form to send data to the ThreeParams servlet that contains
HTML-specific characters. Verify that this can cause malformed results. Modify the
servlet to filter the strings before displaying them.

Exercises: Request Headers
Do whichever exercises fit your background and interests. They are ordered in approximate
order of difficulty. As always, feel free to experiment on your own with other related
exercises.
1. Install the servlet that shows all request headers (ShowRequestHeaders). Access it
from both Netscape and Internet Explorer. Remember that, since the servlet is in the
coreservlets package, you have to install it in the coreservlets directory and use the
URL http://hostname/servlet/coreservlets.ShowRequestHeaders.
2. Make a tiny Web page that contains a hypertext link to the servlet that shows all
request headers. What new header shows up that wasn’t there previously? Remember
that HTML documents (and images, JSP pages, etc.) go in
tomcat-install-dir\webapps\ROOT.
3. Write a servlet that sends a different result to Internet Explorer users than to Netscape
users. If you prefer one browser over the other, feel free to have the servlet insult
users of the other browser. Hint: review printout of request headers from slides.
4. Write a servlet that checks the Referer header to know which banner ad to display.
Link to it from a couple of different Web pages, and display different images depending
on how the user got to the servlet. Collect images by right-clicking on them in
your browser and saving them to a banner-ads subdirectory of the server’s root directory
(not the server’s classes directory!). You can use
to refer to the images.
Note: in Java, you insert a double quote into a String by putting a backslash in front.

Exercises: The HTTP Response
Do whichever exercises fit your background and interests. You are not expected to do
nearly all of them.
1. Write a servlet that sends half the users to http://home.netscape.com and half to
http://www.microsoft.com. Choose at random (compare the output of Math.random()
to 0.5).
2. Write a servlet that sends Netscape users to http://home.netscape.com and Internet
Explorer users to http://www.microsoft.com (or, vice versa :-).
3. Write a servlet that returns a “page not found” error page (404) unless the user supplies
a favoriteLanguage request (form) parameter with a value of “Java.” Note:
some Tomcat versions incorrectly omit the user-supplied error message string.
4. Write a servlet that generates an Excel spreadsheet. Use the appropriate MIME type
from the table in the notes. Use plain text rows with entries separated by tabs (\t in a
Java string). Try it from both Netscape and Internet Explorer. You need to have MS
Office installed for this to work. Hint: this one is easy.
5. Write a servlet that instructs the browser to reconnect every five seconds. Display the
time (print new java.util.Date()) on each connection.
6. Write a servlet that returns a page to Internet Explorer users saying they will be sent
to http://www.microsoft.com after 10 seconds. Send them there after that timeout.
Send Netscape users to http://home.netscape.com after the same delay. You’ll have to
read about the Refresh header in the book (page 152) to see the option of supplying a
specific URL to connect to.
7. If you are familiar with Java I/O, write a servlet that returns an image (reading it from
the disk). Since you will be sending binary data, use getOutputStream instead of get-
Writer to get the stream that sends the image. Use the appropriate MIME type. This
one is probably too hard unless you already know how to read files from disk.

Exercises: Cookies
These exercises are longer than most. Start with one of the first four, then the last one, then
come back to the others if you have time. Number five is easy if you’ve done number one;
number four is easy if you’ve done number two.
1. Make a servlet that says “Welcome aboard” to first-time visitors and “Welcome
back” to repeat visitors. First verify that it works within a browsing session, then quit
your browser and restart to verify that the cookie is persistent on disk.
2. Write a servlet that displays the values of the firstName, lastName, and emailAddress
request parameters. If a parameter is missing and the client is a first-time visitor, have
the servlet list “Unknown” for the missing values. If a parameter is missing and the
client is a repeat visitor, have the servlet use previously-entered values for the missing
values.
3. Make a servlet that keeps per-client access counts. That is, have it print “This is visit
number x to this page.” Visit it several times each with Netscape and Internet
Explorer to verify that it is keeping separate counts for each.
4. Make an HTML form that lets you send a background color and foreground color to
a servlet that displays a Web page in those colors. If you go straight to the servlet
without going through the HTML form, have the servlet use cookie values to provide
reasonable default color choices (i.e., your previous choice if you made one). If you
aren’t too familiar with HTML, you set the colors as follows:

or

(where R, G, and B are hex values for the red, green and blue components. I.e.,
#FF00FF is magenta -- 255 for red, 0 for green, and 255 for blue).
5. Repeat exercise number one, but with session cookies, not persistent cookies. Visit it
twice in Internet Explorer, then click on the IE icon on the desktop to start a new
browser. Is this considered the same session or a new one? Repeat the process with
Netscape. Notice that they work differently.
6. Check out your cookie files in IE and Netscape. On IE, start at the Tools menu, then
do Internet Options, General, Settings, View Files. It is easier to find the cookie files
if you do “Delete Files” first. On Netscape, do a search (“Find”) for a file called
cookies.txt in a Netscape folder. See if you notice a cookie from doubleclick.net in
both cases. Take a look at the structure of these files to see if you can figure out how
they represent the various cookie parameters.

Exercises: Session Tracking
1. Make a servlet that says “Welcome Aboard” to first-time visitors (within a browsing
session) and “Welcome Back” to repeat visitors. Was this servlet harder or easier than
the equivalent version using cookies explicitly?
2. Write a servlet that displays the values of the firstName, lastName, and emailAddress
request parameters. Have the servlet list “Unknown” for missing values of first-time
visitors and the previously entered values for repeat visitors. This should definitely
be easier than the version that used cookies explicitly.
3. Make an HTML form containing a textfield and a submit button, where the textfield
is intended to gather the name of an item to be purchased. Every time you submit an
item, have the servlet show a table or list containing that item plus all previously
“purchased” items. If you feel truly inspired, you can check to see if the current item
matches a previous item, and display a number indicating how many of that item are
being purchased. Don’t forget to put the HTML form in
tomcat_install_dir\webapps\ROOT and to access it through a URL of the form
http://localhost/YourForm.html. Do not read the HTML form directly from disk—if
you do, the browser won’t know how to interpret the ACTION="/servlet/..." part of
the form. If you are unfamiliar with the list-related data structures in Java, see note at
bottom regarding the Vector class.
4. Make a servlet that prints a list of the URLs of all pages that the current user has used
to link to it. That is, for each user, have it keep track of all unique values of the Referer
request header. Test it out by making a couple of different static Web pages, each
of which link to it via click to visit servlet.
Put your pages in tomcat_install_dir\webapps\ROOT and access them through a
URL of the form http://localhost/YourPage.html.
Note: Using the Vector Class
The java.util.Vector class (or java.util.ArrayList if you know you are using JDK 1.2 or
later) is useful for keeping lists of items when you don’t know how many items you will
have. It has several key methods:
• Constructor: empty. Eg Vector v = new Vector();
• Adding items to end of vector: call “add”. Eg v.add("Item One");
• Number of items in in vector: call “size”. Eg int numItems = v.size();
• Get an item out: elementAt. Eg String item = (String)v.elementAt(0);

Exercises: JSP Intro
1. Download Expressions.jsp and install it on your server in
tomcat_install_dir\webapps\ROOT. Also download the JSP-Styles.css file that
Expressions.jsp uses. Access Expressions.jsp through the appropriate URL. Compare
the time it takes to access it the first time to the time it takes on subsequent requests.
Try supplying a value for the testParam form parameter.
2. Question to ponder: if you wanted to use style sheets from regular servlets, where
would you put the style sheet and how would you refer to it from the servlet? How
about images? Notice how much simpler the process is with JSP.
3. Make a very simple static HTML page. Download one from the Web if you want.
Rename it to have a .jsp extension. Have an HTML form with nothing but a SUBMIT
button that directs the user to the static page. Now, change the form to use
POST instead of GET (see Listing 16.2 on page 388 and the METHOD section on
page 391 if you don’t remember how to tell the form to use POST). Why does it work
both times? (Answer: the auto-generated code can’t just be in the doGet method.
Where does the auto-generated code go, then?)

Exercises:
JSP Scripting Elements
1. Make a JSP page that shows a random number between 0 and 1.
2. Make a JSP page that displays the values of the param1, param2, and param3 form
parameters. That is, change the ThreeParams servlet into a JSP page that has the same
result. Modify the ThreeParams HTML form to send data to that JSP page. You’ll
probably find that the JSP version is much cleaner and simpler than the equivalent
servlet.
3. Make a JSP page that makes a bulleted list with a random number of entries in the list,
each of which is a random int. To generate a random int, use Math.random, multiply,
cast the result to an int, and add 1. You’ll probably find that this JSP page is not nearly
as clean and simple as that of #1. Why?
4. Define a method called randomInt that takes a number as an argument and returns a
random int from 1 to that number (use Math.random, multiply, cast the result to an int,
and add 1). Redo problem #3 using that method.
5. Make a JSP page that displays a random number the first time anyone visits it, and displays
the same number on all subsequent visits (hint: you don’t need cookies or session
tracking).
6. Make a JSP page that always displays the same page content, but uses a background
color of green, red, blue, or yellow, randomly chosen for each request. Make sure your
page does not use the JSP-Styles style sheet, since that style sheet overrides the background
color. (Or, if you feel truly inspired, you could have the style sheet be generated
by a JSP page and set the background color that way.)
7. Visit the servlet you made earlier that sets some session data, then visit a JSP page that
displays the data. Use the predefined “session” variable.
8. Make a JSP page that displays the value of a cookie with a designated name. (Hint: call
ServletUtilities by doing “coreservlets.ServletUtilities.someMethod(...)”). First visit
one of your servlets that sets a cookie, then visit the JSP page to display its value. The
servlet will need to set the path so that the JSP page will get the cookie, since the JSP
page is in a different directory hierarchy. That is, the servlet that sets the cookie should
do:
Cookie c = new Cookie(...); // or coreservlets.LongLivedCookie
c.setPath("/");
response.addCookie(c);

Exercises: The page Directive
1. Make a JSP page that displays the value of a cookie with a designated name. First
visit one of your servlets that sets a cookie, then visit the JSP page to display its
value. Use the ServletUtilities class. Remember, the servlet will need to set the path
so that the JSP page will get the cookie, since the JSP page is in a different directory
hierarchy. That is, the servlet that sets the cookie should do:
Cookie c = new Cookie(...); // or coreservlets.LongLivedCookie
c.setPath("/");
response.addCookie(c);
2. The java.math package has a class called BigInteger that lets you create whole numbers
with an arbitrary number of digits. Create a JSP page that makes a large BigInteger
from a String you supply as a request parameter, squares it, and prints out the
result.
3. Make an Excel spreadsheet where each entry is a random number. Use Internet
Explorer to access it if you don’t have the MS Office plugin in Netscape.
4. Make an Excel spreadsheet with a random number of rows.
5. Make a JSP page that sleeps for 20 seconds before returning the page. (Call
Thread.sleep from inside a try/catch block that catches InterruptedException).
Access it “simultaneously” from Netscape and Internet Explorer. Repeat the experiment
with the JSP page not allowing concurrent access. Verify the slower result.
6. Download the ComputeSpeed and SpeedError pages from the archive site. Access
the ComputeSpeed page with numeric values for the “furlongs” and “fortnights”
form parameters attached to the end of the URL. (See section 11.10 starting on page
261 if you want more detail). Now, supply a non-numeric value for one of the parameters.
Next, supply 0 for the fortnights parameter. Can you explain the unexpected
result you get?

Exercises: Including Files and Applets
1. Make an HTML “signature” block with your name and email address. Include it in
two JSP pages.
2. Suppose that you have two different JSP pages that do two different things.
However, for both pages you want to let the user supply a bgColor attribute to
set the background color of the page. Implement this, but use an include mechanism
to avoid repeating code. Hint: when you use jsp:include, the included page
has the same request object as the main page. For example:
White background: http://host/path/page1.jsp
White background: http://host/path/page2.jsp
Red background: http://host/path/page1.jsp?bgColor=RED
Yellow background: http://host/path/page2.jsp?bgColor=YELLOW
3. Make two separate JSP pages that have bulleted lists containing random integers in a
certain range. Avoid repeating code unnecessarily by including a page that defines
the randomInt method from the exercise on JSP scripting expressions.
4. The value of the page attribute of jsp:include is allowed to be a JSP expression. Make
a JSP page that includes a “good news” page or a “bad news” page at random.
5. If you are familiar with applets, make a trivial one that does nothing but set the background
color to blue and print a string derived from the MESSAGE parameter
embedded in the HTML by means of a PARAM element. Convert it to a version that
uses the Java Plug-In. Note that, if this runs at all, it proves that you are correctly
accessing the Plug-In. You don’t need to use Swing or Java2D to verify that you are
using the Plug-In, since the tag generated by jsp:plugin is incompatible with the standard
virtual machine used by Netscape and IE. Try both Netscape and Internet
Explorer to see which (if any) of them has the Plug-In installed. Reminder: applets
run on the client, not on the server. So your applet’s .class files can’t go in the
server’s WEB-INF/classes directory. These .class files work the same way as for regular
applets: they go in the same directory as the JSP/HTML file that uses the applet
tag. The one exception is if the applets are in a package, in which case they go in a
subdirectory (matching the package name) of the directory that contains the JSP file.
Again, this is nothing specific to JSP, but is just the normal way applets work.

Exercises: Beans
1. Make a simple bean called BakedBean with two String properties: level (default
value “half-baked”) and goesWith (default value “hot dogs”). Compile and test it
separately (i.e., without using a servlet or JSP page). Note: if your driver class (i.e.,
the one that has “public static void main(String[] args) {...}” in it) is in a package,
remember that you have to use the package name when you run it from the command
line. That is, you have to do “javac BeanDriver.java” and then
“java yourPackage.BeanDriver”.
2. Make a JSP page that makes a BakedBean, sets the goesWith property to “caviar”,
and then prints out the level and goesWith properties.
3. Make a JSP page that makes a BakedBean, sets the goesWith property based upon
the value of some request parameter, and stores the bean in the ServletContext. Make
a second JSP page that displays the value. Visit the first page from Netscape only
(with a request parameter that sets goesWith), then visit the second page from both
Netscape and Internet Explorer. Verify that both browsers see the same value.
4. Make a JSP page that makes a BakedBean, sets the goesWith property based upon
the value of some request parameter, and stores the bean in the HttpSession object.
Make a second JSP page that displays the value. Visit the first page from Netscape
only (with a request parameter that sets goesWith), then visit the second page from
both Netscape and Internet Explorer. Verify that the two browsers see different values.

Exercises: Custom Tags
1. Download all the files needed to get the SimplePrimeTag and PrimeTag examples
working, and test them. There are quite a number of files needed.
2. Make a random number tag that inserts a random number between 0 and 1 into the
page.
3. Make a random number tag that inserts a random integer between 0 and some specified
number.
4. Make a tag that results in whatever text it encloses being displayed in a large, bold,
red, blinking format. For example,
This is a test
should result in

This is a test


Test on Netscape; Internet Explorer wisely ignores the BLINK tag.

Exercises: Servlet/JSP Integration and
the MVC Architecture
For each of the following exercises, you might want to start by creating a bean, then creating
a servlet that populates it (and invokes the RequestDispatcher), then creating a JSP
page that presents it.
1. Write a servlet that generates a random number, puts it in a bean, and forwards it to a
JSP page that displays it. Use request-based bean sharing.
Hint: you might want to start by simply forwarding from an empty servlet to a simple
JSP page that doesn’t use beans. Then, once you have the RequestDispatcher part
working, you can go back and have the servlet store the bean object (request.set-
Attribute) and have the JSP page read it (jsp:useBean with scope="request").
2. Write a servlet that reads the firstName and lastName request parameters. If they are
both present, it forwards the user to a page that displays them. If either is missing or
is an empty string, it uses previously seen values from that client. If values are still
missing after that, it forwards the user to a page that tells them which parameter is
missing. Use session-based bean sharing.
3. Write a servlet that uses a request parameter to determine the desired size of a prime
number. If the user asks for a particular size, it should create and store one of that
size. If no size is specified, the system should use the previous prime number (if there
is one). Either way, it should forward the user to a page that displays the number. Use
application (servlet context) based bean sharing.

Exercises: JDBC
1. Make a servlet that displays a bulleted list of the names of all shipping companies
used in the Northwind example. (Table name: shippers; column name: Company-
Name — see the second of the screen shots from “Using Metadata”).
2. Make an HTML form that collects a last name. Send the name to a servlet or JSP
page. If there is an employee with that last name, show full details on him or her (just
show the first employee if there are multiple people with the same name). If there is
no employee with that last name, say so. See the screen shot from Access for details
on the column names (table name: employees; column names firstname, lastname,
title, birthdate).
3. Make an HTML form that collects three values: a table name, a number of columns
c, and a number of rows r. Send the data to a servlet or a JSP page. Display an HTML
table containing the first c columns of the first r rows of the designated table. Be sure
to handle the case where c or r are too big.

Student Survey
1. Please rate the following from 1 (poor) to 5 (great):
• Instructor: ______
• Topics: ______
• Handouts: ______
• Exercises: ______
• Book: ______
• Facilities: ______
• Overall: ______
2. What is your overall opinion of the course?
3. What were the strong points of the course?
4. What should be changed to improve it?
Read more ...

June 07, 2011

Servlets interview-questions-4

76) How do I write to a log file using JSP under Tomcat? Can I make use of the log() method for this?

Yes, you can use the Servlet API's log method in Tomcat from within JSPs or servlets. These messages are stored in the server's log directory in a file called servlet.log.

77) How can I use a servlet to print a file on a printer attached to the client?

The security in a browser is designed to restrict you from automating things like this. However, you can use JavaScript in the HTML your servlet returns to print a frame. The browser will still confirm the print job with the user, so you can't completely automate this. Also, you'll be printing whatever the browser is displaying (it will not reliably print plug-ins or applets), so normally you are restricted to HTML and images.
[The JavaScript source code for doing this is:


 

78) How do you do servlet aliasing with Apache and Tomcat?

Servlet aliasing is a two part process with Apache and Tomcat. First, you must map the request in Apache to Tomcat with the ApJServMount directive, e.g.,
ApJServMount/myservlet/ROOT
Second, you must map that url pattern to a servlet name and then to a servlet class in your web.xml configuration file. Here is a sample exerpt:


 
    myservlet
    com.mypackage.MyServlet
 
 
    myservlet
    /myservlet
 

79) I want my servlet page to redirect to a login page if the session has timed out. How can I know if my session has timed out?

If the servlet engine does the time-out, following code should help you:


 //assume you have a HttpServletRequest request
 if(request.getSession(false)==null) {
    //no valid session (timeouted=invalid)

    //code to redirect to login page
 }

80) Can Tomcat be configured to interpret all, or selected, .html files within a given context as JSP? Or, do JSP files have to end with a .jsp extension?

yes you can do that by modifying the web.xml file. You will have to invoke the org.apache.jasper.runtime.JspServlet for all the requests having extension .html. You can do that by changing the Servlet mapping code:


 
    
      jsp
    
    *.html
 

And comment out the following block


 
    
      html
    
    
      text/html
    
 

81) What is the difference between request attributes, session attributes, and ServletContext attributes?

A ServletContext attribute is an object bound into a context through ServletContext.setAttribute() method and which is available to ALL servlets (thus JSP) in that context, or to other contexts via the getContext() method. By definition a context attribute exists locally in the VM where they were defined. So, they're unavailable on distributed applications.
Session attributes are bound to a session, as a mean to provide state to a set of related HTTP requests. Session attributes are available ONLY to those servlets which join the session. They're also unavailable to different JVMs in distributed scenarios. Objects can be notified when they're bound/unbound to the session implementing the HttpSessionBindingListener interface.
Request attributes are bound to a specific request object, and they last as far as the request is resolved or while it keep dispatched from servlet to servlet. They're used more as comunication channel between Servlets via the RequestDispatcher Interface (since you can't add Parameters...) and by the container. Request attributes are very useful in web apps when you must provide setup information between information providers and the information presentation layer (a JSP) that is bound to a specific request and need not be available any longer, which usually happens with sessions without a rigorous control strategy.
Thus we can say that context attributes are meant for infra-structure such as shared connection pools, session attributes to contextual information such as user identification, and request attributes are meant to specific request info such as query results.

82) Are singleton/static objects shared between servlet contexts?

[Question continues: For example if I have two contexts on a single web server, and each context uses a login servlet and the login servlet connects to a DB. The DB connection is managed by a singleton object. Do both contexts have their own instance of the DB singleton or does one instance get shared between the two?]
It depends on from where the class is loaded.
The classes loaded from context's WEB-INF directory are not shared by other contexts, whereas classes loaded from CLASSPATH are shared. So if you have exactly the same DBConnection class in WEB-INF/classes directory of two different contexts, each context gets its own copy of the singleton (static) object.

83) When building web applications, what are some areas where synchronization problems arrise?

In general, you will run into synchronization issues when you try to access any shared resource. By shared resource, I mean anything which might be used by more than one request.
Typical examples include:
  • Connections to external servers, especially if you have any sort of pooling.
  • Anything which you include in a HttpSession. (Your user could open many browser windows and make many simultaneous requests within the one session.)
  • Log destinations, if you do your own logging from your servlets.

84) What is the difference between apache webserver, java webserver and tomcat server?

Apache is an HTTP server written in C that can be compiled and run on many platforms.
Java WebServer is an HTTP server from Sun written in Java that also supports Servlets and JSP.
Tomcat is an open-source HTTP server from the Apache Foundation, written in Java, that supports Servlets and JSP. It can also be used as a "plug-in" to native-code HTTP servers, such as Apache Web Server and IIS, to provide support for Servlets (while still serving normal HTTP requests from the primary, native-code web server).

85) How can you embed a JavaScript within servlets / JSP pages?

You don't have to do anything special to include JavaScript in servlets or JSP pages. Just have the servlet/JSP page generate the necessary JavaScript code, just like you would include it in a raw HTML page.
The key thing to remember is it won't run in the server. It will run back on the client when the browser loads the generate HTML, with the included JavaScript.

86) How can I make a POST request through response.sendRedirect() or response.setStatus() and response.setHeader() methods?

You can't. It's a fundamental limitation of the HTTP protocol. You'll have to figure out some other way to pass the data, such as
  • Use GET instead
  • Make the POST from your servlet, not from the client
  • Store data in cookies instead of passing it via GET/POST

87) How do I pass a request object of one servlet as a request object to another servlet?

Use a Request Dispatcher.

88) I call a servlet as the action in a form, from a jsp. How can I redirect the response from the servlet, back to the JSP? (RequestDispatcher.forward will not help in this case, as I do not know which resource has made the request. request.getRequestURI will return the uri as contained in the action tag of the form, which is not what is needed.)

You'll have to pass the JSP's URI in to the servlet, and have the servlet call sendRedirect to go back to the JSP. For example:


 
Shoe size:

Then in the servlet...


 response.sendRedirect(request.getParameter("redirect"));

89) What is the ServletConfig object, and why is it useful?

The ServletConfig object is an interface. It contains the methods
  • getInitParameter
  • getInitParameterNames
  • getServletContext
  • getServletName
You can use the methods to determine the Servlet's initialization parameters, the name of the servlets instance, and a reference to the Servlet Context the servlet is running in.
getServletContext is the most valuable method, as it allows you to share information accross an application (context).

90) I have a global variable in a servlet class. What will happen to this global variable if two requests hit on the same time?

What will happen is an unforeseeable event.
The best way to establish a default occurrence (the servlet handles a request at a time) is to synchronize the access to the global variable or alternatively to create a servlet that implements the SingleThreadModel interface.

91) Suppose I have 2 servers, server1 and server2. How can I take data in a cookie from server1, and send it to server2?

You'll have to create a (new) similar cookie on server 2.
Have a ReadCookieServlet running on server1 that
  • Reads the cookie, using request.getCookies()
  • Redirects to WriteCookieServlet running on server2, passing the cookie name, value and expiration date as request parameters, using response.sendRedirect().
Have a WriteCookieServlet running on server2 that
  • Reads the cookie name, value and expiration date request parameters, using request.getParameter().
  • Creates a similar cookie, using response.addCookie().

92) How can I pass data from a servlet running in one context (webapp) to a servlet running in another context?

There are three ways I can think of off the top of my head:
  1. Store the information you want to share in a persistant format, such as in a file system or database. That way, any servlet that is running in a JVM that can "see" these resources can get to this information.
  2. If persisting this information is not an option, you can bind this information to a context that is accessible to all servlet contexts, such as the application server's context. This way, you can keep the data you want to share in memory.
  3. Use the old fashion way of passing information to a servlet - HTTP. One servlet could foward a request to another servlet and include the data that needs to be shared as parameters in the request.

93) How can I write an "error page" -- that is, a servlet or JSP to report errors of other servlets?

The Servlet 2.2 specification allows you to specify an error page (a servlet or a JSP) for different kinds of HTTP errors or ServletExceptions. You can specify this in deployment descriptor of the web application as:


 
    FooException
    /error.jsp
  

where FooException is a subclass of ServletException.
The web container invokes this servlet in case of errors, and you can access the following information from the request object of error servlet/JSP: error code, exception type, and a message.

94) What is the difference between ServletContext and ServletConfig?

A ServletContext represents the context in a servlet container of a servlet instance operates. A servlet container can have several contexts (or web applications) at one time. Each servlet instance is running in one of these contexts. All servlets instances running in the same context are part of the same web application and, therefore, share common resources. A servlet accesses these shared resource (such as a RequestDispatcher and application properties) through the ServletContext object.
This notion of a web application became very significant upon the Servlet 2.1 API, where you could deploy an entire web application in a WAR file. Notice that I always said "servlet instance", not servlet. That is because the same servlet can be used in several web applications at one time. In fact, this may be common if there is a generic controller servlet that can be configured at run time for a specific application. Then, you would have several instances of the same servlet running, each possibly having different configurations.
This is where the ServletConfig comes in. This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig.

95) Under what circumstances will a servlet be reloaded?

That depends on the Servlet container.
Most of the Servlet containers reload the servlet only it detects the code change in the Servlet, not in the referenced classes.
In Tomcat's server.xml deployment descriptor, if you have mentioned


 Context path="/myApp" 
   docBase="D:/myApp/webDev" 
   crossContext="true"
   debug="0"
   reloadable="true"
   trusted="false" 
 Context

The reloadable = true makes the magic. Every time the Servlet container detects that the Servlet code is changed, it will call the destroy on the currently loaded Servlet and reload the new code.
But if the class that is referenced by the Servlet changes, then the Servlet will not get loaded. You will have to change the timestamp of the servlet or stop-start the server to have the new class in the container memory.

96) What is a Servlet Filter?

A filter is basically a component that is invoked whenever a resource is invoked for which the filter is mapped. The resource can be something like a servlet, or a URL pattern. A filter normally works on the request, response, or header attributes, and does not itself send a response to the client.

97) I am using the RequestDispatcher's forward() method to redirect to a JSP. The problem is that the jsp's url is now relative to the servlet's url and all my url's in the jsp such as will be corrupt. How do I solve this problem?

You can use absolute urls like:

       BODY
    String base = request.getContextPath(); 
    IMG src="%=base%>/img/pic.gif"
 BODY
or write out a BASE tag like:

 String base = request.getContextPath(); 
 HEAD
    BASE HREF="<%=base%>"
 HEAD
 BODY
    
 


That should take care of the problem.

98) How can I return a readily available (static) HTML page to the user instead of generating it in the servlet?

To solve your problem, you can either send a "Redirect" back to the client or use a RequestDispatcher and forward your request to another page:
  1. Redirect:
  2. A redirection is made using the HttpServletResponse object:
    
     if(condition) {
        response.sendRedirect("page1.html");
     } else {
               response.sendRedirect("page2.html");
     }
    
  3. RequestDispatcher:
  4. A request dispatcher can be obtained through the ServletContext. It can be used to include another page or to forward to it.
    
     if(condition) {
        this.getServletContext()
      .getRequestDispatcher("page1.html").forward();
     } else {
       this.getServletContext()
      .getRequestDispatcher("page2.html").forward();
     }
    
Both solutions require, that the pages are available in you document root. If they are located somewhere else on your filesystem, you have to open the file manually and copy their content to the output writer.
If your application server is set up in combination with a normal web server like Apache, you should use solution (1), because the the web server usually serves static files much faster than the application server.

99) What is the difference between static variables and instance variables in a servlet?

According to the Java Language definition, a static variable is shared among all instances of a class, where a non-static variable -- also called an instance variable -- is specific to a single instance of that class.
According to the Servlet specification, a servlet that does not declare SingleThreadModel usually has one and only one instance, shared among all concurrent requests hitting that servlet.
That means that, in servlets (and other multithreaded applications), an instance variable behaves very much like a static variable, since it is shared among all threads. You have to be very careful about synchronizing access to shared data.
The big difference between instance variables and static variables comes when you have configured your servlet engine to instantiate two instances of the same servlet class, but with different init parameters. In this case, there will be two instances of the same servlet class, which means two sets of instance variables, but only one set of static variables.
Remember that you can store data in lots of different places in a servlet. To wit:
  • Local variables - for loop iterators, result sets, and so forth
  • Request attributes - for data that must be passed to other servlets invoked with the RequestDispatcher
  • Session attributes - persists for all future requests from the current user only
  • Instance variables - for data that persists for the life of the servlet, shared with all concurrent users
  • Static variables - for data that persists for the life of the application, shared with all concurrent users -- including any other servlet instances that were instantiated with different init parameters
  • Context attributes - for data that must persist for the life of the application, and be shared with all other servlets

100) How can I share data between two different web applications?

Different servlets may share data within one application via ServletContext. If you have a compelling to put the servlets in different applications, you may wanna consider using EJBs.
Read more ...

Servlets interview-questions-3

51) Can I send multiple responses for a single request?

No. That doesn't even make sense :-)
You can, however, send a "redirect", which tells the user's browser to send another request, possibly to the same servlet with different parameters. Search this FAQ on "redirect" to learn more.

52) What is FORM based login and how do I use it? Also, what servlet containers support it?

Form based login is one of the four known web based login mechanisms. For completeness I list all of them with a description of their nature:
  1. HTTP Basic Authentication
    • An authentication protocol defined within the HTTP protocol (and based on headers). It indicates the HTTP realm for which access is being negotiated and sends passwords with base64 encoding, therefore it is not very secure. (See RFC2068 for more information.)
  2. HTTP Digest Authentication
    • Like HTTP Basic Authentication, but with the password transmitted in an encrypted form. It is more secure than Basic, but less then HTTPS Authentication which uses private keys. Yet it is not currently in widespread use.
  3. HTTPS Authentication (SSL Mutual Authentication)
    • This security mechanism provides end user authentication using HTTPS (HTTP over SSL). It performs mutual (client & server) certificate based authentication with a set of different cipher suites.
  4. Form Based Login
    • A standard HTML form (static, Servlet/JSP or script generated) for logging in. It can be associated with protection or user domains, and is used to authenticate previously unauthenticated users.
    • The major advantage is that the look and feel of the login screen can be controlled (in comparison to the HTTP browsers' built in mechanisms).
To support 1., 3., and 4. of these authentication mechanisms is a requirement of the J2EE Specification (as of v1.2, 3.4.1.3 Required Login Mechanisms). (HTTP Digest Authentication is not a requirement, but containers are encouraged to support it.)
You can also see section 3.3.11.1 of the J2EE Specs. (User Authentication, Web Client) for more detailed descriptions of the mechanisms.
Thus any Servlet container that conforms to the J2EE Platform specification should support form based login.
To be more specific, the Servlet 2.2 Specification describes/specifies the same mechanisms in 11.5 including form based login in 11.5.3.
This section (11.5.3) describes in depth the nature, the requirements and the naming conventions of form based login and I suggest to take a look at it.
Here is a sample of a conforming HTML login form:


 
    
    
 
Known Servlet containers that support FORM-based login are:
  • iPlanet Application Server
  • Tomcat (the reference implementation of the Java Servlet API)

53) How do I capture a request and dispatch the exact request (with all the parameters received) to another URL?

As far as i know it depends on the location of the next target url.
  • If the next servlet url is in the same host, then you can use the forward method.
Here is an example code about using forward:


 RequestDispatcher rd = null;
 String targetURL = "target_servlet_name";
 ServletContext ctx = this.getServletContext();
 rd = ctx.getRequestDispatcher(targetURL);
 rd.forward(request, response);

54) How can the data within an HTML form be refreshed automatically whenever there is a change in the database?

JSP is intended for dynamically generating pages. The generated pages can include wml, html, dhtml or whatever you want...
When you have a generated page, JSP has already made its work. From this moment you have a page.
If you want automatic refreshing, then this should be acomplished by the technology included in the generated page (JSP will tell only what to include in the page).
The browser can not be loaded by extern factors. The browser is the one who fetches url's since the http protocol is request-response based. If a server can reload a browser without its allow, it implies that we could be receiving pages which we haven't asked for from servers.
May you could use applets and a ServerSocket for receiving incoming signals from the server for changed data in the DB. This way you can load new information inside the applet or try to force a page reload.
[That's a nice idea -- it could use the showDocument() call to reload the current page. It could also use HTTP polling instead of maintaining an expensive socket connection. -Alex]
Perhaps (if possible), could be simpler using an automatic JavaScript refreshing function that force page reload after a specified time interval.

55) What is a web application (or "webapp")?

A web application is a collection of servlets, html pages, classes, and other resources that can be bundled and run on multiple containers from multiple vendors. A web application is rooted at a specific path within a web server. For example, a catalog application could be located at http://www.mycorp.com/catalog. All requests that start with this prefix will be routed to the ServletContext which represents the catalog application.

56) How can I call a servlet from a JSP page? How can I pass variables from the JSP that the servlet can access?

You can use or response.sendRedirect("http://path/YourServlet").
Variables can be sent as:


       
 
 
  

You may also pass parameters to your servlet by specifying response.sendRedirect("http://path/YourServlet?param1=val1").

57) Can there be more than one instance of a servlet at one time ?

It is important to note that there can be more than one instance of a given Servlet class in the servlet container. For example, this can occur where there was more than one servlet definition that utilized a specific servlet class with different initialization parameters. This can also occur when a servlet implements the SingleThreadModel interface and the container creates a pool of servlet instances to use.

58) How can I measure the file downloading time using servlets?



 ServletOutputStream out = response.getOutputStream();
 String filename = getServletContext().getRealPath(request.getQueryString());
 FileInputStream fin = new FileInputStream(filename);
 long start = System.currentTimeMillis();
 byte data[] = new byte[1024];
 int len = 0;
 while ((len = fin.read(data)) > 0) {
    out.write(data, 0, len);
 }
 out.flush();
 long stop = System.currentTimeMills();
 log("took " + (stop - start) + "ms to download " + filename);
 

59) What is inter-servlet communication?

As the name says it, it is communication between servlets. Servlets talking to each other. [There are many ways to communicate between servlets, including
  • Request Dispatching
  • HTTP Redirect
  • Servlet Chaining
  • HTTP request (using sockets or the URLConnection class)
  • Shared session, request, or application objects (beans)
  • Direct method invocation (deprecated)
  • Shared static or instance variables (deprecated)
Search the FAQ, especially topic Message Passing (including Request Dispatching) for information on each of these techniques. -Alex]
Basically interServlet communication is acheived through servlet chaining. Which is a process in which you pass the output of one servlet as the input to other. These servlets should be running in the same server.
e.g. ServletContext.getRequestDispatcher(HttpRequest, HttpResponse).forward("NextServlet") ; You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet.
There are some Servlet engine specific configurations for servlet chaining.
Servlets can also call public functions of other servlets running in the same server. This can be done by obtaining a handle to the desired servlet through the ServletContext Object by passing it the servlet name ( this object can return any servlets running in the server). And then calling the function on the returned Servlet object.
e.g. TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet"); otherServletDetails= Test.getServletDetails();
You must be careful when you call another servlet's methods. If the servlet that you want to call implements the SingleThreadModel interface, your call could conflict with the servlet's single threaded nature. (The server cannot intervene and make sure your call happens when the servlet is not interacting with another client.) In this case, your servlet should make an HTTP request to the other servlet instead of direct calls.
Servlets could also invoke other servlets programmatically by sending an HTTP request. This could be done by opening a URL connection to the desired Servlet.

60) How do I make servlet aliasing work with Apache+Tomcat?

When you use Tomcat standalone as your web server, you can modify the web.xml in $TOMCAT_HOME/webapps/myApp/WEB-INF to add a url-pattern:


 


    
      
   myServlet
      
      
   myServlet
      
    
    
      
   myServlet
      
      
       /jsp-bin/*
      
   
 

This will let you use: http://webserver:8080/myApp/jsp-bin/stuff.html instead of: http://webserver:8080/myApp/servlet/myServlet/stuff.html But it won't work on port 80 if you've integrated Tomcat with Apache. Graeme Wallace provided this trick to remedy the situation. Add the following to your tomcat-apache.conf (or to a static version of it, since tomcat re-generates the conf file every time it starts):


 
   LocationMatch /myApp/jsp-bin/* 
   SetHandler jserv-servlet


 LocationMatch

This lets Apache turn over handling of the url pattern to your servlet.

61) Is there any way to determine the number of concurrent connections my servlet engine can handle?

Depends on whether or not your servlet container uses thread pooling. If you do not use a thread pool, the number of concurrent connections accepted by Tomcat 3.1, for example, is 10. This you can see for yourself by testing a servlet with the Apache JMeter tool.
However, if your servlet container uses a thread pool, you can specify the number of concurrent connections to be accepted by the container. For Tomcat 3.1, the information on how to do so is supplied with the documentation in the TOMCAT_HOME/doc/uguide directory.

62) What is a request dispatcher and how does it work?

A RequestDispatcher object can forward a client's request to a resource or include the resource itself in the response back to the client. A resource can be another servlet, or an HTML file, or a JSP file, etc.
You can also think of a RequestDispatcher object as a wrapper for the resource located at a given path that is supplied as an argument to the getRequestDispatcher method.
For constructing a RequestDispatcher object, you can use either the ServletRequest.getRequestDispatcher() method or the ServletContext.getRequestDispatcher() method. They both do the same thing, but impose slightly different constraints on the argument path. For the former, it looks for the resource in the same webapp to which the invoking servlet belongs and the pathname specified can be relative to invoking servlet. For the latter, the pathname must begin with '/' and is interpreted relative to the root of the webapp.
To illustrate, suppose you want Servlet_A to invoke Servlet_B. If they are both in the same directory, you could accomplish this by incorporating the following code fragment in either the service method or the doGet method of Servlet_A:

 
 RequestDispatcher dispatcher = getRequestDispatcher("Servlet_B");
 dispatcher.forward( request, response );

where request, of type HttpServletRequest, is the first parameter of the enclosing service method (or the doGet method) and response, of type HttpServletResponse, the second. You could accomplish the same by

 
 RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( "/servlet/Servlet_B" );
 dispatcher.forward( request, response );

63) What is a Servlet Context?

A Servlet Context is a grouping under which related servlets (and JSPs and other web resources) run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container.
The ServletContext object is used by an individual servlet to "call back" and obtain services from the container (such as a request dispatcher). Read the JavaDoc for javax.servlet.ServletContext for more information.
You can maintain "application global" variables by using Servlet Context Attributes.

64) Does the RequestDispatcher expect a relative URL to be relative to the originally-called servlet or to the current servlet (if different)?

Since the RequestDispatcher will be passing the control (request object and response object) from the current Servlet, the relative URL must be relative to the current servlet.
The originally called servlet has passed the control to the current servlet, and now current servlet is acting as controller to other resourses.

65) What is the difference between in-process and out-of-process servlet containers?

The in-process Servlet containers are the containers which work inside the JVM of Web server, these provides good performance but poor in scalibility.
The out-of-process containers are the containers which work in the JVM outside the web server. poor in performance but better in scalibility
In the case of out-of-process containers, web server and container talks with each other by using the some standard mechanism like IPC.
In addition to these types of containers, there is 3rd type which is stand-alone servlet containers. These are an integral part of the web server.

66) How is SingleThreadModel implemented in Tomcat? In other containers? [I would assume that Tomcat uses its connection thread pool, and creates a new instance of the servlet for each connection thread, instead of sharing one instance among all threads. Is that true?]

The question mixes together two rather independent aspects of a servlet container: "concurrency control" and "thread pooling".
Concurrency control, such as achieved by having a servlet implement the SingleThreadModel interface, addresses the issue of thread safety. A servlet will be thread-safe or thread-unsafe regardless of whether the servlet container used a thread pool. Thread pooling merely eliminates the overhead associated with the creation and destruction of threads as a servlet container tries to respond to multiple requests received simultaneously. It is for this reason that the specification document for Servlet 2.2 API is silent on the subject of thread pooling -- as it is merely an implementation detail. However, the document does indeed address the issue of thread safety and how and when to use SingleThreadModel servlets.
Section 3.3.3.1 of the Servlet 2.2 API Specification document says that if a servlet implements the SingleThreadModel it is guaranteed "that only one request thread at time will be allowed in the service method." It says further that "a servlet container may satisfy this guarantee by serializing requests on a servlet or by maintaining a pool of servlet instances."
Obviously, for superior performance you'd want the servlet container to create multiple instances of a SingleThreadModel type servlet should there be many requests received in quick succession. Whether or not a servlet container does that depends completely on the implementation. My experiments show that Tomcat 3.1 does indeed create multiple instances of a SingleThreadModel servlet, but only for the first batch of requests received concurrently. For subsequent batches of concurrent requests, it seems to use only one of those instances.

67) Which servlet containers have persistent session support? Specifically, does Tomcat 3.1?

All servlet containers that implement the Servlet 2.2 API must provide for session tracking through either the use of cookies or through URL rewriting. All Tomcat servlet containers support session tracking.

68) Can I use JAAS as the authentication technology for servlets ?

Yes, JAAS can be used as authentication technology for servlets. One important feature of JAAS is pure Java implementation. The JAAS infrastructure is divided into two main components: an authentication component and an authorization component. The JAAS authentication component provides the ability to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet.

69) How can I set a servlet to load on startup of the container, rather than on the first request?

The Servlet 2.2 spec defines a load-on-startup element for just this purpose. Put it in the section of your web.xml deployment descriptor. It is either empty () or contains "a positive integer indicating the order in which the servlet should be loaded. Lower integers are loaded before higher integers. If no value is specified, or if the value specified is not a positive integer, the container is free to load it at any time in the startup sequence."
For example,


       
    foo
    com.foo.servlets.Foo
    5
 

Some servlet containers also have their own techniques for configuring this; please submit feedback with information on these.

70) Is it possible to write a servlet that acts as a FTP server?

Yes. It would spawn a thread that opens a ServerSocket, then listens for incoming connections and speaks the FTP protocol.

71) Is there a way to disable a user's ability to double-click a submit image/button (and therefore submitting duplicate data -- multiple submits)? Is there a way to do this with Javascript?

Give the submit image (or button) an onClick() handler. Have the handler check if a flag is set and if not set the flag and submit the form and then clear the form.

72) What are the main differences between Servlets and ISAPI?

The first difference is obviously that Servlets is the technology from Sun Microsystems and ISAPI is from Microsoft.
Other Differences are:
  1. Servlet is a simple .class file and ISAPI is a DLL
  2. Servlets run in the Servlet containers and may be in-process or out of process. ISAs run in the same address space as the HTTP server
  3. Servlet container preprocesses and postprocesses the data communication between the client and server. ISAPI Filters provide the capability of pre-processing and post-processing of all data sent between the client and the server
  4. Java is the only choice for writing Servlets, VC++/MFC is used to write ISAPI code
  5. Servlets works on most of the Web servers plus third party containers can be integrated with other web servers to provide servlets on them. ISAPI works on only ISAPI-compliant Web server (for example, Microsoft Internet Information Server)
  6. Servlets can connect to the Databases through JDBC as well as jdbc-odbc bridges. ISAPI can connect to Databases through only ODBC
  7. Servlets have access to many server-side technologies like EJB and etc. ISAPI is limited in scope
  8. Multiple commands can be implemented in a servlet by using pathinfo. ISAPI allows multiple commands in one DLL, implemented as member functions of the CHttpServer object in the DLL.
  9. Content generation and content presentation can be done seperately in Servlets with the help of JSP. ISAPI code has to generate HTML code itself.

73) Can I associate a servlet with a particular mime-type, so if the client requests a file of that type, my servlet will be executed?

In web.xml you can use a mime-mapping to map the type with a certain extension and then map the servlet to that extension.


    
      zzz
    
    
      text/plain
    
 

 
    
      *.zzz
     
    
      MyServlet
    
 

So, when a file for type zzz is requested, the servlet gets called.

74) What are the different cases for using sendRedirect() vs. getRequestDispatcher()?

When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher or getNamedDispatcher.
If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.
If you don't need to preserve the request/response objects, you can use either.

75) How do I access the value of a cookie using JavaScript?

You can manipulate cookies in JavaScript with the document.cookie property. You can set a cookie by assigning this property, and retrieve one by reading its current value.
The following statement, for example, sets a new cookie with a minimum number of attributes:


 document.cookie = "cookieName=cookieValue";

And the following statement displays the property's value:


 alert(document.cookie);

The value of document.cookie is a string containing a list of all cookies that are associated
with a web page. It consists, that is, of name=value pairs for each cookie that matches the
current domain, path, and date. The value of the document.cookie property, for instance,
might be the following string:


 cookieName1=cookieValue1; cookieName2=cookieValue2;
Read more ...

My Favorite Site's List

#update below script more than 500 posts