- When the user goes to a JSP page web browser makes the request via internet.
- JSP request gets sent to the Web server.
- Web server recognises the .jsp file and passes the JSP file to the JSP Servlet Engine.
- If the JSP file has been called the first time,the JSP file is parsed,otherwise Servlet is instantiated.
- The next step is to generate a special Servlet from the JSP file. All the HTML required is converted to println statements.
- The Servlet source code is compiled into a class.
- The Servlet is instantiated,calling the init and service methods.
- HTML from the Servlet output is sent via the Internet.
- HTML results are displayed on the user's web browser
Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts
Monday, 7 January 2013
Steps for JSP request:
Saturday, 26 May 2012
Working with Cookie in JSP
Cookie is a small piece of information which is stored in user's computer. Webserver uses cookie to identify the user in the next time visit.
Each time user visits a website which cookie is enable, the web server adds extra data into the HTTP header and responds to the web browser. in the next time when user visits the same site again, the web browser also sends cookie in the HTTP request header to the web server.
User can also disables cookie in the web browser which supports disable cookie function such as Mozilla Firefox, IE...
Cookie is stored in the user's computer as a string of name/value. In addition, cookie has attributes such as domain, path, timeout...
JSP provides API to allows you to work with cookie effectively through object of the class javax.server.http.Cookie. Let's take a look at an example how to set cookie in JSP and respond it back to the client.
Sending cookie from the web server
In the code, first you create a new cookie with the name and value. If you se the methods such as setDomain() and setPath() to restrict the cookie to the current URL you have to read the cookie exactly from that URL. Cookie has its own lifetime called expiration time. If you don't set the timeout for the cookie, it will be removed when user closes the web browser. The method setMaxage() is used to set the expiration time for the cookie. Finally you add cookie to the response header and store it in the user's computer by using methodaddCookie() of response object.
Reading cookie
To read cookie from a HTTP request, you first call the method getCookies() of the requestobject. This method returns you a list of available cookies in the request header, then you can walk through all of them. Here is the code to read cookie information:
Removing existing cookie
Friday, 25 May 2012
Jsp Sessions
HTTP protocol is stateless. It means that there is no permanent connectionbetween client (web browser) and Web Server. When client request a page from a web server, it opens a connection, retrieve the page and close connection. Web servers doesn't know what happen then in the client side. In addition, If another request from client is made, web server doesn't associate the new connection with the connection has been made.
In order to overcome the stateless of HTTP protocol, JSP provides you the implicit sessionobject which is a HttpSession object. The session object resides in the server side so you can keep arbitrary data about the client and other data as well in session and later on in different requests you can retrieve the saved data for processing. JSP stores data in the server side in the session object by using a single key that client remembers.
The session object has the three most important methods which you use most as bellows:
public void setAttribute(String name, Object value)throws IllegalStateExceptionpublic Object getAttribute(String name)throws IllegalStateExceptionpublic void removeAttribute(String name)throws IllegalStateException
A session is an object associated with a visitor. Data can be put in the session and retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to the site. Here is a set of pages that put a user's name in the session, and display it elsewhere. Try out installing and using these.First we have a form, let us call it GetName.html
The target of the form is "SaveName.jsp", which saves the user's name in the session. Note the variable "session". This is another variable that is normally made available in JSPs, just like outand request variables. (In the @page directive, you can indicate that you do not need sessions, in which case the "session" variable will not be made available.)
The SaveName.jsp saves the user's name in the session, and puts a link to another page, NextPage.jsp.
NextPage.jsp shows how to retrieve the saved name.
If you bring up two different browsers (not different windows of the same browser), or run two browsers from two different machines, you can put one name in one browser and another name in another browser, and both names will be kept track of. The session is kept around until a timeout period. Then it is assumed the user is no longer visiting the site, and the session is discarded.
Exercise: Add another attribute "age" to the above example.
How session works
When server creates a new session, it always adds a session identifier in the form of cookie. When web browser asks for a page or makes a request, the web browser always sends cookie which are created by the web server in the request. Therefore in the server side, web server checks for that cookie and find the corresponding session that is matched to the received cookie.
The session normally short-lived so the session cookie is not saved into disk. Session also has time out. When the time is out, the session is no longer exist in the server side. You can set time out of session in configuration file in the server.
Wednesday, 23 May 2012
JSP Standard Actions
JSP Standard Actions
JSP actions are special XML tags which control the behavior of servlet engine. JSP actions allow you to insert a file dynamically, reuse external JavaBean components, forward the request to the other page and generate HTML for JavaApplet plugin.
jsp:include action
JSP include action allows you to include a file at runtime. The syntax of jsp include action is as follows:
In the page attribute you insert a relative URL of a file which could be an HTML file or another JSP page. Unlike the include directive, the jsp include action insert a file at the time page is being requested.
jsp:useBean action
jsp useBean action lets you load a JavaBean component into the page and use it later. jsp useBean action allows you to reuse other Java classes. The syntax of jsp useBean action is as follows:
By using the jsp:useBean action, you create an new object with the object nameobjectName of the class package.class. Later on you can access the properties of this object by using either jsp:setProperty or jsp:getProperty. Let's take a look at an example. First we have a JavaBeans call Message:
public class Message {
private String text;
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}
}
Then we create a JSP page which uses the jsp:useBean action to access JavaBean Message inside that page.
We use jsp:setProperty to set the text property of the JavaBean Message and then we call jsp:getProperty to get that message and print it out. Here is the output screenshot:

