Vous êtes sur la page 1sur 31

Introduction to JSP

JSP technology is used to create dynamic web applications. JSP pages are easier to
maintain then a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code
inside Java code, while JSP adds Java code inside HTML using JSP tags. Everything a
Servlet can do, a JSP page can also do it.
Advantage of JSP

Easy to maintain and code.


High Performance and Scalability.
JSP is built on Java technology, so it is platform independent.

JSP Scriptlet tag (Scripting elements)


In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what
are the scripting elements first.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:

o scriptlet tag

o expression tag

o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

1. <% java source code %>

Example of JSP scriptlet tag


In this example, we are displaying a welcome message.

1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files index.html and welcome.jsp. The index.html file
gets the username from the user and the welcome.jsp file prints the username with the
welcome message.

File: index.html

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>

File: welcome.jsp

1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print the
values of variable or method.

Syntax of JSP expression tag


1. <%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.

1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>

Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints current time


To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the
instance of Calendar class by the getInstance() method.

index.jsp

1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>

Example of JSP expression tag that prints the user name


In this example, we are printing the username using the expression tag. The index.html file
gets the username and sends the request to the welcome.jsp file, which displays the
username.

File: index.jsp

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>

File: welcome.jsp

1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>

JSP Declaration Tag


The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of
auto generated servlet.

So it doesn't get memory at each request.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

1. <%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration


tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare varia
methods.

The declaration of scriptlet tag is placed inside the The declaration of jsp declaration ta
_jspService() method. _jspService() method.
Example of JSP declaration tag that declares field
In this example of JSP declaration tag, we are declaring the field and printing the value of
the declared field using the jsp expression tag.

index.jsp

1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube
of given number and calling this method from the jsp expression tag. But we can also use
jsp scriptlet tag to call the declared method.

index.jsp

1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>
11. -------------------------------------------------------------------------------------------
JSP Implicit Objects
There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.

The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

1.Out Object

1. void print(): This method writes the value which has been passed to it. For
e.g. the below statement would display a sentence Out Implicit Object in jSP
BeginnersBook to the output screen (client browser).

out.print(Out Implicit Object in jSP - BeginnersBook);

2. void println(): This method is similar to the print() method, the only
difference between print and println is that the println() method adds a new
line character at the end. Lets have a look at the difference with the help of
an example.
print:
out.print(hi);
out.print(" ");
out.print(hello);
output on browser: There will not be a new line between the outcomes of all
3 out.print statements.
hi hello

println:

out.println(hi);
out.println(hello);
output on browser:
hi
hello

<HTML>
<HEAD>
<TITLE> OUT IMPLICIT OBJECT EXAMPLE </TITLE>
</HEAD>
<BODY>
<%
out.print( "print statement " );
out.println( "println" );
out.print("Another print statement");
%>
</BODY>
</HTML>

2.Request Implicit Object


. It is mainly used to get the data on a JSP page which has been entered by user
on the previous JSP page.

Methods of request Implicit Object


1. getParameter(String name) This method is used to get the value of a
requests parameter. For example at login page user enters user-id and
password and once the credentials are verified the login page gets
redirected to user information page, then using request.getParameter we
can get the value of user-id and password which user has input at the login
page.
2. String Uid= request.getParameter("user-id");
String Pass= request.getParameter("password");
3. getParameterNames() It returns enumeration of all the parameter names
associated to the request.
Enumeration e= request.getParameterNames();

4. getParameterValues(String name) It returns the array of parameter


values.

String[] allpasswords = request.getParameterValues("password");

5. getAttribute(String name) Used to get the attribute


value. request.getAttribute(admin) would give you the value of attribute
admin.
6. getAttributeNames() It is generally used to get the attribute names
associated to the current session. It returns the enumeration of attribute
names present in session.

Enumerator e = request.getAttributeNames();

7. setAttribute(String,Object) It assigns an objects value to the attribute.


