SlideShare uma empresa Scribd logo
1 de 27
GTU SYLLABUS COURSE MATERIAL
SERVLET
Definition :-
Servlets are Java classes that extend the functionality of a Web server by
dynamically generating Web pages. A run-time environment known as a servlet
engine manages servlet loading and unloading, and works with the Web server to
direct requests to servlets and to send output back to Web clients.
Servlettechnology is robustand scalable as it uses the java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was used as a server-side
programming language. But there were many disadvantages of this technology.
Servlet can be described in many ways, depending on the context.
 Servlet is a technology i.e. used to create web application.
 Servlet is an API that provides many interfaces and classes including
documentations.
 Servlet is an interface that must be implemented for creating any servlet.
 Servlet is a class that extend the capabilities of the servers and respond to the
incoming request. It can respond to any type of requests.
 Servlet is a web component that is deployed on the server to create dynamic
web page.
Advantage of Servlet :-
The basic benefits of servlet are as follows:
1. better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so no need to worry about memory
leak, garbage collection etc.
4. Secure: because it uses java language..
5. Simplicity: Client-side Java applet runs in a virtual machine provided by
Web Browser. So, various compatibility issues that increase complexity and
also it limits the functionality. Servlets simplify this situation considerably
because they run in a virtual machine in a controlled server environment and
require only basic HTTP to communicate with their clients. No special client
software is required, even with older browsers.
6. HTTP Sessions: Although HTTP servers have no built-in capability to
remember details of a previous request from the same client, the Servlet API
provides an HttpSession class that overcomes this limitation.
7. Access to Java Technology: Servlets, being Java applications, have direct
access to the full range ofJava features, suchas threading, network access and
database connectivity.
8. Servlets are persistance.
What is the difference between Get and Post?
There are many differences between the Get and Post request. Let's see these
differences:
GET POST
1) In case of Get request, only limited
amount of data can be sent because
data is sent in header.
In case of postrequest, large amount
of data can be sent because data is sent
in body.
2) Get request is not securedbecause
data is exposed in URL bar.
Postrequest is securedbecausedata is
not exposed in URL bar.
3) Get request can be bookmarked Postrequest cannot be bookmarked
4) Get request is idempotent. It means
second request will be ignored until
responseof first request is delivered.
Postrequest is non-idempotent
5) Get request is more efficient and
used more than Post
Postrequest is less efficient and used
less than get.
Servlet Applets
1)subclass of GenericServlet
2)Runs in a server
3)must be multi threaded or
thread per applet
4)no direct user interface
interface
1)subclass of Applet
2)Runs in a browser
3)generally single thread safe
4)uses AWT for user
Method summary of servlet class :-
public void init(ServletConfig config)
public void service(ServletRequest request,ServletResponse response)
public void destroy()
public ServletConfig getServletConfig()
public String getServletInfo()
public string getInitParameter(string pname)
public ServletContext getServletContext()
Methods of HTTP servlet 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 doOptions(HttpServletRequest req, HttpServletResponse res)
protected void doPut(HttpServletRequest req, HttpServletResponse res)
protected void doTrace(HttpServletRequest req, HttpServletResponse res)
protected void doDelete(HttpServletRequest req, HttpServletResponse res)
Servlet Life Cycle:-
servlets operate in the context of a request and responsemodel managed by a servlet
engine.. The engine does the following:
class is loaded.
instance is created.
method is invoked.
method is invoked.
method is invoked.
init():
When a request is received by the servlet engine, it checks to see if the servlet is
already loaded. If not, servlet engine calls an initialization method with the
following signature:
public void init(ServletConfig config) throws ServletException
The ServletConfig object provides access to the servlet context and to any
initialization parameters coded for the servlet init() method, the servlet can
perform any necessary startup tasks, such as establishing database connections.
If any errors occurthat make the servlet unable to handle requests, it should throw
an UnavailableException.
service():
After the init() method completes successfully, the servlet is able to accept
requests. By default, only a single instance ofthe servlet is created, and the servlet
engine dispatches each request to the instance in a separate thread. The servlet
method that’s called has the following signature:
public void service(ServletRequest request,ServletResponse response) throws
ServletException, IOException
The ServletRequest object is constructed by the servlet engine and acts as a
wrapper for information about the client and the request.The ServletResponse
object provides the means for a servlet to communicate its results back to the
original requester.
The General service() method is rarely used , because The most servlets are
designed to operate in the HTTP environment, for which there’s a specialized
javax.servlet.http package, most servlets extend its subclass
javax.servlet.http.HttpServlet. This subclass provides specialized methods
corresponding to each HTTP request method: GET requests are handled by
doGet(),POST requests by doPost(), and so on.
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
destroy():
The servlet specification allows a servlet engine to unload a servlet at any time.
used to conservesystem resources or in preparation for servlet engine shutdown.
The servlet engine notifies each loaded servlet that this is about to happen by
calling its destroy() method. By overriding destroy(), you can release any
resources allocated during init().
public void destroy()
Compare Generic Servlet with Http Servlet?
GenericServlet HttpServlet
1) defines a generic, protocol
independent servlet.
2) GenericServlet is an abstractclass it can
handle all types of protocols
3)In generic we use only service method.
4)GenericServlet gives a blueprint and
makes writing servlet easier.
1)HttpServlet defines a HTTP protocol
specific servlet.
2)HttpServlet can handle only Http
specific protocols.
3) Http we use doGet()& doPost()bcznow
a days we useonly http WWW depends up
on Http protocols.
4) HttpServlet gives a blueprint for Http
servlet and makes writing them easier.
Compare ServletContext and ServletConfig..
Servlet Context Servlet Config
1)ServletContext object has global
behaviour.
2)There is only one servlet context
object for context(project).
3) we can access servlet config
from context.
4)All methods of servlet config are
not applicable to servlet context.
1)Servlet Config is private for Servlet
& jsp component.
2)There is only one Servletconfig for
Servlet and jsp component..
3)We can’t access servlet context
from servlet config
4) All methods of servlet context
are applicable to servlet config but
only the scope bounds.
Difference betweenforward() and sendRedirect()method
There are many differences between the forward() method of RequestDispatcher
and sendRedirect() method of HttpServletResponse interface. They are given
below:
Forward() SendRedirect()
The forward() method works at server side. The sendRedirect() method works
at client side.
It sends the same request and response
objects to another servlet.
It always sends a new request.
It can work within the server only. It can be used within and outside
the server
Example:
request.getRequestDispacher("servlet2").for
ward(request,response);
Example:
response.sendRedirect("servlet2");
Methods of ServletConfig interface
1. public String getInitParameter(String name):Returns the parameter value for
the specified parameter name.
2. public Enumeration getInitParameterNames():Returns an enumeration of all
the initialization parameter names.
3. public String getServletName():Returns the name of the servlet.
4. public ServletContext getServletContext():Returns an object of
ServletContext.
Commonly used methods of ServletContextinterface
There is given some commonly used methods of ServletContext interface.
1. public String getInitParameter(String name):Returns the parameter value
for the specified parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the
context's initialization parameters.
3. public void setAttribute(String name,Object object):sets the given object
in the application scope.
4. public Object getAttribute(String name):Returns the attribute for the
specified name.
5. public Enumeration getInitParameterNames():Returns the names of the
context's initialization parameters as an Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with
the given name from the servlet context.
What is Session? How can you handle session with cookie? Discuss
the scenario with sample code.
Because the Web server doesn’t remember clients from one request to the
next, the only way to maintain a session is for clients to keep track of it. You
can accomplish this in two basic ways:
 Have the client remember all session-related data and send it back to
