0% found this document useful (0 votes)
12 views10 pages

Serv Lets

Servlet technology enables the creation of dynamic web applications on the server side, improving upon the older CGI technology by offering platform independence, better security, and faster processing. The servlet life cycle includes loading the servlet class, creating an instance, and invoking methods for initialization, service, and destruction. JSP addresses the limitations of servlets by separating business and presentation logic, making it easier to manage and develop web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

Serv Lets

Servlet technology enables the creation of dynamic web applications on the server side, improving upon the older CGI technology by offering platform independence, better security, and faster processing. The servlet life cycle includes loading the servlet class, creating an instance, and invoking methods for initialization, service, and destruction. JSP addresses the limitations of servlets by separating business and presentation logic, making it easier to manage and develop web applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Servlets

Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).

CGI: Before servlets CGI(Common Gateway Interface) technology was used to develop
dynamic web pages. The CGI programs can be designed in the native OS and kept in particular
directory. Web Servers communicates with these external program via an interface called CGI.
CGI Vs Servlet

BASIS FOR
CGI SERVLET
COMPARISON

Basic Programs are written in the Programs employed using Java.


native OS.

Platform dependency Platform dependent Does not rely on the platform

Creation of process Each client request creates its Processes are created depending on
own process. the type of the client request.

Conversion of the Present in the form of Compiled to Java Bytecode.


script executables (native to the server
OS).

Runs on Separate process JVM

Security More vulnerable to attacks. Can resist attacks.

Speed Slower Faster

Processing of script Direct Before running the scripts it is


translated and compiled.

Portability Can not be ported Portable

Life Cycle of a Servlet:


1) Servlet class is loaded: The classloader 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.
2) 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.
3) 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.
public void init(ServletConfig config) throws ServletException
4) service() method is invoked: The web container calls the service method each time when
request for the servlet is received.
public void service(ServletRequest request, ServletResponse response)
5) 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.
public void destroy()

Servlet API
Interfaces Description
Servlet Declares life cycle methods that all servlets must implement.
ServletConfig Allows servlets to get initialization parameters
ServletContext Allows servlets to communicate with its servlet container.
ServletRequest Provides client request information to a servlet.
ServletResponse Assist a servlet in sending a response to the client.

Classes Description
GenericServlet Provides a basic implementation of the Servlet interface for
protocol independent servlets
ServletlnputStream Provides an input stream for reading binary data from a client
request.
ServletOutputStream Provides an output stream for sending binary data to the client.
ServletException Defines a general exception, a servlet can throw when it
encounters difficulty.

Interfaces and classes from java.servlet.http package


Impotant Interfaces in javax.servlet.http package
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
Important Classes in javax.servlet.http package
1. HttpServlet
2. Cookie
important methods of HttpServletRequest

Methods Description

Cookies getCookies() returns an array containing all of the Cookie objects the client sent with
this request

HttpSession getSession() returns the current HttpSession associated with this request or, if there is
no current session and create is true, returns a new session

String getMethod() Returns the name of the HTTP method with which this request was made,
for example, GET, POST, or PUT.

String getServletPath() returns the part of this request's URL that calls the servlet

Some Important Methods of HttpServletResponse

Methods Description

void addCookie(Cookie cookie) adds the specified cookie to the response.

void sendRedirect(String location) Sends a temporary redirect response to the client using the
specified redirect location URL and clears the buffer

int getStatus() gets the current status code of this response


String getHeader(String name) gets the value of the response header with the given name.

void setHeader(String name, sets a response header with the given name and value
String value)

Handling Http Request and Http Response


// Simple Calculator Example
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class serv6 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
int x=Integer.parseInt(request.getParameter("t1"));
int y=Integer.parseInt(request.getParameter("t2"));
String opr=request.getParameter("s1");
opr=opr.trim();
int op=Integer.parseInt(opr);
int result=0;
switch(op)
{
case 1: result=x+y; break;
case 2: result=x-y; break;
case 3: result=x*y; break;
case 4: result=x/y; break;
}
PrintWriter pw=response.getWriter();
pw.println("Result = "+result);
}
}

Cookies:
Cookie is a bit of information created by server for the first client request and will sent back to
the client browser.
For the subsequent client request, all the cookies that the web browser has will be automatically
forwarded to the server along with the client request.
Size of the cookies are limited.
Generally cookies will expire when we close the browser window. If we want our cookies to
persist for more time, we can set age for cookies.
Generally Cookies are used to exchange key,value pairs between web browser and web server.
Creating & sending cookies to client:
Cookie ck1=new Cookie("username","shiva");
response.addCookie(ck1);
Accessing all cookies coming from client:
PrintWriter out=response.getWriter();
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++) {
out.print(ck[i].getName()+" ");
out.println(ck[i].getValue());
}
}