For example I have an attribute password and a String object str which has
a value admin then calling request.setAttribute(password, str) would
assign a value admin to the attribute password.

Request Implicit Object Example


In the below example we are receiving the input from user in index.html page and
displaying the same information in userinfo.jsp page using request implicit object.

index.html

<html>
<head>
<title>Enter UserName and Password</title>
</head>
<body>
<form action="userinfo.jsp">
Enter User Name: <input type="text" name="uname" /> <br><br>
Enter Password: <input type="text" name="pass" /> <br><br>
<input type="submit" value="Submit Details"/>
</form>
</body>
</html>
userinfo.jsp

<%@ page import = " java.util.* " %>


<html>
<body>
<%
String username=request.getParameter("uname");
String password=request.getParameter("pass");
out.print("Name: "+username+" Password: "+password);
%>
</body>
</html>

Response Implicit Object in JSP with


examples
mainly used for modifying the response which is being sent to the browser after
processing the clients request.

Methods of response Implicit Object


void setContentType(String type)
void sendRedirect(String address)
void addHeader(String name, String value)
void setHeader(String name, String value)
boolean containsHeader(String name)
void addCookie(Cookie value)
void sendError(int status_code, String message)

1. void setContentType(String type) This method tells browser, the type of


response data by setting up the MIME type and character encoding. The
information sets by this method helps browser to interpret the response.
Example
2. response.setContentType("text/html");
3. response.setContentType("image/gif");
4. response.setContentType("image/png");
response.setContentType("application/pdf");

5. void sendRedirect(String address) It redirects the control to a new JSP


page. For e.g. When the browser would detect the below statement, it would
be redirected to the beginnersbook.com from the current JSP page.
response.sendRedirect("http://beginnersbook.com");

6. void addHeader(String name, String value) addHeader method adds a


header to the response, basically it includes a header name and its value.
For example The below statement will include a header Site in the
response with value BeginnersBook.com.
response.addHeader("Site", "BeginnersBook.com");

7. void setHeader(String name, String value) It sets the header value.


This method overrides the current value of header with the new value. Lets
say Im modifying the value of Header Site. The below statement would
modify the current value BeginnersBook.com to a new value BB.com
response.setHeader("Site", "BB.com");

8. boolean containsHeader(String name) It returns a Boolean value


true/false. It basically checks the whether the header is present in the
response or not. For example Above, in the addHeader method example
we have added a Site Header in response so the below statement would
return true.

response.containsHeader("Site");

9. void addCookie(Cookie cookie) This method adds a cookie to the


response. The below statements would add 2
Cookies Author and Siteinfo to the response.
10. response.addCookie(Cookie Author);
response.addCookie(Cookie Siteinfo);

11. void sendError(int status_code, String message) It is used to send


error response with a code and an error message. For example

response.sendError(404, "Page not found error");

12. boolean isCommitted() -It checks whether the Http Response has been
sent to the client, if yes then it returns true else it gives false.
13. <% if(response.isCommited())
14. {
15. <%--do something --%>
16. }else
17. {
18. <%--do something else --%>
} %>

19. void setStatus(int statuscode) This method is used to set the HTTP
status to a given value. For e.g. the below statement would set HTTP
response code to 404 (Page not found).

response.setStatus(404);
ndex.html

<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="checkdetails.jsp">
UserId: <input type="text" name="id" /> <br><br>
Password: <input type="text" name="pass" /> <br><br>
<input type="submit" value="Sign In!!"/>
</form>
</body>
</html>
This JSP page verifies the input id/pass against hard-coded values.

checkdetails.jsp

<html>
<head><title>Check Credentials</title>
</head>
<body>
<%
String uid=request.getParameter("id");
String password=request.getParameter("pass");
session.setAttribute("session-uid", uid);
if(uid.equals("Chaitanya") && password.equals("BeginnersBook"))
{
response.sendRedirect("success.jsp");
}
else
{
response.sendRedirect("failed.jsp");
}
%>
</body>
</html>

