Unit 4JavaServlet
Unit 4JavaServlet
Unit-4
Servlets and Java Server pages
Introduction to Servlet
• Servlets are programs that run on a Web or Application server and act as a middle layer between a
requests coming from a Web browser or other HTTP client and databases or applications on the
HTTP server
• Using Servlets, we can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
• Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.
• All servlets must implement the Servlet interface, which defines life-cycle
methods.
Life cycle of servlets
• The web container maintains the life cycle of a servlet instance.
• The servlet class is loaded when the first request for the servlet is received by the web container
Servlet instance is created
• The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only
once in the servlet life cycle.
• The web container calls the init method only once after creating the servlet instance. The init() method is used to
initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface.
• The web container calls the service method each time when request for the servlet is received. If servlet is not
initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it
calls the service method. Notice that servlet is initialized only once.
• The syntax of the service() method of the Servlet interface is given below:
• The web container calls the destroy method before removing the servlet instance from the service.
• It gives the servlet an opportunity to clean up any resource for example memory, thread etc.
• The syntax of the destroy method of the Servlet interface is given below:
• The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are
not specific to any protocol.
• The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
servlet example
• The servlet example can be created by three ways:
1.By implementing Servlet interface,
2.By inheriting GenericServlet class, (or)
3.By inheriting HttpServlet class
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("</body></html>");
{System.out.println("servlet is destroyed");
}
By inheriting GenericServlet class
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
By inheriting HttpServlet class
• The HttpServlet class extends the GenericServlet class and implements Serializable
interface.
• It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
• getParameterMap() : Read the key and value pair of request into a map
object.
Example:
//input.html
<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form action="formread" method="POST">
Name:<input type="text" name="uname"/>
Age:<input type="number" name="uage"/>
<input type="submit" name="submit"/>
</form>
</body>
</html>
//formread.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class formread extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
String age=request.getParameter("uage");
out.println("your name:"+name+"<br>");
out.println("your Age:"+age+"<br>");
out.close();
}
}
Deployment Descriptor
• Deployment descriptor is XML file known as web.xml. file that contains configuration of the java web application.
• The deployment descriptor describes the deployment information (or Web Information) of a Servlet.
<servlet>
<servlet-name>servletName</servlet-name>
<servlet-class>servletClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletName</servlet-name>
<url-pattern>/ServletName</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Introduction to cookies
• Cookie is a small piece of information which is stored at client browser. It is used to recognize the user.
• 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.
• Each time when client sends request to the server, cookie is embedded with request. Such way, cookie
can be received at the server side.
• By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet.
• So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is
added with request by default. Thus, we recognize the user as the old user
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.
How to send Cookies to the Client
• Cookie(String name, String value): construct cookie with specified name and value.
• By using setMaxAge () method we can set the maximum age for the particular
cookie in seconds
• Cookieobj.setMaxAge(int expiry): sets the maximum age of cookie in seconds
Place the Cookie in HTTP response header:
We can send the cookie to the client browser through response.addCookie() method.
i.e, response.addCookie(cookie_obj);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
out.print("<form action='servlet2'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
//SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Session tracking in servlets
• A session is a way to store information to be used across multiple
pages.
• Session is used to store and pass information from one user to another
,temporally ( until use close the website)
• Session creates unique user id for each browser to recognize the user
and avoid conflict between multiple browser.
• There are four techniques used is session tracking.
1.Cookies
2.Hidden form field
3.URL rewriting
4.HttpSession
• HttpSession object can be created by calling the public method getSession()
of HttpServletRequest, as below
HttpSession session=request.getSession();
session.setAttribute(<Session_name>,<session_value>);
session.getAttribute(<Sesion_name>);
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetSession extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out = response.getWriter();
String nstr=req.getParameter("uname");
HttpSession session=req.getSession();
session.setAttribute("name", nstr);
out.println("<a href='ReadServlet'> click here to read session</a>");
}
}
ReadServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ReadServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=req.getSession();
String sessionname=(String) session.getAttribute(“name”);
out.println(“the sssion value=“+sessionname);
}
}
Introduction to JSP
• JSP is a technology based in java which produces dynamic web pages.
• JSP files are html files which contains special tags where java code is
embedded into it.
• The JSP page is compiled to servlet by JSP engine, eliminating the html tags
and putting them inside out.println() statements and removing the jsp tags.
• Once it is translated into servlet then the servlet, then it follows the servlet
lifecycles
• jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
Advantages of JSP
• User need not write HTML and JAVA code separately.
• JSP can be used for both front end and for writing business logic.
• A server(generally referred to as application or web server) supports the Java Server Pages.
• This server will act as a mediator between the client browser and a database.
• Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet
Engine.
• If the JSP file has been called the first time then the JSP file is parsed otherwise servlet is
instantiated. The next step is to generate a servlet from the JSP file. The generated servlet
output is sent via the Internet form web server to users web browser.
• Now in last step, HTML results are displayed on the users web browser.
JSP syntax
There are five main tags that all together form JSP syntax
These tags are:
1.Declaration tags
2.Expression tags
3.Diractive tags
4.Scriptlet tags
5.Action tags
Declaration tags
This tag allows the developer to declare one or multiple variable and methods.
They do not produce any output.
Syntax:-
<%! Declarations %>
Example:-
<%!
public String name;
public int age;
public void setDetail(name,age);
%>
Expression tag
This tag allows the developer to embed single java expression which is not terminated by a semi
colon.
Syntax:-
<%= expression %>
Example:- Date: <%= new java.util.Date() %>
Scriplets tag
This tag allows the developer to embedded java code inside it that can use the variable declared
earlier.
Syntax:-
<% java code %>
Example:-
<%
int sum=a+b;
system.out.println(sum);
%>
Directives tag
This tag is used to convey special information about the page to the jsp engine.
Syntax:-
<%@ %>
Three kinds of Directives are available:-
page
include
tag library
page directive
This directive informs the jsp engine about the headers and facilities that the page should
get from the environment. There can be any number of page directives in a jsp page.
Declared usually at the top.
Syntax:-
<%@page attribute= %>
Attributes can be; include, import, session, etc.
Example: <%@page import=“package_name”%>
Include directive
This is used to statically include one or more resources to the jsp page. This
allows the jsp developer to reuse the code.
Syntax:-
<%@include page=“”%>
Example: <%@include page=“abc.jsp”%>
There is only on attribute named “page” in include directive.
JSP Comment:
Jsp comments marks text or statements that the jsp container should be ignore
Syntax:-
<% -- This is jsp comment --%>
JSP implicit objects
There are certain objects in jsp that can be used in jsp page without being
declared these are Implicit objects. There are nine implicit object in JSP:-
1. request
2. response
3. out
4. application
5. page
6. pageContext
7. config
8. session
9. exception
Example: first.jsp
<html>
<head>
<title>jsp first Example</title>
</head>
<body>
<%-- display by using expression tag --%>
<%
out.println(“welcome BSCCSIT students to write jsp program”);
%>
</body>
</html>
Form Processing in JSP
• Form processing in jsp is similar to form processing in servlets.
• We can also use request object to read parameter values from HTML file or another jsp
file.
• Method supported by request object are similar to methods used in servlets.
Example:
index.html
<html>
<body>
<form action="calculate.jsp" method="post">
Eneter first number:<input type="number" name="fnum"/><br>
Eneter first number:<input type="number" name="snum"/><br>
<input type="submit" value="ADD" />
</form>
</body>
</html>
Calculate.jsp
<html>
<head>
<title>Form processing to add</title>
</head>
<body>
<%-- display by using expression tag --%>
<%
int a=Integer.parseInt(request.getParameter(“fnum”));
int b=Integer.parseInt(request.getParameter(“snum”));
int c=a+b;
out.println(“sum =”+c);
%>
</body>
</html>
Object Scope in JSP
• The availability of a JSP object for use from a particular place of the
application is defined as the scope of that JSP object.
• Object scope in JSP is segregated into four parts and they are
• page
• request
• session
• application.
Page
• ‘page’ scope means, the JSP object can be accessed only from within the
same page where it was created.
• JSP implicit objects out, exception, response, pageContext, config and
page have ‘page’ scope.
Request
• A JSP object created using the ‘request’ scope can be accessed from any
pages that serves that request.
• Implicit object request has the ‘request’ scope.
Session
• ‘session’ scope means, the JSP object is accessible from pages that belong to the same session from
where it was created.
• The JSP object that is created using the session scope is bound to the session object.
Application
• A JSP object created using the ‘application’ scope can be accessed from any pages across the
application.
• When an error occurs within a method, the method creates an object and hands it off to the run
time system.
• The object, called an exception object contains information about the error, including its type and
state of the program
• Creating exception object and handling it to runtime system is called throwing exception.
errorPage
Syntax:
isErrorPage :
Syntax:
int x = Integer.parseInt(num1);
int y = Integer.parseInt(num2);
int z = x / y;
out.print("division of numbers is: " + z);
%>
//error.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page isErrorPage = "true" %>
• This is another way of specifying the error page for each element, but instead of using the
errorPage directive, the error page for each page can be specified in the web.xml file, using
the <error-page> element
Syntax:
<web-app>
<error-page>
<exception-type>Type of Exception</exception-type>
</error-page>
</web-app>
Example:
//index.html
<html>
<head>
<title>Exception Handling</title>
</head>
<body>
<form action="divide.jsp" method="GET">
Fnum:<input type="number" name="fnum">
Snum:<input type="number" name="snum">
<input type="submit" name="submit">
</form>
</body>
</html>
//divide.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
String num1= request.getParameter("fnum");
String num2 = request.getParameter("snum");
int x = Integer.parseInt(num1);
int y = Integer.parseInt(num2);
int z = x / y;
out.print("division of numbers is: " + z);
%>
//error.jsp
//web.xml
<web-app>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
Session Management in JSP
• A session is a way to store information to be used across multiple pages.
• Session is used to store and pass information from one user to another ,temporally ( until
use close the website)
• Session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browser.
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
</body>
</html>
//second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
Introduction to Java Web Frameworks
• Frameworks are tools with pre-written code, that act as a template or skeleton, which can be reused
to create an application by simply filling with your code as needed which enables developers to
program their application with no overhead of creating each line of code again and again from
scratch