the server as needed.
 Have the server maintain all the data, assign an identifier to it, and have
the client remember the identifier.
The first approachis simple to implement and requires no special capabilities
on the part of the server. This approachcan entail transmitting large amounts
of data back and forth, however, which might degrade performance. Another
problem is server-side objects, suchas databaseand network connections have
to be reinitialized with every request. For these reasons, this approachis best
suited for long-term persistence of small amounts of data, such as user
preferences or account numbers.
The second approach offers more functionality. Once a server initiates a
session and the client accepts it, the server can build complex, active objects
and maintain large amounts of data, requiring only a key to distinguish
between sessions.
Four techniques are commonly used to maintain session:
 Hidden fields
 URL rewriting
 Cookies
 The HTTP session API
Cookies:
The most widely used technique for persistent client data storage involves
HTTP cookies. A cookie is a small, named data elementthe server passes to
a client witha Set-Cookie header as part of the HTTP response. The client
is expected to store the cookie and return it to the server with a Cookie header
on subsequent requests to the same server. Along with the name and value,
the cookie may contain
 An expiration date
 A domain name
 A path name
 A secure attribute
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.
Working:
First, the Web browser requests a page from the Web server. No cookies are
involved at this point. When the server responds with the requested document,
it sends a Set-Cookie header assigning the value fr to a cookie named
language. The cookie is set to expire in one year. The browser reads this
header, extracts the cookie information, and stores the name/value pair in its
cookie cache, along with the Web server’s domain and default path. Later,
when the user visits the page again, the browser recognizes it previously
received a cookie from this server and the cookie hasn’t yet expired, and,
therefore, sends the cookie back to the server.
Advantages:
One advantage of cookies over other persistence schemes is they can retain
their values after the browser sessionis over, even after the client computer is
rebooted. This makes cookies well suited for maintaining users’ preferences,
such as language.
Disadvantages:
One of the drawbacks of using cookies is that cookies are not fully supported
by some browsers and the most browsers limit the amount of data that can be
stored with a cookie.
Cookies are stored on client side. So it can be easily disabled. So, secured data
can’t be stored into cookie.
Example1:
index.html
1. <form action="servlet1" method="post">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29.}
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22.}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10.<url-pattern>/servlet1</url-pattern>
11.</servlet-mapping>
12.
13.<servlet>
14.<servlet-name>s2</servlet-name>
15.<servlet-class>SecondServlet</servlet-class>
16.</servlet>
17.
18.<servlet-mapping>
19.<servlet-name>s2</servlet-name>
20.<url-pattern>/servlet2</url-pattern>
21.</servlet-mapping>
22.
23.</web-app>
Output :-
Example2:
//Cookiee_loginview.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class cookiee_loginview extends HttpServlet
{
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext con=getServletContext();
try {
out.println("<html>");
out.println("<body>");
out.println("<form action='cokiee'> " +
"UserName : <input type='text' name='unm'><br><br>" +
"<input type='submit' value='submit'>" +
"<input type='reset' value='reset'> " +
"</form>");
String m=con.getAttribute("msg").toString();
if(m!=null)
{
Cookie[] coki=request.getCookies();
Cookie ck=coki[0];
if(ck.getValue()!=null)
{
out.println("Sucessfully logged in");
}
}
else
{
out.println("Please Try again");
}
out.println("</body>");
out.println("</html>");
}
finally
{
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
//Cokiee.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class cokiee extends HttpServlet
{
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext con=getServletContext();
try
{
String user=request.getParameter("unm");
con.setAttribute("msg","true");
if(user.equals("admin"))
{
Cookie cunm=new Cookie("username",user);
response.addCookie(cunm);
response.sendRedirect("cookiee_loginview");
}
else
{
response.sendRedirect("cookiee_loginview");
}
}
finally
{
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
Event and Listener in Servlet
Events are basically occurrence of something. Changing the state of an object is
known as an event.
We can perform some important tasks at the occurrence of these exceptions,
such as counting total and current logged-in users, creating tables of the
database at time of deploying the project, creating database connection object
etc.
There are many Event classes and Listener interfaces in the javax.servlet and
javax.servlet.http packages.
Event classes
The event classes are as follows:
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent
What is filter? How it differs from servlet?
Filter is a Java class that is called for responding to the requests for resources,
such as Java Servlet and Java server pages (JSP). Filters dynamically change
behavior of a resource when a client requests a resource. Filters intercept and
process therequests beforethe requests are forwarded to the servlets, and process
the responses after the response has been generated by the server which means
filter does pre-processingand post-processing. Filters can also be put into a chain
where multiple filters can be invoked one after the other. A filter in a chain can
either transfer the controlto the next filter or redirect the request out of the chain
to retrieve the requested resource.
A servlet besides fulfilling its primary objectives that is to accept request and
send responses to clients has to also implement additional functionalities. The
additional functionalities may include
 security verification
 session validation
 login operations
 data compression
 encryption
 file formatting
 MIME type changing
Example:
Example of authenticating user using filter
Let's see the simple example of authenticating user using filter.
Here, we have created 4 files:
 index.html
 MyFilter.java
 AdminServlet.java
 web.xml
index.html
1. <form action="servlet1">
2. Name:<input type="text" name="name"/><br/>
3. Password:<input type="password" name="password"/><br/>
4.
5. <input type="submit" value="login">
6.
7. </form>
MyFilter.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.*;
4.
5. public class MyFilter implements Filter{
6.
7. public void init(FilterConfig arg0) throws ServletException {}
8.
9. public void doFilter(ServletRequest req, ServletResponse resp,
10. FilterChain chain) throws IOException, ServletException {
11.
12. PrintWriter out=resp.getWriter();
13.
14. String password=req.getParameter("password");
15. if(password.equals("admin")){
16. chain.doFilter(req, resp);//sends request to next resource
17. }
18. else{
19. out.print("username or password error!");
20. RequestDispatcher rd=req.getRequestDispatcher("index.html");
21. rd.include(req, resp);
22. }
23.
24.}
25. public void destroy() {}
26.
27.}
AdminServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.ServletException;
5. import javax.servlet.http.*;
6.
7. public class AdminServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. out.print("welcome ADMIN");
15. out.close();
16. }
17.}
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>AdminServlet</servlet-name>
4. <servlet-class>AdminServlet</servlet-class>
5. </servlet>
6.
7. <servlet-mapping>
8. <servlet-name>AdminServlet</servlet-name>
9. <url-pattern>/servlet1</url-pattern>
10. </servlet-mapping>
11.
12. <filter>
13. <filter-name>f1</filter-name>
14. <filter-class>MyFilter</filter-class>
15. </filter>
16. <filter-mapping>
17. <filter-name>f1</filter-name>
18. <url-pattern>/servlet1</url-pattern>
19. </filter-mapping>
20.
21.</web-app>
Example of counting number of visitors for a single page
MyFilter.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class MyFilter implements Filter{
5. static int count=0;
6. public void init(FilterConfig arg0) throws ServletException {}
7.
8. public void doFilter(ServletRequest req, ServletResponse res,
9. FilterChain chain) throws IOException, ServletException {
10.
11. PrintWriter out=res.getWriter();
12. chain.doFilter(request,response);
13.
14. out.print("<br/>Total visitors "+(++count));
15. out.close();
16.
17. }
18. public void destroy() {}
19.}
Explain filter lifecycle.
A filter can be created in an application by implementing javax.servlet.Filter. Filter
Life Cycle includes three methods as follows:ssss
init() method:
Refers to the method that is invoked by the web container only once when the filter
is initialized. The servlet container passes the FilterConfig object as a parameter
through the init() method.
Syntax:
Public void init(FilterConfig config) throws ServletException
Initializes filter and places it into service.A filter cannot be placed into service by
the web container if either a ServletException is thrown by init() method or the
method is not invoked within the time period specified by the web container.
doFilter()method:
Refers to the method that is invoked each time a user request a resource, such as a
servlet to which the filter is mapped. When the doFilter() method is invoked,the
servlet container passes theServletRequest,servletResponseand FilterChain objects.
The FilterChain object is passed to control the next object, if any.
Syntax:
Public void doFilter (ServletRequest req,ServletResponse res,FilterChain chain)
throws ServletException,IoException
Filter a request/response pair,whenever pair is passed to filter chain.The method
takes instance of FilterChain interface as an argument, which helps the filter to
forward the request and response to the next filter in the chain.The doFilter method
encapsulates the actual login of the filte.r
destroy() method:
Refers to the method that is invoked when filter instance is destroyed.
Syntax:
Public void destroy()
Removes the filter instance indicating that the filter is being moved out of the
service.This method is invoked only once for all threads within the doFilter()
method. The destroy method enables the filter to give up any resources being
held,such as memory, file handlers or thread.
What is servlet filters? Give the necessary API for filters and
explain their use.
 A filter is an object that performs filtering tasks either on the request to a
resource, or on the responsefrom a resource, or both.
 Filters are used for several purposewhich could be:
o Authentication filters.
o Logging and auditing filters.
o Data compressionfilters.
o Encryption filters.
o Tokenizing Filters.
o Filters that trigger resourceaccess events.
 When encapsulating common functionality in a filter, the same filter can
easily be used with several servlets.
The necessaryAPI for filters :
 The Filter API consists of three interfaces:
1. javax.servlet.Filter
2. javax.servlet.FilterChain
3. javax.servlet.FilterConfig
1) javax.servlet.Filter :
To create a filter class you must implements the javax.servlet.Filter interface
to the class and implement codes forall the above methods.
Methods in javax.servlet.Filter interface:
 public void init(FilterConfig filterConfig) :
Called by the web container to indicate to a filter that it is being placed into
service.
 public void doFilter(ServletRequestrequest, ServletResponseresponse,
FilterChain chain) :
The doFilter() method is called by the container each time a request/response
pair is passed through the chain due to a client request for a resource at the end
of the chain.
 public void destroy() :
Called by the web container to indicate to a filter that it is being taken out of
service.
2) javax.servlet.FilterChain :
The javax.servlet.FilterChain interface is an argument to the doFilter()
method. This interface has only one method, doFilter(), which are used by the
programnmer to causes the next filter in the chain to be invoked.
Methods in javax.servlet.FilterChain :
 public void doFilter(ServletRequestrequest, ServletResponseresponse)