Application Implicit Object in JSP with


examples
It is basically used for getting initialization parameters and for sharing the
attributes & their values across the entire JSP application, which means any
attribute set by application implicit object would be available to all the JSP
pages.

Methods

1. Object getAttribute(String attributeName): It returns the object stored in


a given attribute name. For example the below statement would return the
object stored in attribute MyAttr.
String s = (String)application.getAttribute("MyAttr");

2. void setAttribute(String attributeName, Object object): It sets the value


of an attribute or in other words it stores an attribute and its value in
application context, which is available to use across JSP application.
Example
application.setAttribute(MyAttribute, This is the value of Attribute);
The above statement would have stored the attribute and its value. What
would be the value of s if we use the below statement in any of the JSP
page?

String s= (String) application.getAttribute(MyAttribute);


String s value would be This is the value of Attribute since we have set it
using setAttribute method.

3. void removeAttribute(String objectName): This method is used for


removing the given attribute from the application. For e.g. It would remove
the Attribute MyAttr from the application. If we try to get the value of a
removed attribute using getAttribute method, it would return Null.

application.removeAttribute(MyAttr);

Exception Implicit Object in JSP


This object is only available for error pages, which means a JSP page should
have isErrorPage to true in order to use exception implicit object. Lets
understand this with the help of below example

Exception implicit Object Example


In this example we are taking two integer inputs from user and then we are
performing division between them. We have used exception implicit object to
handle any kind of exception in the below example.

index.html

<html>
<head>
<title>Enter two Integers for Division</title>
</head>
<body>
<form action="division.jsp">
Input First Integer:<input type="text" name="firstnum" />
Input Second Integer:<input type="text" name="secondnum" />
<input type="submit" value="Get Results"/>
</form>
</body>
</html>
Here we have specified exception.jsp as errorPage which means if any exception
occurs in this JSP page, the control will immediately transferred to the
exception.jsp JSP page. Note: We have used errorPage attribute of Page
Directive to specify the exception handling JSP page (<%@ page
errorPage=exception.jsp %>).

division.jsp

<%@ page errorPage="exception.jsp" %>


<%
String num1=request.getParameter("firstnum");
String num2=request.getParameter("secondnum");
int v1= Integer.parseInt(num1);
int v2= Integer.parseInt(num2);
int res= v1/v2;
out.print("Output is: "+ res);
%>
In the below JSP page we have set isErrorPage to true which is also an
attribute of Page directive, used for making a page eligible for exception
handling. Since this page is defined as a exception page in division.jsp, in case
of any exception condition this page will be invoked. Here we are displaying the
error message to the user using exception implicit object.

exception.jsp

<%@ page isErrorPage="true" %>


Got this Exception: <%= exception %>
Please correct the input data.

JSP Directives Page, Include and TagLib


Directives control the processing of an entire JSP page. It gives directions to the
server regarding processing of a page.

Syntax of Directives:

<%@ directive name [attribute name=value attribute name=value ........]%>


There are three types of Directives in JSP:
1) Page Directive
2) Include Directive
3) TagLib Directive

1) Page Directive
There are several attributes, which are used along with Page Directives and
these are

1. import
2. session
3. isErrorPage
4. errorPage
5. ContentType
6. extends
7. info
8. language

1. import:
This attribute is used to import packages. While doing coding you may need to
include more than one packages, In such scenarios this page directives attribute
is very useful as it allows you to mention more than one packages at the same
place separated by commas (,). Alternatively you can have multiple instances of
page element each one with different package.

Syntax of import attribute


<%@page import="value"%>
Here value is package name.

Example of import- The following is an example of how to import more than one
package using import attribute of page directive.

<%@page import="java.io.*%>
<%@page import="java.lang.*%>
<%--Comment: OR Below Statement: Both are Same--%>
<%@page import="java.io.*, java.lang.*"%>
2. session:
Generally while building a user interactive JSP application, we make sure to give
access to the user to get hold of his/her personal data till the session is active.
Consider an example of logging in into your bank account, we can access all of
your data till we signout (or session expires). In order to maintain session for a
page the session attribute should be true.

