Académique Documents
Professionnel Documents
Culture Documents
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
o scriptlet tag
o expression tag
o declaration tag
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
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>
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.
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
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>
The code written inside the jsp declaration tag is placed outside the service() method of
auto generated servlet.
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>
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.
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).
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>
Enumerator e = request.getAttributeNames();
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
response.containsHeader("Site");
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>
Methods
application.removeAttribute(MyAttr);
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
exception.jsp
Syntax of Directives:
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.
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.
Examples of session:
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.
Example of isErrorPage:
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.
Example of errorPage:
5. contentType:
This attribute is used to set the content type of a JSP page.
Example of contentType:
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.
Example of buffer:
Syntax of info:
Syntax of language:
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.
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.
Example of Targlib:
1. <jsp:include> Action
Like include page directive this action is also used to insert a JSP file in
another file.
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> :
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> :
<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>:
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
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
<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>
<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>
<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.
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.
It sets the maximum time which should apply till the cookie expires
Public intgetMaxAge()
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.
Action_cookie_main.jsp
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: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
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.
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