:
Causes the next filter in the chain to be invoked, or if the calling filter, is the
last filter in the chain, causes the resource at the end of the chain to be invoked.
3) javax.servlet.FilterConfig :
The javax.servlet.FilterConfig interface is an argument to the init() method.
The Container gives us through this interface some information about initial
parameters and access to the ServletContext as well.
Methods in javax.servlet.FilterConfig interface:
 public String getFilterName() :
Returns the filter-name of this filter as defined in the deployment descriptor.
 public ServletContextgetServletContext() :
Returns a reference to the ServletContext in which the caller is executing.
 public String getInitParameter(String name) :
Returns a String containing the value of the named initialization parameter,
or null if the parameter does not exist.
 public Enumeration getInitParameterNames() :
Returns the names of the filter's initialization parameters as an Enumeration
of String objects, or an empty Enumeration if the filter has no initialization
parameters.

Mais conteúdo relacionado

Mais procurados (20)

JNDI
JNDIJNDI
JNDI
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Servlets
ServletsServlets
Servlets
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Express JS Rest API Tutorial
Express JS Rest API TutorialExpress JS Rest API Tutorial
Express JS Rest API Tutorial
 
Jsp
JspJsp
Jsp
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Express js
Express jsExpress js
Express js
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Implicit object.pptx
Implicit object.pptxImplicit object.pptx
Implicit object.pptx
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 