This attribute is to handle HTTP sessions for JSP pages. It can have two values:
true or false. Default value for session attribute is true, which means if you do not
mention this attribute, server may assume that HTTP session is required for this
page.

Default value for this attribute: true

Syntax of session attribute:

<%@ page session="value"%>


here value is either true OR false

Examples of session:

<%@ page session="true"%>


The above code would allow a page to have session implicit objects.

<%@ page session="false"%>


If this code is specified in a JSP page, it means session objects will not be
available for that page. Hence session cannot be maintained for that page.

3. isErrorPage:
This attribute is used to specify whether the current JSP page can be used as an
error page for another JSP page. If value of isErrorPage is true it means that the
page can be used for exception handling for another page. Generally these
pages has error/warning messages OR exception handling codes and being
called by another JSP page when there is an exception occurred there.

There is another use of isErrorPage attribute The exception implicit object can
only be available to those pages which has isErrorPage set to true. If the value is
false, the page cannot use exception implicit object.

Default value: false

Syntax of isErrorPage attribute:

<%@ page isErrorPage="value"%>


Here value is either true OR false.

Example of isErrorPage:

<%@ page isErrorPage="true"%>


This makes a JSP page, a exception handling page.

4. errorPage:
As I stated above, when isErrorPage attribute is true for a particular page then it
means that the page can be called by another page in case of an
exception. errorPage attribute is used to specify the URL of a JSP page which
has isErrorPage attrbute set to true. It handles the un-handled exceptions in the
page.

Syntax of errorPage attribute:

<%@ page errorPage="value"%>


Here value is a JSP page name which has exception handling code (and
isErrorPage set to true).

Example of errorPage:

<%@ page errorPage="ExceptionHandling.jsp"%>


This means if any exception occurs on the JSP page where this code has been
placed, the ExceptionHandling.jsp (this page should have isErrorPage true) page
needs to be called.

5. contentType:
This attribute is used to set the content type of a JSP page.

Default value: text/html

Syntax of contentType attribute:

<%@ page contentType="value"%>


here value of content type can be anything such as: text/html, text/xml etc.

Example of contentType:

Below code can be used for text/html pages.

<%@ page contentType="text/html"%>


for text/xml based pages:

<%@ page contentType="text/xml"%>

7. buffer:
This attribute is used to specify the buffer size. If you specify this to none during
coding then the output would directly written to Response object by JSPWriter.
And, if you specify a buffer size then the output first written to buffer then it will be
available for response object.

Syntax of buffer attribute:

<%@ page buffer="value"%>


value is size in kb or none.

Example of buffer:

No buffer for this page:


<%@ page buffer="none"%>
5 kb buffer size for the page, which has below code:

<%@ page buffer="5kb"%>


9. info:
It provides a description to a JSP page. The string specified in info will return
when we will call getServletInfo() method.

Syntax of info:

<%@ page info="value"%>


here value is Message or Description

Example of info attribute:

<%@ page info="This code is given by Chaitanya Singh"%>


10. language:
It specifies the scripting language( underlying language) being used in the page.

Syntax of language:

<%@ page language="value"%>


value is scripting language here.

Example of language attribute:

<%@ page language="java"%>


2) Include Directive
Include directive is used to copy the content of one JSP page to another. Its like
including the code of one file into another.

Syntax of Include Directive:

<%@include file ="value"%>


here value is the JSP file name which needs to be included. If the file is in the
same directory then just specify the file name otherwise complete URL(or path)
needs to be mentioned in the value field.
Note: It can be used anywhere in the page.

Example:

<%@include file="myJSP.jsp"%>
You can use the above code in your JSP page to copy the content of myJSP.jsp
file. However in this case both the JSP files must be in the same directory. If the
myJSP.jsp is in the different directory then instead of just file name you would
need to specify the complete path in above code.

