You are on page 1of 15

Java Server Pages

 server-side technology for creating web


application & dynamic web content
 JSP tags are used to insert JAVA code into
HTML pages
 Connection to Database is easier
 Make Interactive websites
 Portable
 Powerful
 Flexible
 easy to maintain
 does not require advanced knowledge of JAVA
 capable of handling exceptions
 Easy to use and learn
 Implicit objects are there which reduces the
length of code Difficult to debug for errors.

JSP syntax
 Declaration Tag :-declare variables.
<%! Dec var %>
<%! int var=10; %>
 Java Scriplets :- add any number of JAVA
code, variables and expressions.
<% java code %>
 JSP Expression :- evaluates and convert the
expression to a string.
<%= expression %>
<% num1 = num1+num2 %>
 JSP Comments :- contains the text that is
added for information which has to be ignored
<% -- JSP Comments %>

Integrating scripts in JSPs


 The scripting elements provides the ability to
insert java code inside the jsp.
 There are three types of scripting elements:
1.scriptlet tag
2.expression tag
3.declaration tag.
 A scriptlet tag is used to execute java source
code in JSP.
<html>
<body>
<% out.print("welcome to jsp"); %> </body>
</html>

JSP components
 Directives
 Declarations
 Scriptlets
 Comments
 Expressions.

Implicit objects in a jsp page


1. out: output to the jsp client page. - used in the
backend and (servlet) to output information after
the execution
2. page object: simple instance of Object, and
essentially represents the current jsp page that
the client is using.
3. request: instance of HttpServletRequest and
represents a request (HTTP), from the client to
the server. Each time that a new request is made,
a new instance is created representing that exact
request. It is used heavily for important
information like headers, cookies, etc.
4. response: an instance of HttpServletResponse,
and represents the response of the server to the
client.
5. exception: instance of Exception, the Java class
used for throwing exceptions when something
goes wrong with the code.
6. config: ServletConfig class and used to access
information about the servlet and the
initialization of the jsp page.
7. pageContext: Used to access information about
the page, as well as to work with attributes of
different scopes and pages.
8. session: represents the current session of using
the jsp page, scope of this session, and it is
useful in order to keep attributes and values and
providing them in different jsp pages of the same
application.
9. application: used to keep objects and values in
order to access them in different jsp pages.
request Object
 The JSP request is implicit object which is
provided by HttpServletRequest.
 In servlet, we have to first import
javax.servlet.http.HttpServletRequest then we
have to create its object for taking input from
any HTML form as-
import javax.servlet.http.HttpServletRequest;
public class LoginServlet extends HttpServlet
{
protected void
doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{ HttpSession session = request.getSession()
}
}
 The request object is implicitly defined so that
you don’t have to create any object. JSP request
object is created by the web container for each
request of client. It’s used for getting the
parameter value, server name, server port etc.
response object
 This is the HttpServletResponse object
associated with the response to the client.
 The response object also defines the interfaces
that deal with creating new HTTP headers.
 Through this object the JSP programmer can add
new cookies or date stamps, HTTP status codes,
etc.
<%@ page language="java"
contentType="text/html;
charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%String
name=request.getParameter("username");out.print
("Welcome "+ name);%>
</body>
</html>
 In JSP the response object is implicitly defined
so you don’t have to create any object.
 JSP response object is created by the web
container for each request of client- used for
redirecting to any another resource.
JSP config implicit object
 This object can be used to get initialization
parameter for a particular JSP page.
 The config object is created by the web
container for each jsp page.
<%
out.print("Welcome
"+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>

Retrieving the Contents of


An HTML Format to JSP
 getParameter() method in getting data from a
client HTML page to a JSP page is dealt
 The request.getParameter() is being used here to
retrieve form data from client side.
 Steps to be followed-
1) First, a html page exGetParameter.html
accepts data from the client. The client
enters text in the space provided and clicks
on ‘Submit’.
2) Immediately the getparam.jsp page gets
called; it being mentioned in the action tag.
3) This JSP page fetches the data using
getParameter() method and displays the
same to the user.
<%@page contentType="text/html"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF 8">
<title>JSP Page</title>
</head>
<body>
<%-- Here we fetch the data using the name
attribute of the text from the previous page --%>
<% String val =
request.getParameter("testParam"); %> </body>
<%-- Here we use the JSP expression tag to display
value stored in a variable --%>
<h2>The text entered was : </h2>
<%=val%>
</html>