Destaque

Destaque (12)

Java servlets
Java servletsJava servlets
Java servlets
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Servlets
ServletsServlets
Servlets
 
Servlet
ServletServlet
Servlet
 
Servlets
ServletsServlets
Servlets
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Servlet and jsp interview questions
Servlet and jsp interview questionsServlet and jsp interview questions
Servlet and jsp interview questions
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
Apache ppt
Apache pptApache ppt
Apache ppt
 
Apache Presentation
Apache PresentationApache Presentation
Apache Presentation
 
Apache Ppt
Apache PptApache Ppt
Apache Ppt
 
Apache web server
Apache web serverApache web server
Apache web server
 

Semelhante a GTU SYLLABUS SERVLET COURSE MATERIAL

Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesbharathiv53
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Servlet viva questions
Servlet viva questionsServlet viva questions
Servlet viva questionsVipul Naik
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIPRIYADARSINISK
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2PawanMM
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jspAnkit Minocha
 

Semelhante a GTU SYLLABUS SERVLET COURSE MATERIAL (20)

Java servlets
Java servletsJava servlets
Java servlets
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Servlets
ServletsServlets
Servlets
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Servlet viva questions
Servlet viva questionsServlet viva questions
Servlet viva questions
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
gayathri.pptx
gayathri.pptxgayathri.pptx
gayathri.pptx
 
Session 26 - Servlets Part 2
Session 26 - Servlets Part 2Session 26 - Servlets Part 2
Session 26 - Servlets Part 2
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Servlet basics
Servlet basicsServlet basics
Servlet basics
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 

Último

TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...Amil Baba Dawood bangali
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Steel Structures - Building technology.pptx
Steel Structures - Building technology.pptxSteel Structures - Building technology.pptx
Steel Structures - Building technology.pptxNikhil Raut
 