Must Read: Include directive in detail with example.

3) Taglib Directive
This directive basically allows user to use Custom tags in JSP. we shall discuss
about Custom tags in detail in coming JSP tutorials. Taglib directive helps you to
declare custom tags in JSP page.

Syntax of Taglib Directive:

<%@taglib uri ="taglibURI" prefix="tag prefix"%>


Where URI is uniform resource locator, which is used to identify the location of
custom tag and tag prefix is a string which can identify the custom tag in the
location identified by uri.

Example of Targlib:

<%@ taglib uri="http://www.sample.com/mycustomlib" prefix="demotag" %>


<html>
<body>
<demotag:welcome/>
</body>
</html>
As you can see that uri is having the location of custom tag library and prefix is
identifying the prefix of custom tag.
Note: In above example <demotag: welcome> has a prefix demotag.
JSP Action Tags
Directives vs Actions
1. Directives are used during translation phase while actions are used during
request processing phase.
2. Unlike Directives Actions are re-evaluated each time the page is accessed.

The following are the action elements used in JSP:

1. <jsp:include> Action
Like include page directive this action is also used to insert a JSP file in
another file.

<jsp:include> vs include directive :

It has the same difference which I mentioned at the beginning of the article
(directive vs action). In <jsp:include> the file is being included during request
processing while in case of include directive it has been included at translation
phase.

Syntax of <jsp:include> :

<jsp:include page="page URL" flush="Boolean Value" />


Here page URL is: the location of the page needs to be included & flush value
can be either true or false (Boolean value).

Example:

<html>
<head>
<title>Demo of JSP include Action Tag</title>
</head>
<body>
<h3>JSP page: Demo Include</h3>
<jsp:include page="sample.jsp" flush="false" />
</body>
</html>
<jsp:forward> Action
<jsp:forward> is used for redirecting the request. When this action is encountered
on a JSP page the control gets transferred to the page mentioned in this action.

Syntax of <jsp:forward> :

<jsp:forward page="URL of the another static, JSP OR Servlet page" />


Example:
first.jsp

<html>
<head>
<title>Demo of JSP Forward Action Tag</title>
</head>
<body>
<h3>JSP page: Demo forward</h3>
<jsp:forward page="second.jsp" />
</body>
</html>
Now when JSP engine would execute first.jsp (the above code) then after action
tag, the request would be transferred to another JSP page (second.jsp).

<jsp:param> Action
This action is useful for passing the parameters to Other JSP action tags such as
JSP include & JSP forward tag. This way new JSP pages can have access to
those parameters using request object itself.

Syntax of <jsp:param>:

<jsp: param name="param_name_here" value="value_of_parameter_here" />


Now considers the same above example

first.jsp

<html>
<head>
<title>Demo of JSP Param Action Tag</title>
</head>
<body>
<h3>JSP page: Demo Param along with forward</h3>
<jsp:forward page="second.jsp">
<jsp:param name ="date" value="20-05-2012" />
<jsp:param name ="time" value="10:15AM" />
<jsp:param name ="data" value="ABC" />
</jsp:forward>
</body>
</html>
In the above example first.jsp is passing three parameters (data, time & data) to
second.jsp and second.jsp can access these parameters using the below code

Date:<%= request.getParameter("date") %>


Time:<%= request.getParameter("time") %>
My Data:<%= request.getParameter("data") %>

Retrieving content of html form


o send information to web server, we can use two methods: GET Method and POST
Method.
The GET method sends the encoded user information separated by the ? character
appended to the page URL.

http://www.java2s.com/hello?key1=value1&key2=value2

The GET method is the default method to send information to web server. Since the
GET method appends plain text string to the URL. We should avoid using GET
method to send password or other sensitive information to the server.
The GET method also has size limitation. We can send only 1024 characters in a
request string. This information sent is accessible getQueryString() and
getParameter() methods of request object.
POST method is more reliable method of sending information to the server. This
method sends the information as a separate message.
JSP handles this type of requests using getParameter() method to read simple
parameters and getInputStream() method to read binary data stream coming from
the client.
JSP handles form data using the following methods.

