0% found this document useful (0 votes)
3 views

Unit 4JavaServlet

The document provides an overview of Servlets and Java Server Pages (JSP) in advanced Java programming, detailing the role of Servlets as a middle layer between web clients and servers, and outlining their lifecycle phases including loading, initialization, service, and destruction. It also covers the creation of Servlets, the Servlet API, handling request parameters, cookies, session tracking, and the JSP lifecycle and architecture. Additionally, it highlights the advantages of JSP and its syntax, emphasizing its dynamic nature and integration capabilities.

Uploaded by

ghondeysaurab55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit 4JavaServlet

The document provides an overview of Servlets and Java Server Pages (JSP) in advanced Java programming, detailing the role of Servlets as a middle layer between web clients and servers, and outlining their lifecycle phases including loading, initialization, service, and destruction. It also covers the creation of Servlets, the Servlet API, handling request parameters, cookies, session tracking, and the JSP lifecycle and architecture. Additionally, it highlights the advantages of JSP and its syntax, emphasizing its dynamic nature and integration capabilities.

Uploaded by

ghondeysaurab55
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Advanced Java Programming

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.

• Following diagram shows the position of Servlets in a Web Application.


• A servlet is a Java programming language class used to extend the capabilities of
servers that host applications accessed via a request-response programming model.

• Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.

• Servlets can be created using the javax.servlet and javax.servlet.http packages,


which are a standard part of the Java's enterprise edition

• 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 life cycle of the servlet consists of following phases as follows:


• Servlet class is loaded.

• Servlet instance is created.

• Init() method is invoked.

• service () method is invoked.

• destroy () method is invoked.

Servlet Class is loaded

• The class loader is responsible to load the servlet class.

• 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.

Init() method is invoked

• 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.

• Syntax of the init() method is given below:

public void init(ServletConfig config) throws ServletException

service() method is invoked

• 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:

public void service(ServletRequest req, ServletResponse res) throws ServletException


destroy() method is invoked

• 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:

public void destroy()throws ServletException


Servlet API
• Servlet API consists of javax.servlet and javax.servlet.http packages represent interfaces and classes for Servlet API.

• 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

• The mostly used approach is by extending HttpServlet because it


provides http request specific method such as doGet(), doPost(),
doHead() etc.
By implementing Servlet interface:
import java.io.*;
import javax.servlet.*;

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

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 simple servlet</b>");

out.print("</body></html>");

public void destroy()

{System.out.println("servlet is destroyed");

public ServletConfig getServletConfig(){return config;}

public String getServletInfo(){return "copyright 2007-1010";}

}
By inheriting GenericServlet class

• GenericServlet class implements Servlet, ServletConfig and serializable


interfaces.

• It provides the implementation of all the methods of these interfaces except


the service method.

• GenericServlet class can handle any type of request so it is protocol-


independent.

• To create a generic servlet by inheriting the GenericServlet class and


providing the implementation of the service method.
Example:
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>");

}
}
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.

• There are many methods in HttpServlet class


• public void service(ServletRequest req,ServletResponse res)
• protected void service(HttpServletRequest req, HttpServletResponse res)
• protected void doGet(HttpServletRequest req, HttpServletResponse res)
• protected void doPost(HttpServletRequest req, HttpServletResponse res)
• protected void doHead(HttpServletRequest req, HttpServletResponse res)
• protected void doTrace(HttpServletRequest req, HttpServletResponse res)
• protected void doDelete(HttpServletRequest req, HttpServletResponse res)
Example:
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data

//writing html in the stream


pw.println("<html><body>");
pw.println("servlet Example by HttpServlet");
pw.println("</body></html>");

pw.close();//closing the stream


}}
Read Request parameters in servlet
• There are four methods to read request parameter
• getParameter(): Read the value of request parameter.

• getParameterValues(): Read either single value of a parameter or multiple


value of parameter.

• getParameterNames() : Read all request parameters names and to store them


in enumeration.

• 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.

• The deployment descriptor of the web application(web.xml) can define:

• The application name and description.

• Servlet classes and mapping to URL

• Servlet configuration (init) parameters.

• Servlet filters definitions and filter mappings

• Application context parameters

• Welcome files, Error message, MIME mappings

• Tag libraries references.

• Security and authentication settings


Sample code of web.xml file
<web-app>

<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.

• Cookie is created at server side and saved to client browser.