jsp:forward Action
jsp:forward action allows you to forward a request to the other page. The syntax of the jsp:forward action is listed as below. There is one attribute called page which value is a page you want to forward the request to. You can specify the page statically or dynamically by using expression.
jsp:plugin Action
jsp:plugin action allows you to embeded Java Applet into a page. Suppose you have an applet which demonstrates the JSP page lifecycle called com.jsp.jspapplet. Here is the way we use jsp:plugin action to embeded that applet into a page:
Tuesday, 22 May 2012
JSP Declarations
JSP Declarations
The JSP you write turns into a class definition. All the scriptlets you write are placed inside a single method of this class. You can also add variable and method declarations to this class. You can then use these variables and methods from your scriptlets and expressions. To add a declaration, you must use the <%! and %> sequences to enclose your declarations, as shown below.
The example has been created a little contrived, to show variable and method declarations.
Here we are declaring a Date variable theDate, and the method getDate. Both of these are available now in our scriptlets and expressions.
But this example no longer works! The date will be the same, no matter how often you reload the page. This is because these are declarations, and will only be evaluated once when the page is loaded! (Just as if you were creating a class and had variable initialization declared in it.)
Exercise: Modify the above example to add another function computeDate which re-initializes theDate. Add a scriptlet that calls computeDate each time.
Note: Now that you know how to do this -- it is in general not a good idea to use variables as shown here. The JSP usually will run as multiple threads of one single instance. Different threads would interfere with variable access, because it will be the same variable for all of them. If you do have to use variables in JSP, you should use synchronized access, but that hurts the performance. In general, any data you need should go either in thesession object or the request object (these are introduced a little later) if passing data between different JSP pages. Variables you declare inside scriptlets are fine, e.g. <% int i = 45; %> because these are declared inside the local scope and are not shared.
Monday, 21 May 2012
JSP Directives
JSP Directives
JSP directives instruct the JSP container on how to work with JSPs. There are three directives in the JSP specification: page, include and taglib. The directive form usualy follows the following form:
<%@ directive attribute1 = "value 1"
attribute2 = "value 2"
...
%>
page Directive
The page directive allows you to define one or more following attributes:
import Option
import="package.class"
import="package.class1,...,package.classN"
Import option allows you to specify which classes or packages are used in the page. for example, you can import all the classes in the package java.util as follows:
<%@ page import="java.util.*" %>
You can use import option multiple times in the page directive.
contentType option
contentType="MIME-Type"
contentType="MIME-Type; charset=Character-Set".
The contentType option allows you specify the MIME type of the output page. The default istext/html you can also use other values such as text/plain for outputing text format such as
<%@ page contentType="text/plain" %>
IsThreadSafe Option
isThreadSafe="true|false".
isThreadSafe option allows you to indicate the page is being processed as thread-safe. The default value of the isThreadSafe is true therefore all JSPs are considered thread-safe. IfisThreadSafe is set to false, JSP engine ensures that only one thread at a time is executing the current JSP page
.session Option
session="true|false".
By using session option, you are telling JSP compiler that you want to use session or not. The default value of the session attribute is true, indicating that there is an implicit variable called session is available for your use.
buffer and autoFlush Options
buffer and autoFlush options let you control the JSP buffering.
You can turn buffer on or off or even specify the buffer size by using buffer option such as:
<%@ page buffer="none" %>
<%@ page buffer="64kb" %>
autoFlush option controls whether the buffer is flushed automatically when it is full. The default value of autoFlush is true means JSP automatically flush the buffer when it is full.
autoFlush option controls whether the buffer is flushed automatically when it is full. The default value of autoFlush is true means JSP automatically flush the buffer when it is full.
Info Option
Info option allows you to define the description of the servlet. Later on you can access this value by calling the method:
Servlet.getServletInfo().
extends Option
In some cases, you need to create your own superclass of JSP pages and using this supper class in different JSPs. In order to do so, first you need to create a super class first. This supper class normally inherits from the HttpServlet class. And in the JSPs you use theextends option to use that supper class in you JSP page.
isELIgnored Option
isELIgnored option provide the ability for you to disable the evaluation of the expression language (EL). You will learn more about expression language in the later tutorial.
errorPage Option
errorPage option allows you to indicate the error page to be displayed when the error occurs in the current executing page. For example:
<%@ page errorPage="error.jsp" %>
isErrorPage Option
isErrorPage option indicates that the current JSP page can be used as an error page for other JSP page. When you set isErrorPage equal true, JSP engine creates an implicit exception object which contains the Throwable object that caused the error page to be called. By using this excpetion object, you can print out the error message to the user, for example:
Include Directive: Include directive lets you to include a file (JSP or HTML) at the time JSP engine translate the JSP page into a servlet. The syntax of include directive is as follows:
<%@ include file="relative url" %>
The filename you specify in the include directive is a relative URL. If you provide a file name without associated path, the JSP compiler always assumes that the file is in the same directory as the JSP page.
Normally the include directive is used to include common sections of a JSP page in a webapplication or website such as header, navigation bar, footer... to make those section reusable in every JSP page.
Normally the include directive is used to include common sections of a JSP page in a webapplication or website such as header, navigation bar, footer... to make those section reusable in every JSP page.
taglib Directive
JSP has a set of standard tags for you to use. JSP also provide a possibility to allow you to create new custom tags look like HTML and XML tag. In this case, you can use taglib directive to use your custom tag in your JSP page. For using custom tag, you can refer to the custom tag tutorial. The syntax of using taglib directive is as follows:
<%@ taglib uri="http://localhost/jsptutorial/taglib/mytaglib"
prefix="jsptutorial" %>
Tuesday, 10 April 2012
Expression Language - EL in JSP
Expression Language (EL) was introduced in JSP 2.0 specification. You can do almost everything like scriptlet by using EL which is simpler to understand.
Basic syntax: The syntax of expression language is very simple. No matter where it is called, it always follows the form as bellows:
${expr}
In the syntax above, expr is an expression. When the Java compiler sees the sign ${}, it evaluates the expr and injects the result in the place where ${expr} is called. Let take a look at an example:
In the above example, first we use the action useBean to instantiate a new object of the class Message and set its text property. Then we use ${msg.text} as an expression. Whencompiler sees this syntax, it evaluates the expression which is msg.text and invokes the appropriate method of the object which returns the value of text property. In this case, on the screen you will see the message "this is a message" is displayed.
Literal Values
Literal values are constants with a specific data type and they can be used in expression along with variables. There are five basic five types as follow:
- Boolean: true and false
- Integer: a combination of numbers from 0 to 9
- Floating Point
- String
- Null: null
Monday, 9 April 2012
Operators in Jsp
Expression language supports a wide range of operators including arithmetic, relational and logical operators. EL allows you to apply those operators to the literal and variables forcalculations. Here is the list of operators with its alternative version.
| Operator | Alternative | Meaning |
|---|---|---|
[]
|
Collection member access
| |
·
|
Property access
| |
()
|
Grouping
| |
-
|
Unary Negation
| |
!
|
not
|
Logical not
|
Empty
|
Empty test
| |
*
|
Multiplication
| |
/
|
div
|
Division
|
%
|
mod
|
Modulo or division remainder
|
+
|
Addition
| |
-
|
Subtraction
| |
<
|
lt
|
Less than
|
>
|
gt
|
Greater than
|
<=
|
le
|
Less than or equal
|
>=
|
ge
|
Greater than or equal
|
==
|
eq
|
Equality
|
!=
|
ne
|
Inequality
|
&&
|
and
|
Logical and
|
||
|
or
|
Logical or
|
=
|
Assignment
| |
?:
|
Conditional operator
|