Method Description

getParameter() returns the value of a form parameter.


getParameterValues() returns multiple values, for example checkbox.

getParameterNames() returns a complete list of all parameters.

getInputStream() read binary data stream coming from the client.

GET parameters from URL


The following code shows how to get parameters using GET method.
The following code uses the getParameter() method to read parameters.

<html>
<body>
<b>First Name:</b><%= request.getParameter("first_name")%><br/>
<b>Last Name:</b><%= request.getParameter("last_name")%>
</body>
</html>

Save the code above as main.jsp. And copy the file to the Tomcat deployment
folder.
First we would type in the parameters and their value directly in the URL. Enter the
following URL in your broswer address bar.

http://localhost:8080/main.jsp?first_name=James&last_name=Smith

We can use the following html form to pass the values to JSP main.jsp page.

<html>
<body>
<form action="main.jsp" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Save this HTML in a file called Hello.htm and put it in Tomcat-installation-


directory/webapps/ROOT directory.
Access it with http://localhost:8080/Hello.htm
The following line in the HTML code calls the jsp page we created to accept
parameter and indicates that we are going to use the GET method to pass the
information.

<form action="main.jsp" method="GET">

POST Method Example with Form


Create a html page as follows and use POST methods for the form. Save it as
Hello.htm.

<html>
<body>
<form action="main.jsp" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Below is main.jsp JSP program to handle input from by web browser using GET or
POST methods.

<html>
<body>
<b>First Name:</b><%= request.getParameter("first_name")%><br/>
<b>Last Name:</b><%= request.getParameter("last_name")%>
</body>
</html>

Passing Checkbox Data to JSP


The following code shows how to use the JSP page to get the checkbox data from a
form.
Here is the html form code. It uses the POST method and calls the main.jsp page.

<html>
<body>
<form action="main.jsp" method="POST" target="_blank">
<input type="checkbox" name="a" checked="checked" /> A
<input type="checkbox" name="b" /> B
<input type="checkbox" name="c" checked="checked" /> C
<input type="submit" value="Select Subject" />
</form>
</body>
</html>

The following is the main.jsp code to handle input for checkbox button.

<html>
<body>
<b>A Flag:</b><%= request.getParameter("a")%>
<b>B Flag:</b><%= request.getParameter("b")%>
<b>C Flag:</b><%= request.getParameter("c")%>
</body>
</html>
Reading All Form Parameters
The following code shows how to use getParameterNames() method from
HttpServletRequest to read all the available form parameters.
This method returns an Enumeration object that contains the parameter names.

<%@ page import="java.io.*,java.util.*" %>


<html>
<body>
<%
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<b>" + paramName + ":</b>\n");
String paramValue = request.getHeader(paramName);
out.println(paramValue);
}
%>
</body>
</html>

JSP COOKIES
JSP Cookies Handling
Cookies are the text files which are stored on the client machine.
They are used to track the information for various purposes.
It supports HTTP cookies using servlet technology
The cookies are set in the HTTP Header.
If the browser is configured to store cookies, it will keep information until
expiry date.

Following are the cookies methods:

Public void setDomain(String domain)

It is used to set the domain to which the cookie applies

Public String getDomain()

It is used to get the domain to which cookie applies

Public void setMaxAge(int expiry)

It sets the maximum time which should apply till the cookie expires

Public intgetMaxAge()

It returns the maximum age of cookie

Public String getName()

It returns the name of the cookie

Public void setValue(String value)

Sets the value associated with the cookie

Public String getValue()

Get the value associated with the cookie

Public void setComment(String cmt)

It describes the cookie purpose

Public String getComment()

It the returns the cookie comments which has been described.

Cookie Set-up using following steps:


1. Creating the cookie object
2. Setting the maximum age
3. Sending the cookie in HTTP response headers

