Servlet

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. Servlet technology is robust and 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

Transcript of Servlet

Page 1: Servlet

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.

Servlet technology is robust and 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

Page 2: Servlet

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 of Java features, such as 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 post request, large amount of data can be sent because data is sent

in body.

2) Get request is not secured because data is exposed in URL bar.

Post request is secured because data is not exposed in URL bar.

3) Get request can be bookmarked Post request cannot be bookmarked

4) Get request is idempotent. It means second request will be ignored until

response of first request is delivered.

Post request is non-idempotent

5) Get request is more efficient and used more than Post

Post request is less efficient and used less than get.

Page 3: Servlet

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)

Page 4: Servlet

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 response model 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 occur that make the servlet unable to handle requests, it should throw

an UnavailableException.

Page 5: Servlet

service():

After the init() method completes successfully, the servlet is able to accept

requests. By default, only a single instance of the 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

Page 6: Servlet

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 conserve system 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()

Page 7: Servlet

Compare Generic Servlet with Http Servlet?

GenericServlet HttpServlet

1) defines a generic, protocol

independent servlet.

2) GenericServlet is an abstract class 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() bcz now

a days we use only http WWW depends up

on Http protocols.

4) HttpServlet gives a blueprint for Http

servlet and makes writing them easier.

Page 8: Servlet

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 between forward() 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");

Page 9: Servlet

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 ServletContext interface

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.

Page 10: Servlet

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 approach is simple to implement and requires no special capabilities

on the part of the server. This approach can entail transmitting large amounts

of data back and forth, however, which might degrade performance. Another

problem is server-side objects, such as database and network connections have

to be reinitialized with every request. For these reasons, this approach is 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 element the server passes to

a client with a 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

Page 11: Servlet

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.

Page 12: Servlet

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

Page 13: Servlet

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.

Page 14: Servlet

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

Page 15: Servlet

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

Page 16: Servlet

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)

Page 17: Servlet

{

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

Page 18: Servlet

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 {

Page 19: Servlet

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

Page 20: Servlet

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 the requests before the requests are forwarded to the servlets, and process

the responses after the response has been generated by the server which means

filter does pre-processing and 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 control to 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

Page 21: Servlet

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

Page 22: Servlet

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>

Page 23: Servlet

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

Page 24: Servlet

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 the ServletRequest,servletResponse and 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.

Page 25: Servlet

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 response from a resource, or both. Filters are used for several purpose which could be:

o Authentication filters. o Logging and auditing filters.

o Data compression filters. o Encryption filters.

o Tokenizing Filters. o Filters that trigger resource access events.

When encapsulating common functionality in a filter, the same filter can easily be used with several servlets.

The necessary API 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 for all the above methods.

Methods in javax.servlet.Filter interface:

public void init(FilterConfig filterConfig) :

Page 26: Servlet

Called by the web container to indicate to a filter that it is being placed into

service.

public void doFilter(ServletRequest request, ServletResponse response,

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(ServletRequest request, ServletResponse response)

:

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

Page 27: Servlet

Returns the filter-name of this filter as defined in the deployment descriptor.

public ServletContext getServletContext() :

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.