• 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

• There are 2 types of cookies in servlets.

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

• Here are steps for sending cookie to the client:

Create a Cookie object:

• javax.servlet.http.Cookie class provides the functionality of using cookies


• Cookie(): construct cookie.

• Cookie(String name, String value): construct cookie with specified name and value.

Set the maximum Age.

• 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);

How to read cookies

getCookies()method of HttpServletRequest interface is used to read all the cookies


from the browser
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
}
//index.html
<html>
<head>
<title>Cookie Example</title>
</head>
<body>
<form action="servlet1" method="post">
Name:<input type="text" name="uname"/><br/>
<input type="submit" name="submit"/>
</form>
</body>
</html>
//servlet1.java
Import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

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

response.addCookie(ck);//adding cookie in the response

//creating submit button

out.print("<form action='servlet2'>");

out.print("<input type='submit' value='go'>");

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();

• To set the session, we use setAttribute() method of session.

session.setAttribute(<Session_name>,<session_value>);

• To read the session , we use getAttribute() method of session.

session.getAttribute(<Sesion_name>);

• The Example below shows illustration of session tracking.


Session.html
<html>
<body>
<form action=“SetSession" method=“GET>
Name:<input type="text" name="uname"/>
<input type="submit" name="submit"/>
</form>
</body>
</html>
SetSession.java

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 is a server side scripting language technology that enables the


creation of dynamic, platform-independent method for building web-
based applications.

• JSP files are html files which contains special tags where java code is
embedded into it.

• JSP have .jsp extension


JSP Lifecycle
• JSP are deployed in the web server as servlet.

• 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.

• JSP is dynamic compilation, which means when a JSP is modified, it need


not be compiled and restarted in the web server. After the modification of
JSP, refresh the browser, changes will be reflected.

• JSP is Efficient: Every request for a JSP is handled by a simple Java


thread.

• JSP is Scalable: Easy integration with other backend services.


JSP Architecture
• Java Server Pages are part of a 3-tier architecture.

• 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.

• The following diagram shows the JSP architecture.


JSP Architecture cont…
• The user goes to a JSP page and makes the request via internet in user’s web browser.

• The JSP request is sent to the Web Server.

• 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 --%>

<%= “this is first jsp program” %>


<hr>
<%-- display by using scriptlet 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 --%>

<%= “processing HTML Form” %>


<hr>
<%-- display by using scriptlet 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.

• Every object created in a JSP page will have a scope.

• 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.

• Implicit object session has the ‘session’ scope.

Application

• A JSP object created using the ‘application’ scope can be accessed from any pages across the
application.

• The JSP object is bound to the application object.

• Implicit object application has the ‘application’ scope.


Exception handling in JSP
• Exception is an event, which occurs during the execution of a program, that disrupts the normal
execution of program.

• 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.

• There are two ways of handling exception in jsp


• By errorPage and isErrorPage attributes of page directive.
• By <error-page> elements in web.xml file
By errorPage and isErrorPage attributes of page directive.
• The page directive in JSP provides two attributes to be used in exception handling. They’re:

errorPage

Used to site which page to be displayed when exception occurred

Syntax:

<%@ page errorPage=“b.jsp ”%>

isErrorPage :

Used to mark a page as an error page where exceptions are displayed

Syntax:

<% @page isErrorPage=“true”%>


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"%>
<%@page errorPage = "error.jsp" %>
<%
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
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page isErrorPage = "true" %>

<h1> Exception caught</ h1>

The exception is : <%= exception %>


Handling Exceptions Using <error-page> Element in web.xml File

• 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>

<location>Error page url</location>

</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

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@page isErrorPage = "true" %>

<h1> Exception caught</ h1>

The exception is : <%= exception %>

//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.

• There are four techniques used is session tracking.


1.Cookies
2.Hidden form field
3.URL rewriting
4.HttpSession
• To manage session in jsp, session is an implicit object of type HttpSession
can be used.
Example:
//Index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
//welcome.jsp
<html>
<body>
<%

String name=request.getParameter("uname");
out.print("Welcome "+name);

session.setAttribute("user",name);

<a href="second.jsp">second jsp page</a>

%>
</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

• The most popular Java web frameworks are:


• Spring
• JSF (Java Server Faces)
• GWT (Google Web Toolkit)
• Play
• Struts
• Vaadin
• Grails

You might also like