Java Server Pages !
An extensible Web technology that uses template
data, custom elements, scripting languages, and server-side Java objects
to return dynamic content to a client. Typically the template data is
HTML or XML elements and The client is often a Web browser.
Java Servlet
A Java program that extends the functionality of a
Web server, generating dynamic content and interacting with Web clients
using a request-response paradigm.
Static contents
- Typically static HTML page
- Same display for everyone
Dynamic contents
- Contents is dynamically generated based on conditions
- Conditions could be User identity, Time of the day, User entered values through forms and selections
JSP Page
A text-based document capable of returning both
static and dynamic content to a client browser. Static content and
dynamic content can be intermixed. Static contents are HTML, XML, Text
and Dynamic contents are Java code, Displaying properties of JavaBeans,
Invoking business logic defined in Custom tags.
Directives
There are five types of JSP directives and
scripting elements. With JSP 1.0, most of your JSP is enclosed within a
single tag that begins with <% and ends with %>. With the newer
JSP 1.1 specification, there are also XML-compliant versions.
JSP directives are for the JSP engine. They do
not directly produce any visible output but instead tell the engine what
to do with the rest of the JSP page. They are always enclosed within
the <%@ … %> tag. The two primary directives are page and include.
The taglib directive will not be discussed but is available for
creating custom tags with JSP 1.1.
The page directive is the one you'll find at the
top of almost all your JSP pages. Although not required, it lets you
specify things like where to find supporting Java classes:
<%@ page import="java.util.Date" %>
where to send the surfer in the event of a runtime Java problem:
<%@ page errorPage="errorPage.jsp" %>
and whether you need to manage information at the
session level for the user, possibly across multiple Web pages (more
later on sessions with JavaBeans):
<%@ page session="true" %>
The include directive lets you separate your
content into more manageable elements, such as those for including a
common page header or footer. The page included could be a fixed HTML
page or more JSP content:
<%@ include file="filename.jsp" %>
Declarations
JSP declarations let you define page-level
variables to save information or define supporting methods that the rest
of a JSP page may need. If you find yourself including too much code,
it is usually better off in a separate Java class. Declarations are
found within the <%! … %> tag. Always end variable declarations
with a semicolon, as any content must be valid Java statements: <%!
int i=0; %>.
Expressions
With expressions in JSP, the results of
evaluating the expression are converted to a string and directly
included within the output page. JSP expressions belong within <%= …
%> tags and do not include semicolons, unless part of a quoted
string:
<%= i %>
<%= "Hello" %>
Code Fragments/Scriptlets
JSP code fragments or scriptlets are embedded
within <% … %> tags. This Java code is then run when the request
is serviced by the Web server. Around the scriptlets would be raw HTML
or XML, where the code fragments let you create conditionally executing
code, or just something that uses another piece of code. For example,
the following displays the string "Hello" within H1, H2, H3, and H4
tags, combining the use of expressions and scriptlets. Scriptlets are
not limited to one line of source code:
<% for (int i=1; i<=4; i++){ %>
>Hello<%=i%>>
<% } %>
Comments
The last of the key JSP elements is for embedding
comments. Although you can always include HTML comments in your files,
users can view these if they view the page's source. If you don't want
users to be able to see your comments, you would embed them within the
<%-- … --%> tag:
<%-- comment for server side only --%>
Scripts in JSP
A JSP scriptlet is used to contain any code fragment that is valid for the scripting language used in a page. The syntax for a scriptlet is as follows:<%
scripting-language-statements
%>
When the scripting language is set to java, a
scriptlet is transformed into a Java programming language statement
fragment and is inserted into the service method of the JSP page’s
servlet. A programming language variable created within a scriptlet is
accessible from anywhere within the JSP page.
In the web service version of the hello1
application, greeting.jsp contains a scriptlet to retrieve the request
parameter named username and test whether it is empty. If the if
statement evaluates to true, the response page is included. Because the
if statement opens a block, the HTML markup would be followed by a
scriptlet that closes the block.
<%
String username = request.getParameter("username");
if ( username != null && username.length() > 0 ) {
%>
<%@include file="response.jsp" %>
<%
}
%>
JSP Objects and Components !
JSP expressions
If a programmer wants to insert data into an HTML page, then this is achieved by making use of the JSP expression.
The general syntax of JSP expression is as follows:
<%= expression %>The expression is enclosed between the tags <%= %>
For example, if the programmer wishes to add 10
and 20 and display the result, then the JSP expression written would be
as follows:
<%= 10+20 %>
Implicit Objects
Implicit Objects in JSP are objects that are
automatically available in JSP. Implicit Objects are Java objects that
the JSP Container provides to a developer to access them in their
program using JavaBeans and Servlets. These objects are called implicit
objects because they are automatically instantiated.
There are many implicit objects available. Some of them are:
request
The class or the interface name of the object
request is http.httpservletrequest. The object request is of type
Javax.servlet.http.httpservletrequest. This denotes the data included
with the HTTP Request. The client first makes a request that is then
passed to the server. The requested object is used to take the value
from client’s web browser and pass it to the server. This is performed
using HTTP request like headers, cookies and arguments.
response
This denotes the HTTP Response data. The result
or the information from a request is denoted by this object. This is in
contrast to the request object. The class or the interface name of the
object response is http.HttpServletResponse. The object response is of
type Javax.servlet.http. >httpservletresponse. Generally, the object
response is used with cookies. The response object is also used with
HTTP Headers.
Session
This denotes the data associated with a specific
session of user. The class or the interface name of the object Session
is http.HttpSession. The object Session is of type
Javax.servlet.http.httpsession. The previous two objects, request and
response, are used to pass information from web browser to server and
from server to web browser respectively. The Session Object provides the
connection or association between the client and the server. The main
use of Session Objects is for maintaining states when there are multiple
page requests. This will be explained in further detail in following
sections.
Out
This denotes the Output stream in the context of
page. The class or the interface name of the Out object is
jsp.JspWriter. The Out object is written: Javax.servlet.jsp.JspWriter
PageContext
This is used to access page attributes and also
to access all the namespaces associated with a JSP page. The class or
the interface name of the object PageContext is jsp.pageContext. The
object PageContext is written: Javax.servlet.jsp.pagecontext
Application
This is used to share the data with all
application pages. The class or the interface name of the Application
object is ServletContext. The Application object is written:
Javax.servlet.http.ServletContext
Config
This is used to get information regarding the
Servlet configuration, stored in the Config object. The class or the
interface name of the Config object is ServletConfig. The object Config
is written Javax.servlet.http.ServletConfig
Page
The Page object denotes the JSP page, used for
calling any instance of a Page's servlet. The class or the interface
name of the Page object is jsp.HttpJspPage. The Page object is written:
Java.lang.Object
The most commonly used implicit objects are request, response and session objects.
JSP Session Object
Session Object denotes the data associated with a specific
session of user. The class or the interface name of the object session
is http.HttpSession. The object session is written as:Javax.servlet.http.httpsession.
The previous two objects, request and response,
are used to pass information from web browser to server and from server
to web browser respectively. But the Session Object provides the
connection or association between the client and the server. The main
use of Session Objects is to maintain states when there are multiple
page requests.
The main feature of session object is to navigate
between multiple pages in a application where variables are stored for
the entire user session. The session objects do not lose the variables
and the value remains for the user’ session. The concept of maintenance
of sessions can be performed by cookies or URL rewriting. A detailed
approach of session handling will be discusses in coming sections.
Methods of session Object
There are numerous methods available for session Object. Some are:
- getAttribute(String name)
- getAttributeNames
- isNew()
- getCreationTime
- getId
- invalidate()
- getLastAccessedTime
- getMaxInactiveInterval
- removeAttribute(String name)
- setAttribute(String, object)
getAttribute(String name)
The getAttribute method of session object is used
to return the object with the specified name given in parameter. If
there is no object then a null value is returned.
General syntax of getAttribute of session object is as follows:
session.getAttribute(String name)
The value returned is an object of the
corresponding name given as string in parameter. The returned value from
the getAttribute() method is an object written: java.lang.Object.
For exampleString exforsys = (String) session.getAttribute("name");
In the above statement, the value returned by the
method getAttribute of session object is the object of name given in
parameter of type java.lang. Object and this is typecast to String data
type and is assigned to the string exforsys.
getAttributeNames
The getAttributeNames method of session object is
used to retrieve all attribute names associated with the current
session. The name of each object of the current session is returned. The
value returned by this method is an enumeration of objects that
contains all the unique names stored in the session object.
General Syntaxsession.getAttributeNames()
The returned value by this method getAttributeNames() is Enumeration of object.
For exampleexforsys = session.getAttributeNames( )
The above statement returns enumeration of
objects, which contains all the unique names stored in the current
session object in the enumeration object exforsys.
isNew()
The isNew() method of session object returns a
true value if the session is new. If the session is not new, then a
false value is returned. The session is marked as new if the server has
created the session, but the client has not yet acknowledged the
session. If a client has not yet chosen the session, i.e., the client
switched off the cookie by choice, then the session is considered new.
Then the isNew() method returns true value until the client joins the
session. Thus, the isNew() method session object returns a Boolean value
of true of false.
General syntax of isNew() of session object is as follows:
session.isNew()
The returned value from the above method isNew() is Boolean
JSP Request Objects !
The request object in JSP is used to get the
values that the client passes to the web server during an HTTP request.
The request object is used to take the value from the client’s web
browser and pass it to the server. This is performed using an HTTP
request such as: headers, cookies or arguments. The class or the
interface name of the object request is http.httpservletrequest.
The object request is written: Javax.servlet.http.httpservletrequest.
Methods of request Object
There are numerous methods available for request object. Some of them are:
- getCookies()
- getHeader(String name)
- getHeaderNames()
- getAttribute(String name)
- getAttributeNames()
- getMethod()
- getParameter(String name)
- getParameterNames()
- getParameterValues(String name)
- getQueryString()
- getRequestURI()
- getServletPath()
- setAttribute(String,Object)
- removeAttribute(String)
getCookies()
The getCookies() method of request object returns
all cookies sent with the request information by the client. The
cookies are returned as an array of Cookie Objects. We will see in
detail about JSP cookies in the coming sections.
General syntax of getHeader() of request object is as follows:
request.getHeader("String")getHeader()request object returned value is a string.
For example:
String onlinemca = request.getHeader("onlinemca");
The above would retrieve the value of the HTTP header whose name is onlinemca in JSP.
getHeader(String name)
The method getHeader(String name) of request
object is used to return the value of the requested header. The returned
value of header is a string.
eneral syntax of getHeader() of request object is as follows:
request.getHeader("String")In the above the returned value is a String.
For example:
String online = request.getHeader("onlinemca");
The above would retrieve the value of the HTTP header whose name is onlinemca in JSP.
getHeaderNames()
The method getHeaderNames() of request object
returns all the header names in the request. This method is used to find
available headers. The value returned is an enumerator of all header
names.
General syntax of getHeaderNames() of request object is as follows:
request.getHeaderNames();In the above the returned value is an enumerator.
For example:
Enumeration onlinemca = request.getHeaderNames();
The above returns all header names under the enumerator onlinemca.
getAttribute(String name)
The method getAttribute() of request object is
used to return the value of the attribute. The getAttribute() method
returns the objects associated with the attribute. When the attribute is
not present, then a null value is returned. If the attribute is present
then the return value is the object associated with the attribute.
General syntax of getAttribute() of request object is as follows:
request.getAttribute()In the above the returned value is an object.
For example:
Object onlinemca = request.getAttribute("test");
The above retrieves the object stored in the request test and returns the object in onlinemca.
getAttributeNames()
The method getAttribute() of request object is
used to return the object associated with the particular given
attribute. If the user wants to get names of all the attributes
associated with the current session, then the request object method
getAttributeNames() can be used. The returned value is an enumerator of
all attribute names.
General syntax of getAttributeNames() of request object is as follows:
request.getAttributeNames()For example:
Enumeration onlinemca = request.getAttributeNames();
The above returns all attribute names of the current session under the enumerator: onlinemca.
getMethod()
The getMethod() of request object is used to
return the methods GET, POST, or PUT corresponding to the requested HTTP
method used.
General syntax of getMethod() of request object is as follows:request.getMethod()For example:
if (request.getMethod().equals("POST"))
{
.........
.........
}
In the above example, the method returned by the
request.getMethod is compared with POST Method and if the returned
method from request.getMethod() equals POST then the statement in if
block executes.
getParameter(String name)
getParameter() method of request object is used
to return the value of a requested parameter. The returned value of a
parameter is a string. If the requested parameter does not exist, then a
null value is returned. If the requested parameter exists, then the
value of the requested parameter is returned as a string.
General syntax of getParameter() of request object is as follows:
request.getParameter(String name)The returned value by the above statement is a string.
For example:
String onlinemca = request.getParameter("test");
The above example returns the value of the
parameter test passed to the getParameter() method of the request object
in the string onlinemca. If the given parameter test does not exist
then a null value is assigned to the string onlinemca.
getParameterNames()
The getParameterNames() method of request object is used to
return the names of the parameters given in the current request. The
names of parameters returned are enumeration of string objects.General syntax of getParameterNames() of request object is as follows:
request.getParameterNames()
Value returned from the above statement getParameterNames() method is enumeration of string objects.
For example:Enumeration exforsys = request.getParameterNames();
The above statement returns the names of the parameters in the current request as an enumeration of string object.
getParameterValues(String name)
The getParameter(String name) method of request
object was used to return the value of a requested given parameter. The
returned value of the parameter is a string. If there are a number of
values of parameter to be returned, then the method
getParameterValues(String name) of request object can be used by the
programmer. The getParameterValues(String name) method of request object
is used to return all the values of a given parameter’s request. The
returned values of parameter is a array of string objects. If the
requested parameter is found, then the values associated with it are
returned as array of string object. If the requested given parameter is
not found, then null value is returned by the method.
General syntax of getParameterValues of request object is as follows:request.getParameterValues(String name)
The returned value from the above method getParameterValues() is array of string objects.
For example:String[] vegetables = request.getParameterValues("vegetable");The above example returns a value of parameter vegetable passed to the method getParameterValues() of request object and the returned values are array of string of vegetables.
getQueryString()
The getQueryString() method of request object is
used to return the query string from the request. From this method, the
returned value is a string.
General syntax of getQueryString() of request object is as follows:request.getQueryString()Value returned from the above method is a string.
For example:
String onlinemca=request.getQueryString();
out.println("Result is"+exforsys);
The above example returns a string exforsys from
the method getQueryString() of request object. The value is returned and
the string is printed in second statement using out.println statement.
getRequestURI()
The getRequestURI() method of request object is used for
returning the URL of the current JSP page. Value returned is a URL
denoting path from the protocol name up to query string.General syntax of getRequestURI() of request object is as follows:
request.getRequestURI()The above method returns a URL.
For example:
out.println("URI Requested is " + request.getRequestURI());Output of the above statement would be:
URI Requested is /Jsp/test.jsp
getServletPath()
The getServletPath() method of request object is used to return the part of request URL that calls the servlet.
General syntax of getServletPath() of request object is as follows:request.getServletPath()The above method returns a URL that calls the servlet.
For example:
out.println("Path of Servlet is " + request.getServletPath());The output of the above statement would be:
Path of Servlet is/test.jsp
setAttribute(String,Object)
The setAttribute method of request object is used to set object
to the named attribute. If the attribute does not exist, then it is
created and assigned to the object.General syntax of setAttribute of request object is as follows:
request.setAttribute(String, object)
In the above statement the object is assigned with named string given in parameter.
For example:request.setAttribute("username", "onlinemca");The above example assigns the value onlinemca to username.
removeAttribute(String)
The removeAttribute method of request object is
used to remove the object bound with specified name from the
corresponding session. If there is no object bound with specified name
then the method simply remains and performs no function.
General syntax of removeAttribute of request object is as follows:request.removeAttribute(String);
JSP Response Objects !
The response object denotes the HTTP Response
data. The result or the information of a request is denoted with this
object. The response object handles the output of the client. This
contrasts with the request object. The class or the interface name of
the response object is http.HttpServletResponse.
-The response object is written: Javax.servlet.http.httpservletresponse.-The response object is generally used by cookies.
-The response object is also used with HTTP Headers.
Methods of response Object
There are numerous methods available for response object. Some of them are:
- setContentType()
- addCookie(Cookie cookie)
- addHeader(String name, String value)
- containsHeader(String name)
- setHeader(String name, String value)
- sendRedirect(String)
- sendError(int status_code)
setContentType()
setContentType() method of response object is used to set the MIME type and character encoding for the page.
General syntax of setContentType() of response object is as follows:
response.setContentType();For example:
response.setContentType("text/html");
The above statement is used to set the content type as text/html dynamically.
addCookie(Cookie cookie)
addCookie() method of response object is used to
add the specified cookie to the response. The addcookie() method is used
to write a cookie to the response. If the user wants to add more than
one cookie, then using this method by calling it as many times as the
user wants will add cookies.
General syntax of addCookie() of response object is as follows:
response.addCookie(Cookie cookie)For example:
response.addCookie(Cookie exforsys);The above statement adds the specified cookie exforsys to the response.
addHeader(String name, String value)
addHeader() method of response object is used to
write the header as a pair of name and value to the response. If the
header is already present, then value is added to the existing header
values.
General syntax of addHeader() of response object is as follows:
response.addHeader(String name, String value)
Here the value of string is given as second
parameter and this gets assigned to the header given in first parameter
as string name.
For example:response.addHeader("Author", "onlinemca");The output of above statement is as below:
Author: onlinemca
containsHeader(String name)
containsHeader() method of response object is
used to check whether the response already includes the header given as
parameter. If the named response header is set then it returns a true
value. If the named response header is not set, the value is returned as
false. Thus, the containsHeader method is used to test the presence of a
header before setting its value. The return value from this method is a
Boolean value of true or false.
General syntax of containsHeader() of response object is as follows:
response.containsHeader(String name)
Return value of the above containsHeader() method is a Boolean value true or false.
setHeader(String name, String value)
setHeader method of response object is used to
create an HTTP Header with the name and value given as string. If the
header is already present, then the original value is replaced by the
current value given as parameter in this method.
General syntax of setHeader of response object is as follows:
response.setHeader(String name, String value)For example:
response.setHeader("Content_Type","text/html");The above statement would give output as
Content_Type: text/html
sendRedirect(String)
sendRedirect method of response object is used to
send a redirect response to the client temporarily by making use of
redirect location URL given in parameter. Thus the sendRedirect method
of the response object enables one to forward a request to a new target.
But one must note that if the JSP executing has already sent page
content to the client, then the sendRedirect() method of response object
will not work and will fail.
General syntax of sendRedirect of response object is as follows:
response.sendRedirect(String)In the above the URL is given as string.
For example:
response.sendRedirect("http://xxx.test.com/error.html");
The above statement would redirect response to
the error.html URL mentioned in string in Parameter of the method
sendRedirect() of response object.
sendError(int status_code)
sendError method of response object is used to
send an error response to the client containing the specified status
code given in parameter.
General syntax of sendError of response object is as follows:
response.sendError(int status_code)
No comments:
Post a Comment