Example:

In this example, we are creating cookies of username and email and add age to the
cookie for 10 hours and trying to get the variable names in the action_cookie.jsp

Action_cookie.jsp.

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"


2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org
/TR/html4/loose.dtd">
4. <html>
5. <head>
6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7. <title>Guru Cookie</title>
8. </head>
9. <body>
10. <form action="action_cookie_main.jsp" method="GET">
11. Username: <input type="text" name="username">
12. <br />
13. Email: <input type="text" name="email" />
14. <input type="submit" value="Submit" />
15. </form>
16. </body>
17. </html>

Action_cookie_main.jsp

1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"


2. pageEncoding="ISO-8859-1"%>
3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org
/TR/html4/loose.dtd">
4. <%
5.
6. Cookie username = new Cookie("username",
7. request.getParameter("username"));
8. Cookie email = new Cookie("email",
9. request.getParameter("email"));
10.
11.
12. username.setMaxAge(60*60*10);
13. email.setMaxAge(60*60*10);
14.
15. // Add both the cookies in the response header.
16. response.addCookie( username );
17. response.addCookie( email );
18. %>
19.

The getQueryString() method of JSP


The "getQueryString()" method is used to fetch the 'query string'. The query string contains the attribute &
the value of the html or JSP form, which sends with the POST /GET method to Servlet or JSP page for
any request.
Example : In this Example , we are asking user to enter any username and password string, the output
displays the query string means username & password . The Query String is fetched using the method
"getQueryString()".
<%
if(request.getQueryString() != null)
out.println(request.getQueryString());
%>

Beans in JSP
Java Bean are reusable software components.They are used to seprate business logic from
presentation logic.Internally bean is just an instance of a class.
how to use a bean class in JSP with the help of jsp:useBean, jsp:setProperty
and jsp:getProperty action tags.

Syntax of jsp:useBean:

<jsp: useBean id="unique_name_to_identify_bean"


class="package_name.class_name" />
Syntax of jsp:setProperty:

<jsp:setProperty name="unique_name_to_identify_bean"
property="property_name" />
Syntax of jsp:getProperty:

<jsp:getProperty name="unique_name_to_identify_bean"
property="property_name" />
A complete example of useBean, setProperty and
getProperty
1) We have a bean class Details where we are having three variables username,
age and password. In order to use the bean class and its properties in JSP we
have initialized the class like this in the userdetails.jsp page

<jsp:useBean id="userinfo" class="beginnersbook.com.Details"></jsp:useBean>


We have used useBean action to initialize the class. Our class is in
beginnersbook.com package so we have given a fully qualified
name beginnersbook.com.Details.

2) We have mapped the properties of bean class and JSP using setProperty
action tag. We have given * in the property field to map the values based on
their names because we have used the same property name in bean class and
index.jsp JSP page. In the name field we have given the unique identifier which
we have defined in useBean tag.

<jsp:setProperty property="*" name="userinfo"/>


3) To get the property values we have used getProperty action tag.

<jsp:getProperty property="propertyname" name="userinfo"/>


Details.java

package beginnersbook.com;
public class Details {
public Details() {
}
private String username;
private int age;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}
index.jsp

<html>
<head><title>
useBean, getProperty and setProperty example
</title></head>
<form action="userdetails.jsp" method="post">
User Name: <input type="text" name="username"><br>
User Password: <input type="password" name="password"><br>
User Age: <input type="text" name="age"><br>
<input type="submit" value="register">
</form>
</html>
userdetails.jsp

<jsp:useBean id="userinfo" class="beginnersbook.com.Details"></jsp:useBean>


<jsp:setProperty property="*" name="userinfo"/>
You have enterted below details:<br>
<jsp:getProperty property="username" name="userinfo"/><br>
<jsp:getProperty property="password" name="userinfo"/><br>
<jsp:getProperty property="age" name="userinfo" /><br>

Vous aimerez peut-être aussi