getQueryString() method
 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.
<% if(request.getQueryString() != null)
out.println(request.getQueryString()); %>

JSP Beans
 reusable software component
 A bean encapsulates many objects into one
object so that we can access this object from
multiple places
 easy maintenance
 The JavaBean properties and methods can be
exposed to another application
 Java class
 no-arg constructor
 does not have public variables
 defined in a named package, cannot be kept in
the default no-name package
 it implements Serializable interface, so that its
state can be stored and retrieved to and from
external storage, for persistent
 methods to set and get the values of the
properties, as getter and setter methods
 JavaBeans are mutable. So, it can't take
advantages of immutable objects
package mypack;
public class Employee implements
java.io.Serializable
{
private int id;
private String name;
public Employee()
{}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setName
(String name)
{
this.name=name;
}
public String getName()
{
return name;
} }
 To access the JavaBean class, we should use
getter and setter methods.
package mypack;
public class Test
{
public static void main(String args[])
{
Employee e=new Employee();
e.setName("Arjun");
System.out.println(e.getName());
}}
JSP Session Tracking
 In a web application, server may be
responding to several clients at a time.
 Hence, so session tracking is a way by
which a server can identify the client
uniquely.
 HTTP protocol is stateless which means
client needs to open a separate connection
every time it interacts with server and server
treats each request as a new request.
 In order to identify the client, server needs to
maintain the state and to do so, there are
several session tracking techniques.

Cookies
 small piece of information which is stored
in user’s computer.
 The web server uses a cookie to identify
the user in the next time visit.
 A cookie has attributes such as domain,
path, and timeout.
 JSP provides API to allows you to work
with cookie effectively through the object of
the class javax.servlet.http.Cookie.
 If cookie is associated with the client
request, server will associate it with
corresponding user session otherwise it will
create a new unique cookie and send it back
with response.
 Cookie objects are can be created using a
name value pair.
 For example, we can create a cookie with
the name sessionId and with a unique value for
each client.
 Later this can be added it in a response so
that it will be sent back to the client.
 Syntax of creating Cookie in a JSP is:
Cookie cookie = new Cookie(“sessionID”, “some
unique value”);
response.addCookie(cookie);
Creating cookies
1) Creating a Cookie object-

Call the Cookie constructor with a cookie


name and a cookie value, both of which are
strings.

2) Setting the maximum age-

Use setMaxAge to specify how long (in


seconds) the cookie should be valid.
cookie.setMaxAge(3600);

3) Sending the Cookie into the HTTP


response headers-

Use response.addCookie to add cookies in the


HTTP response header.

1. <%@page import="javax.servlet.http.Cookie"%>
2. <html>
3. <head>
4. <title>JSP Create Cookie</title>
5. </head>
6. <body>
7. <%
8. Cookie cookie = new Cookie("ClientID","username");
9. cookie.setMaxAge(3600);
10. response.addCookie(cookie);
11. %>
12. </body>
13. </html>

Reading Cookies
 To read a cookie from an HTTP request,
first call the method getCookies() of
the request object.
 This method returns a list of available
cookies in the request header, then walk
through all of them.
1. <%@page import="javax.servlet.http.Cookie"%>
2. <html>
3. <head>
4. <title>JSP Read Cookie</title>
5. </head>
6. <body>
7. <%
8. Cookie[] list = request.getCookies();
9. if (list != null){
10. for (int i = 0; i < list.length;i++){
11. out.println(list[i].getName() + ":" +
list[i].getPath());
12. }
13. }
14. %>
15. </body>
16. </html>

JSP Application Object


 Application implicit object is an instance
of javax.servlet.ServletContext.
 Used for getting initialization parameters
and for sharing the attributes & their values
across the entire JSP application
 Any attribute set by application implicit
object would be available to all the JSP pages.
 The JSP Application Object is used to get
the information from the web.xml as context-
param tag inside init-param.
 Some of the important methods in JSP
Application Object are:

Methods Return Type


getAttribute(string name) Object
getAttributeNames() java.util.Enumeration
getlnitparameter(string name) String
getlnitparameterNames() java.util.Enumeration
getRealPath(String path) string
getServerinfo() string
getMinorVersion() int
getMajorVersion() int
log(Message)() string

You might also like