Session Tracking:
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of 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 the user to recognize to particular user.
Creating an instance of current date and time and storing in session
Date d1=new Date();
HttpSession s1=request.getSession();
s1.setAttribute("mydate",d1);
getSession() in the above code returns a reference to the existing session if exists else create a
new session and returns that session object.
setAttribute() helps use store our data(objects) with some name.
getSession() method also returns a cookies to the client browser with this new session id, so
when the same client make the second request, server will compare the session id value inside
the cookie to identify the client.
Accessing the data( date object) from session:
HttpSession s=request.getSession(false);
Date d=(Date)s.getAttribute("mydate");
response.getWriter().println(d);

JSP
Problems with Servlets
The Servlet itself contains the code for all aspects of the application like Request processing,
Business logic & Presentation logic.
html code(presentation logic) is embedded inside java code(business logic).
1. Changes in the look and feel (presentation) of the application requires the Servlet to be
updated and recompiled.
2. Developer needs proficiency in both web page designing and java.
3. Difficult to use development tools.
for example, if we use a tool to develop a user interface design, the generated html code has to be
manually inserted with in the java code which is time consuming and error prone.

Benefits of JSP:
1. JSP Separates business logic and presentation logic.
i) Presentation logic(html code) can be written in a jsp file directly(as if you are writing in a
HTML file).
ii) Business logic (java code) should be written inside JSP elements.
2. JSP has built objects, which helps in reducing development effort.

Anatomy of a JSP File


1. Template text:
it can be plane text, html code, XML code or any other markup language code.
2. JSP Elements:
i) Scripting elements ( declarations, expressions, scriptlets)
ii) Directives (page, include & taglib)
iii) Actions
iv) EL (Expression Language) expressions.
v) Comments.
When a JSP file is requested by the client, the template text is merged with dynamic content
generated by JSP elements and sent as a response back to the client.

JSP Processing:

Translation phase:
When the first client sends a request for a JSP file, JSP file will be converted into a Servlet.
The “.jsp ” converted to “.java”
i) The html code present in the JSP file will be converted to the corresponding println()
statements.
ii) The JSP elements will be converted to the java code that implements the corresponding
dynamic behaviour.
The converted “.java” file is compiled and generates “.class” file.
This “.class” file is called as jsp page implementation class.
Then an instance for the jsp page implementation class is created.
Request processing phase:
The container invokes service() to process client request.

MVC Design Pattern


1. Model: Represents Business logic.
Responsible for generating the content(data) what the client has requested for.
Generally the java code that access the data from Database(if required) , process the data and
generates the response requested by the client.
2. View: Represents Presentation logic.
Responsible for presenting the content(data) generated by the Model components.
We can have more than on View component for one Model component.
Technologies used are: i) HTML ii) JSP
3. Controller: Represents Request Processing.
The Controller is responsible for controlling the application logic and acts as the coordinator
between the View and the Model.
The Controller receives an input from the users via the View, then processes the user's data with
the help of Model and passes the results back to the View for displaying the results to client
browser.
Technologies used are
i) Java Beans ii) Enterprise JavaBeans iii) POJO (Plane Old Java Objects)

JSP Elements
1.Directives: Directives are translation time instruction to the JSP container.
We have 3 type of directives : page, include & taglib.
example of page directive:
<%@ page language="java"
contentType="text/html”
extends="demotest.DemoClass“
import="java.util.Date“
session=“true/false“
isThreadSafe="true/false“
isErrorPage=“true/false“
errorPage="errorHandler.jsp“%>
2. JSP Scripting Elements:
1.Declarations:
A declaration tag is a piece of Java code for declaring variables and methods.
If we declare a variable or method inside declaration tag it means that the declaration is made
inside the Servlet class but outside the service() method.
Example
<%! int count =10; %>
JSP Elements
2. Scripting Elements
Scriptlets:
1. Allows you to write Java code in JSP file.
2. JSP container moves statements in _jspservice() method while generating Servlet from JSP.
Example:
<%
int num1=10;
int num2=40;
int num3 = num1+num2;
out.println("Scriplet Number is " +num3);
%>
3.Actions
We can dynamically insert a file, reuse the bean components, forward user to another page, etc.
through JSP Actions Unlike directives, actions are re-evaluated each time the page is accessed.
Example
<jsp:useBean id="name“ class="demotest.DemoClass">
<jsp:include page="date.jsp“ />
<jsp:forward page="jsp_action_42.jsp" />

JSP Built in Objects – Servlet Classes


request (HttpServletRequest)
response(HttpServletResponse)
out(JSPWriter)
config(ServletConfig)
exception(Throwable)
session(HttpSession)
application(ServletContext)
page
pageContext

You might also like