Chapter 5 Servlets and JSP Notes
Chapter 5 Servlets and JSP Notes
Diagram:
GET POST
1) In case of Get request, only limited amount of In case of post request, large amount of
data can be sent because data is sent in header. data can be sent because data is sent in body.
2) Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.
3) Get request can be bookmarked Post request cannot be bookmarked
4) Get request is idempotent. It means second
request will be ignored until response of first request Post request is non-idempotent
is delivered.
5) Get request is more efficient and used more than Post request is less efficient and used less
Post than get.
GenericServlet :
It is a class implements Servlet, ServletConfig and Serializable interfaces. It provides the
implementaion of all the methods of these interfaces except the service method.
GenericServlet class can handle any type of request so it is protocol-independent.
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
• import java.io.*;
• import javax.servlet.*;
•
• public class First extends GenericServlet{
• public void service(ServletRequest req,ServletResponse res)
• throws IOException,ServletException{
•
• res.setContentType("text/html");
•
• PrintWriter out=res.getWriter();
• out.print("<html><body>");
• out.print("<b>hello generic servlet</b>");
• out.print("</body></html>");
•
• }
• }
HttpSrevlet Class:
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It
provides http specific methods such as doGet, doPost, doHead, doTrace et
\\Session Id
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to
another resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make another request. So, it can
work inside and outside the server.
Import java.io.*;
• import javax.servlet.*;
• import javax.servlet.http.*;
• pw.close();
• }}
Session Tracking:
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each
time user requests to the server, server treats the request as the new request. So we need to maintain
the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure
given below
Method Description
public HttpSession getSession() Will cause one session to be created.
public HttpSession getSession(boolean) true = will cause one to be created;
false = will return null (no session)
public String getRequestedSessionId() Gets the ID assigned by the server to the session
public Boolean isRequestedSessionIdValid() Returns true if the request contains a valid session
ID
public Boolean Returns true if the session ID was sent as part of a
isRequestedSessionIdFromCookie() cookie
public Boolean Returns true if the session ID was sent through
isRequestedSessionIdFromURL() URL rewriting
Cookie:
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
1) Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP.
In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in
JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation
logic. In servlet technology, we mix our business logic with the presentation logic.
1. <%=statement%>
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>
Expression of variables
In this example we have initialized few variables and passed the expression of variables in the
expression tag for result evaluation.
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>
<%
int a=10;
int b=20;
int c=30;
%>
<%= a+b+c %>
</body>
</html>
JSP directives
The jsp directives are messages that tells the web container how to translate a JSP page into
1) import
The import attribute is used to import class,interface or all the members of a package.It is similar to
import keyword in java class or interface.
Example of import attribute
1. <html>
2. <body>
3.
4. <%@ page import="java.util.Date" %>
5. Today is: <%= new Date() %>
6.
7. </body>
8. </html>
2) contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is "text/html;charset=ISO-8859-1".
3) extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.
4) info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
<%!
String name = "Mark";
String date = "28th April, 2004";
%>
<HTML>
<TITLE>Declaration Tag Example</TITLE>
<BODY>
This page was last modified on <%= date %> by <%= name %>.
</BODY>
</HTML>
JSTL:
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for
manipulating XML documents, internationalization tags, and SQL tags. It also provides a
framework for integrating existing custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into following JSTL tag library groups
that can be used when creating a JSP page:
• Core Tags
• Formatting tags
• SQL tags
• XML tags
• JSTL Functions
Core Tags:
The core group of tags are the most frequently used JSTL tags. Following is the syntax to include
JSTL Core library in your JSP:
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
Formatting tags:
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Web sites. Following is the syntax to include Formatting library in your JSP:
<%@ taglib prefix="fmt"
uri="http://java.sun.com/jsp/jstl/fmt" %>
Following is the list of Formatting JSTL Tags:
Tag Description
<fmt:formatNumber> To render numerical value with specific precision or format.
<fmt:parseNumber> Parses the string representation of a number, currency, or percentage.
<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern
<fmt:parseDate> Parses the string representation of a date and/or time
<fmt:bundle> Loads a resource bundle to be used by its tag body.
<fmt:setLocale> Stores the given locale in the locale configuration variable.
Loads a resource bundle and stores it in the named scoped variable or the
<fmt:setBundle>
bundle configuration variable.
Specifies the time zone for any time formatting or parsing actions nested in
<fmt:timeZone>
its body.
<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable
<fmt:message> To display an internationalized message.
<fmt:requestEncodin
Sets the request character encoding
g>
SQL tags:
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as
Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql"
uri="http://java.sun.com/jsp/jstl/sql" %>
TLD
1. It is Tag library descriptor
3. It is a XML file
4. We can create custom tags in TLD
Java Security
As java is internet language so we need security for it.
Import java.security is the package in which it contains number of classes related to security
and Guard.
1.Permission class
Permission class is used to give the permissions to the standard code.
Syntax:
AllPermission
FilePermission
unResolvedPermission
Policy class
Policy class is used to run the code in run environment or not.
Syntax:
void setPolicy()
String getPolicy()