Último (20)

TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Steel Structures - Building technology.pptx
Steel Structures - Building technology.pptxSteel Structures - Building technology.pptx
Steel Structures - Building technology.pptx
 

GTU SYLLABUS SERVLET COURSE MATERIAL

  • 1. GTU SYLLABUS COURSE MATERIAL SERVLET Definition :- Servlets are Java classes that extend the functionality of a Web server by dynamically generating Web pages. A run-time environment known as a servlet engine manages servlet loading and unloading, and works with the Web server to direct requests to servlets and to send output back to Web clients. Servlettechnology is robustand scalable as it uses the java language. Before Servlet, CGI (Common Gateway Interface) scripting language was used as a server-side programming language. But there were many disadvantages of this technology. Servlet can be described in many ways, depending on the context.  Servlet is a technology i.e. used to create web application.  Servlet is an API that provides many interfaces and classes including documentations.  Servlet is an interface that must be implemented for creating any servlet.  Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.  Servlet is a web component that is deployed on the server to create dynamic web page. Advantage of Servlet :- The basic benefits of servlet are as follows: 1. better performance: because it creates a thread for each request not process. 2. Portability: because it uses java language. 3. Robust: Servlets are managed by JVM so no need to worry about memory leak, garbage collection etc. 4. Secure: because it uses java language.. 5. Simplicity: Client-side Java applet runs in a virtual machine provided by Web Browser. So, various compatibility issues that increase complexity and
  • 2. also it limits the functionality. Servlets simplify this situation considerably because they run in a virtual machine in a controlled server environment and require only basic HTTP to communicate with their clients. No special client software is required, even with older browsers. 6. HTTP Sessions: Although HTTP servers have no built-in capability to remember details of a previous request from the same client, the Servlet API provides an HttpSession class that overcomes this limitation. 7. Access to Java Technology: Servlets, being Java applications, have direct access to the full range ofJava features, suchas threading, network access and database connectivity. 8. Servlets are persistance. What is the difference between Get and Post? There are many differences between the Get and Post request. Let's see these differences: GET POST 1) In case of Get request, only limited amount of data can be sent because data is sent in header. In case of postrequest, large amount of data can be sent because data is sent in body. 2) Get request is not securedbecause data is exposed in URL bar. Postrequest is securedbecausedata is not exposed in URL bar. 3) Get request can be bookmarked Postrequest cannot be bookmarked 4) Get request is idempotent. It means second request will be ignored until responseof first request is delivered. Postrequest is non-idempotent 5) Get request is more efficient and used more than Post Postrequest is less efficient and used less than get.
  • 3. Servlet Applets 1)subclass of GenericServlet 2)Runs in a server 3)must be multi threaded or thread per applet 4)no direct user interface interface 1)subclass of Applet 2)Runs in a browser 3)generally single thread safe 4)uses AWT for user Method summary of servlet class :- public void init(ServletConfig config) public void service(ServletRequest request,ServletResponse response) public void destroy() public ServletConfig getServletConfig() public String getServletInfo() public string getInitParameter(string pname) public ServletContext getServletContext() Methods of HTTP servlet class:- public void service(ServletRequest req,ServletResponse res) protected void service(HttpServletRequest req, HttpServletResponse res) protected void doGet(HttpServletRequest req, HttpServletResponse res)
  • 4. protected void doPost(HttpServletRequest req, HttpServletResponse res) protected void doHead(HttpServletRequest req, HttpServletResponse res) protected void doOptions(HttpServletRequest req, HttpServletResponse res) protected void doPut(HttpServletRequest req, HttpServletResponse res) protected void doTrace(HttpServletRequest req, HttpServletResponse res) protected void doDelete(HttpServletRequest req, HttpServletResponse res) Servlet Life Cycle:- servlets operate in the context of a request and responsemodel managed by a servlet engine.. The engine does the following: class is loaded. instance is created. method is invoked. method is invoked. method is invoked. init(): When a request is received by the servlet engine, it checks to see if the servlet is already loaded. If not, servlet engine calls an initialization method with the following signature: public void init(ServletConfig config) throws ServletException The ServletConfig object provides access to the servlet context and to any initialization parameters coded for the servlet init() method, the servlet can perform any necessary startup tasks, such as establishing database connections. If any errors occurthat make the servlet unable to handle requests, it should throw an UnavailableException.
  • 5. service(): After the init() method completes successfully, the servlet is able to accept requests. By default, only a single instance ofthe servlet is created, and the servlet engine dispatches each request to the instance in a separate thread. The servlet method that’s called has the following signature: public void service(ServletRequest request,ServletResponse response) throws ServletException, IOException The ServletRequest object is constructed by the servlet engine and acts as a wrapper for information about the client and the request.The ServletResponse object provides the means for a servlet to communicate its results back to the original requester. The General service() method is rarely used , because The most servlets are designed to operate in the HTTP environment, for which there’s a specialized javax.servlet.http package, most servlets extend its subclass
  • 6. javax.servlet.http.HttpServlet. This subclass provides specialized methods corresponding to each HTTP request method: GET requests are handled by doGet(),POST requests by doPost(), and so on. public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException destroy(): The servlet specification allows a servlet engine to unload a servlet at any time. used to conservesystem resources or in preparation for servlet engine shutdown. The servlet engine notifies each loaded servlet that this is about to happen by calling its destroy() method. By overriding destroy(), you can release any resources allocated during init(). public void destroy()
  • 7. Compare Generic Servlet with Http Servlet? GenericServlet HttpServlet 1) defines a generic, protocol independent servlet. 2) GenericServlet is an abstractclass it can handle all types of protocols 3)In generic we use only service method. 4)GenericServlet gives a blueprint and makes writing servlet easier. 1)HttpServlet defines a HTTP protocol specific servlet. 2)HttpServlet can handle only Http specific protocols. 3) Http we use doGet()& doPost()bcznow a days we useonly http WWW depends up on Http protocols. 4) HttpServlet gives a blueprint for Http servlet and makes writing them easier.
  • 8. Compare ServletContext and ServletConfig.. Servlet Context Servlet Config 1)ServletContext object has global behaviour. 2)There is only one servlet context object for context(project). 3) we can access servlet config from context. 4)All methods of servlet config are not applicable to servlet context. 1)Servlet Config is private for Servlet & jsp component. 2)There is only one Servletconfig for Servlet and jsp component.. 3)We can’t access servlet context from servlet config 4) All methods of servlet context are applicable to servlet config but only the scope bounds. Difference betweenforward() and sendRedirect()method There are many differences between the forward() method of RequestDispatcher and sendRedirect() method of HttpServletResponse interface. They are given below: Forward() SendRedirect() The forward() method works at server side. The sendRedirect() method works at client side. It sends the same request and response objects to another servlet. It always sends a new request. It can work within the server only. It can be used within and outside the server Example: request.getRequestDispacher("servlet2").for ward(request,response); Example: response.sendRedirect("servlet2");
  • 9. Methods of ServletConfig interface 1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name. 2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names. 3. public String getServletName():Returns the name of the servlet. 4. public ServletContext getServletContext():Returns an object of ServletContext. Commonly used methods of ServletContextinterface There is given some commonly used methods of ServletContext interface. 1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name. 2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters. 3. public void setAttribute(String name,Object object):sets the given object in the application scope. 4. public Object getAttribute(String name):Returns the attribute for the specified name. 5. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects. 6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.
  • 10. What is Session? How can you handle session with cookie? Discuss the scenario with sample code. Because the Web server doesn’t remember clients from one request to the next, the only way to maintain a session is for clients to keep track of it. You can accomplish this in two basic ways:  Have the client remember all session-related data and send it back to the server as needed.  Have the server maintain all the data, assign an identifier to it, and have the client remember the identifier. The first approachis simple to implement and requires no special capabilities on the part of the server. This approachcan entail transmitting large amounts of data back and forth, however, which might degrade performance. Another problem is server-side objects, suchas databaseand network connections have to be reinitialized with every request. For these reasons, this approachis best suited for long-term persistence of small amounts of data, such as user preferences or account numbers. The second approach offers more functionality. Once a server initiates a session and the client accepts it, the server can build complex, active objects and maintain large amounts of data, requiring only a key to distinguish between sessions. Four techniques are commonly used to maintain session:  Hidden fields  URL rewriting  Cookies  The HTTP session API Cookies: The most widely used technique for persistent client data storage involves HTTP cookies. A cookie is a small, named data elementthe server passes to a client witha Set-Cookie header as part of the HTTP response. The client is expected to store the cookie and return it to the server with a Cookie header
  • 11. on subsequent requests to the same server. Along with the name and value, the cookie may contain  An expiration date  A domain name  A path name  A secure attribute 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.
  • 12. Working: First, the Web browser requests a page from the Web server. No cookies are involved at this point. When the server responds with the requested document, it sends a Set-Cookie header assigning the value fr to a cookie named language. The cookie is set to expire in one year. The browser reads this header, extracts the cookie information, and stores the name/value pair in its cookie cache, along with the Web server’s domain and default path. Later, when the user visits the page again, the browser recognizes it previously received a cookie from this server and the cookie hasn’t yet expired, and, therefore, sends the cookie back to the server. Advantages: One advantage of cookies over other persistence schemes is they can retain their values after the browser sessionis over, even after the client computer is rebooted. This makes cookies well suited for maintaining users’ preferences, such as language. Disadvantages: One of the drawbacks of using cookies is that cookies are not fully supported by some browsers and the most browsers limit the amount of data that can be stored with a cookie.
  • 13. Cookies are stored on client side. So it can be easily disabled. So, secured data can’t be stored into cookie. Example1: index.html 1. <form action="servlet1" method="post"> 2. Name:<input type="text" name="userName"/><br/> 3. <input type="submit" value="go"/> 4. </form> FirstServlet.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. 5. 6. public class FirstServlet extends HttpServlet { 7. 8. public void doPost(HttpServletRequest request, HttpServletResponse response){ 9. try{ 10. 11. response.setContentType("text/html"); 12. PrintWriter out = response.getWriter(); 13. 14. String n=request.getParameter("userName"); 15. out.print("Welcome "+n); 16. 17. Cookie ck=new Cookie("uname",n);//creating cookie object 18. response.addCookie(ck);//adding cookie in the response 19.
  • 14. 20. //creating submit button 21. out.print("<form action='servlet2'>"); 22. out.print("<input type='submit' value='go'>"); 23. out.print("</form>"); 24. 25. out.close(); 26. 27. }catch(Exception e){System.out.println(e);} 28. } 29.} SecondServlet.java 1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*; 4. 5. public class SecondServlet extends HttpServlet { 6. 7. public void doPost(HttpServletRequest request, HttpServletResponse response){ 8. try{ 9. 10. response.setContentType("text/html"); 11. PrintWriter out = response.getWriter(); 12. 13. Cookie ck[]=request.getCookies(); 14. out.print("Hello "+ck[0].getValue()); 15. 16. out.close(); 17. 18. }catch(Exception e){System.out.println(e);} 19. } 20. 21. 22.}
  • 15. web.xml 1. <web-app> 2. 3. <servlet> 4. <servlet-name>s1</servlet-name> 5. <servlet-class>FirstServlet</servlet-class> 6. </servlet> 7. 8. <servlet-mapping> 9. <servlet-name>s1</servlet-name> 10.<url-pattern>/servlet1</url-pattern> 11.</servlet-mapping> 12. 13.<servlet> 14.<servlet-name>s2</servlet-name> 15.<servlet-class>SecondServlet</servlet-class> 16.</servlet> 17. 18.<servlet-mapping> 19.<servlet-name>s2</servlet-name> 20.<url-pattern>/servlet2</url-pattern> 21.</servlet-mapping> 22. 23.</web-app> Output :-
  • 16. Example2: //Cookiee_loginview.java import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; public class cookiee_loginview extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); ServletContext con=getServletContext(); try { out.println("<html>"); out.println("<body>"); out.println("<form action='cokiee'> " + "UserName : <input type='text' name='unm'><br><br>" + "<input type='submit' value='submit'>" + "<input type='reset' value='reset'> " + "</form>"); String m=con.getAttribute("msg").toString(); if(m!=null) { Cookie[] coki=request.getCookies(); Cookie ck=coki[0]; if(ck.getValue()!=null)
  • 17. { out.println("Sucessfully logged in"); } } else { out.println("Please Try again"); } out.println("</body>"); out.println("</html>"); } finally { out.close(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } //Cokiee.java import java.io.*;
  • 18. import java.net.*; import javax.servlet.*; import javax.servlet.http.*; public class cokiee extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); ServletContext con=getServletContext(); try { String user=request.getParameter("unm"); con.setAttribute("msg","true"); if(user.equals("admin")) { Cookie cunm=new Cookie("username",user); response.addCookie(cunm); response.sendRedirect("cookiee_loginview"); } else { response.sendRedirect("cookiee_loginview"); } } finally { out.close(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  • 19. processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } Event and Listener in Servlet Events are basically occurrence of something. Changing the state of an object is known as an event. We can perform some important tasks at the occurrence of these exceptions, such as counting total and current logged-in users, creating tables of the database at time of deploying the project, creating database connection object etc. There are many Event classes and Listener interfaces in the javax.servlet and javax.servlet.http packages. Event classes The event classes are as follows: 1. ServletRequestEvent 2. ServletContextEvent 3. ServletRequestAttributeEvent 4. ServletContextAttributeEvent 5. HttpSessionEvent 6. HttpSessionBindingEvent
  • 20. What is filter? How it differs from servlet? Filter is a Java class that is called for responding to the requests for resources, such as Java Servlet and Java server pages (JSP). Filters dynamically change behavior of a resource when a client requests a resource. Filters intercept and process therequests beforethe requests are forwarded to the servlets, and process the responses after the response has been generated by the server which means filter does pre-processingand post-processing. Filters can also be put into a chain where multiple filters can be invoked one after the other. A filter in a chain can either transfer the controlto the next filter or redirect the request out of the chain to retrieve the requested resource. A servlet besides fulfilling its primary objectives that is to accept request and send responses to clients has to also implement additional functionalities. The additional functionalities may include  security verification  session validation  login operations  data compression  encryption  file formatting  MIME type changing Example: Example of authenticating user using filter Let's see the simple example of authenticating user using filter. Here, we have created 4 files:  index.html  MyFilter.java  AdminServlet.java
  • 21.  web.xml index.html 1. <form action="servlet1"> 2. Name:<input type="text" name="name"/><br/> 3. Password:<input type="password" name="password"/><br/> 4. 5. <input type="submit" value="login"> 6. 7. </form> MyFilter.java 1. import java.io.IOException; 2. import java.io.PrintWriter; 3. import javax.servlet.*; 4. 5. public class MyFilter implements Filter{ 6. 7. public void init(FilterConfig arg0) throws ServletException {} 8. 9. public void doFilter(ServletRequest req, ServletResponse resp, 10. FilterChain chain) throws IOException, ServletException { 11. 12. PrintWriter out=resp.getWriter(); 13. 14. String password=req.getParameter("password"); 15. if(password.equals("admin")){ 16. chain.doFilter(req, resp);//sends request to next resource 17. } 18. else{ 19. out.print("username or password error!"); 20. RequestDispatcher rd=req.getRequestDispatcher("index.html"); 21. rd.include(req, resp); 22. } 23. 24.} 25. public void destroy() {} 26. 27.}
  • 22. AdminServlet.java 1. import java.io.IOException; 2. import java.io.PrintWriter; 3. 4. import javax.servlet.ServletException; 5. import javax.servlet.http.*; 6. 7. public class AdminServlet extends HttpServlet { 8. public void doGet(HttpServletRequest request, HttpServletResponse response) 9. throws ServletException, IOException { 10. 11. response.setContentType("text/html"); 12. PrintWriter out = response.getWriter(); 13. 14. out.print("welcome ADMIN"); 15. out.close(); 16. } 17.} web.xml 1. <web-app> 2. <servlet> 3. <servlet-name>AdminServlet</servlet-name> 4. <servlet-class>AdminServlet</servlet-class> 5. </servlet> 6. 7. <servlet-mapping> 8. <servlet-name>AdminServlet</servlet-name> 9. <url-pattern>/servlet1</url-pattern> 10. </servlet-mapping> 11. 12. <filter> 13. <filter-name>f1</filter-name> 14. <filter-class>MyFilter</filter-class> 15. </filter> 16. <filter-mapping>
  • 23. 17. <filter-name>f1</filter-name> 18. <url-pattern>/servlet1</url-pattern> 19. </filter-mapping> 20. 21.</web-app> Example of counting number of visitors for a single page MyFilter.java 1. import java.io.*; 2. import javax.servlet.*; 3. 4. public class MyFilter implements Filter{ 5. static int count=0; 6. public void init(FilterConfig arg0) throws ServletException {} 7. 8. public void doFilter(ServletRequest req, ServletResponse res, 9. FilterChain chain) throws IOException, ServletException { 10. 11. PrintWriter out=res.getWriter(); 12. chain.doFilter(request,response); 13. 14. out.print("<br/>Total visitors "+(++count)); 15. out.close(); 16. 17. } 18. public void destroy() {} 19.} Explain filter lifecycle. A filter can be created in an application by implementing javax.servlet.Filter. Filter Life Cycle includes three methods as follows:ssss
  • 24. init() method: Refers to the method that is invoked by the web container only once when the filter is initialized. The servlet container passes the FilterConfig object as a parameter through the init() method. Syntax: Public void init(FilterConfig config) throws ServletException Initializes filter and places it into service.A filter cannot be placed into service by the web container if either a ServletException is thrown by init() method or the method is not invoked within the time period specified by the web container. doFilter()method: Refers to the method that is invoked each time a user request a resource, such as a servlet to which the filter is mapped. When the doFilter() method is invoked,the servlet container passes theServletRequest,servletResponseand FilterChain objects. The FilterChain object is passed to control the next object, if any. Syntax: Public void doFilter (ServletRequest req,ServletResponse res,FilterChain chain) throws ServletException,IoException Filter a request/response pair,whenever pair is passed to filter chain.The method takes instance of FilterChain interface as an argument, which helps the filter to forward the request and response to the next filter in the chain.The doFilter method encapsulates the actual login of the filte.r destroy() method: Refers to the method that is invoked when filter instance is destroyed. Syntax: Public void destroy() Removes the filter instance indicating that the filter is being moved out of the service.This method is invoked only once for all threads within the doFilter() method. The destroy method enables the filter to give up any resources being held,such as memory, file handlers or thread.
  • 25. What is servlet filters? Give the necessary API for filters and explain their use.  A filter is an object that performs filtering tasks either on the request to a resource, or on the responsefrom a resource, or both.  Filters are used for several purposewhich could be: o Authentication filters. o Logging and auditing filters. o Data compressionfilters. o Encryption filters. o Tokenizing Filters. o Filters that trigger resourceaccess events.  When encapsulating common functionality in a filter, the same filter can easily be used with several servlets. The necessaryAPI for filters :  The Filter API consists of three interfaces: 1. javax.servlet.Filter 2. javax.servlet.FilterChain 3. javax.servlet.FilterConfig 1) javax.servlet.Filter : To create a filter class you must implements the javax.servlet.Filter interface to the class and implement codes forall the above methods. Methods in javax.servlet.Filter interface:  public void init(FilterConfig filterConfig) :
  • 26. Called by the web container to indicate to a filter that it is being placed into service.  public void doFilter(ServletRequestrequest, ServletResponseresponse, FilterChain chain) : The doFilter() method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.  public void destroy() : Called by the web container to indicate to a filter that it is being taken out of service. 2) javax.servlet.FilterChain : The javax.servlet.FilterChain interface is an argument to the doFilter() method. This interface has only one method, doFilter(), which are used by the programnmer to causes the next filter in the chain to be invoked. Methods in javax.servlet.FilterChain :  public void doFilter(ServletRequestrequest, ServletResponseresponse) : Causes the next filter in the chain to be invoked, or if the calling filter, is the last filter in the chain, causes the resource at the end of the chain to be invoked. 3) javax.servlet.FilterConfig : The javax.servlet.FilterConfig interface is an argument to the init() method. The Container gives us through this interface some information about initial parameters and access to the ServletContext as well. Methods in javax.servlet.FilterConfig interface:  public String getFilterName() :
  • 27. Returns the filter-name of this filter as defined in the deployment descriptor.  public ServletContextgetServletContext() : Returns a reference to the ServletContext in which the caller is executing.  public String getInitParameter(String name) : Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.  public Enumeration getInitParameterNames() : Returns the names of the filter's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the filter has no initialization parameters.