Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

GenericServlet Class

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

GenericServlet class

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides


the implementation of all the methods of these interfaces except the service method.

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

You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.

Methods of GenericServlet class

There are many methods in GenericServlet class. They are as follows:

1. public void init(ServletConfig config) is used to initialize the servlet.


2. public void destroy() is invoked only once throughout the life cycle and indicates that
servlet is being destroyed.
3. public void init() it is a convenient method for the servlet programmers, now there is no
need to call super.init(config)

Servlet Example by inheriting the GenericServlet class

Let's see the simple example of servlet by inheriting the GenericServlet class.

It will be better if you learn it after visiting steps to create a servlet.

File: First.java

1. import java.io.*;  
2. import javax.servlet.*;  
3.   
4. public class First extends GenericServlet{  
5. public void service(ServletRequest req,ServletResponse res)  
6. throws IOException,ServletException{  
7.   
8. res.setContentType("text/html");  
9.   
10. PrintWriter out=res.getWriter();  
11. out.print("<html><body>");  
12. out.print("<b>hello generic servlet</b>");  
13. out.print("</body></html>");  
14.   
15. }  
16. }  

HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It
provides http specific methods such as doGet, doPost, doHead, doTrace etc.

Methods of HttpServlet class

There are many methods in HttpServlet class. They are as follows:

1. public void service(ServletRequest req,ServletResponse res) dispatches the request to


the protected service method by converting the request and response object into http
type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the
request from the service method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the
GET request. It is invoked by the web container.

ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a servlet such as
content type, content length, parameter names and values, header informations, attributes etc.

Methods of ServletRequest interface

There are many methods defined in the ServletRequest interface. Some of them are as follows:

Method Description

public String getParameter(String is used to obtain the value of a parameter by name.


name)

public String[] returns an array of String containing all values of given parameter name. It
getParameterValues(String name) is mainly used to obtain values of a Multi select list box.

java.util.Enumeration returns an enumeration of all of the request parameter names.


getParameterNames()

public int getContentLength() Returns the size of the request entity data, or -1 if not known.

Example of ServletRequest to display the name of the user

In this example, we are displaying the name of the user in the servlet. For this purpose, we have
used the getParameter method that returns the value for the given request parameter name.

index.html
1. <form action="welcome" method="get">  
2. Enter your name<input type="text" name="name"><br>  
3. <input type="submit" value="login">  
4. </form>  

DemoServ.java

1. import javax.servlet.http.*;  
2. import javax.servlet.*;  
3. import java.io.*;  
4. public class DemoServ extends HttpServlet{  
5. public void doGet(HttpServletRequest req,HttpServletResponse res)  
6. throws ServletException,IOException  
7. {  
8. res.setContentType("text/html");  
9. PrintWriter pw=res.getWriter();  
10.   
11. String name=req.getParameter("name");//will return value  
12. pw.println("Welcome "+name);  
13.   
14. pw.close();  
15. }}  

Servlet – Response
A servlet can use this object to help it provide a response to the client. A ServletResponse object is
created by the servlet container and passed as an argument to the servlet’s service function.
Some Important Methods of ServletResponse

Methods Description

String It returns the name of the MIME


getCharacterEncoding() charset that was used in the body of
the client response.

String getContentType() It returns the response content type.


e.g. text, HTML etc.

 ServletOutputStream This method returns a


getOutputStream() ServletOutputStream that may be used
to write binary data to the response.

PrintWriter getWriter() The PrintWriter object is used to


transmit character text to the client.

Implementation: The setContentType() and getWriter() methods of the ServletResponse interface


were utilised in the example below.

A. File: index.html

HTML
<html>

<body>

<title> GEEKSFORGEEKS </title>

<form action="GFG" method="get">

 Enter your username:

<br><br>

<input type="text" name="uname">

<br><br>

<input type="submit" value="login">

</form>

</body>

</html>

B. Application File (GFG.java)

Java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class GFG extends HttpServlet{

   public void doGet(HttpServletRequest req,HttpServletResponse res)

   throws ServletException,IOException

   {

     res.setContentType("text/html");

     PrintWriter pwriter=res.getWriter();

     String name=req.getParameter("uname");
     pwriter.println("This is user details page:");

     pwriter.println("Hello "+name);

     pwriter.close();

  }

ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet. This object can be used
to get configuration information from web.xml file.

If the configuration information is modified from the web.xml file, we don't need to change the
servlet. So it is easier to manage the web application if any specific content is modified from time
to time.

Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if information is
modified from the web.xml file.

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.

How to get the object of ServletConfig

1. getServletConfig() method of Servlet interface returns the object of ServletConfig.

Syntax of getServletConfig() method

1. public ServletConfig getServletConfig();  

Example of getServletConfig() method


1. ServletConfig config=getServletConfig();  
2. //Now we can call the methods of ServletConfig interface  

Syntax to provide the initialization parameter for a servlet

The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.

1. <web-app>  
2.   <servlet>  
3.     ......  
4.       
5.     <init-param>  
6.       <param-name>parametername</param-name>  
7.       <param-value>parametervalue</param-value>  
8.     </init-param>  
9.     ......  
10.   </servlet>  
11. </web-app>  

Example of ServletConfig to get initialization parameter

In this example, we are getting the one initialization parameter from the web.xml file and printing
this information in the servlet.

DemoServlet.java

1. import java.io.*;  
2. import javax.servlet.*;  
3. import javax.servlet.http.*;  
4.   
5. public class DemoServlet extends HttpServlet {  
6. public void doGet(HttpServletRequest request, HttpServletResponse response)  
7.     throws ServletException, IOException {  
8.   
9.     response.setContentType("text/html");  
10.     PrintWriter out = response.getWriter();  
11.       
12.     ServletConfig config=getServletConfig();  
13.     String driver=config.getInitParameter("driver");  
14.     out.print("Driver is: "+driver);  
15.           
16.     out.close();  
17.     }  
18.   
19. }  

What is servlet mapping?

Servlet mapping specifies the web container of which java servlet should be invoked for a
url given by client. It maps url patterns to servlets. When there is a request from a client,
servlet container decides to which application it should forward to. Then context path of
url is matched for mapping servlets.

Example code for java servlet mapping:

<servlet>
<servlet-name>milk</servlet-name>
<servlet-class>com.javapapers.Milk</servlet-class>
</servlet>
<servlet>
<servlet-name>points</servlet-name>
<servlet-class>com.javapapers.Points</servlet-class>
</servlet>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>com.javapapers.ControllerServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>points</servlet-name>
<url-pattern>/pointlist</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

JSP Tutorial

JSP technology is used to create web application just like Servlet technology. It can be thought of
as an extension to Servlet because it provides more functionality than servlet such as expression
language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet
because we can separate designing and development. It provides some additional features such as
Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation
logic. In Servlet technology, we mix our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page


The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator.
The JSP translator is a part of the web server which is responsible for translating the JSP page into
Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file.
Moreover, all the processes that happen in Servlet are performed on JSP later like initialization,
committing response to the browser and destroy.

The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB-
INF folder or in any directory.
JSP Declaration Tag
The JSP declaration tag is used to declare fields and methods.

The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.

So it doesn't get memory at each request.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

1. <%!  field or method declaration %>  

Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variables as well as
methods. methods.

The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is placed outside the
_jspService() method. _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.

index.jsp

1. <html>  
2. <body>  
3. <%! int data=50; %>  
4. <%= "Value of the variable is:"+data %>  
5. </body>  
6. </html>  

Example of JSP declaration tag that declares method

In this example of JSP declaration tag, we are defining the method which returns the cube of given
number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to
call the declared method.

index.jsp

1. <html>  
2. <body>  
3. <%!   
4. int cube(int n){  
5. return n*n*n*;  
6. }  
7. %>  
8. <%= "Cube of 3 is:"+cube(3) %>  
9. </body>  
10. </html>  

JSP directives
. JSP directives
. page directive
. Attributes of page directive

The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive

1. <%@ directive attribute="value" %>  

JSP page directive


The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

1. <%@ page attribute="value" %>  

Attributes of JSP page directive

o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage

1)import

The import attribute is used to import class,interface or all the members of a package.It is similar to import keyword in
java class or interface.

Example of import attribute

1. <html>  
2. <body>  
3.   
4. <%@ page import="java.util.Date" %>  
5. Today is: <%= new Date() %>  
6.   
7. </body>  
8. </html>  

2)contentType

The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute

1. <html>  
2. <body>  
3.   
4. <%@ page contentType=application/msword %>  
5. Today is: <%= new java.util.Date() %>  
6.   
7. </body>  
8. </html>  

3)extends

The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.

4)info

This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.

Example of info attribute

1. <html>  
2. <body>  
3.   
4. <%@ page info="composed by Sonoo Jaiswal" %>  
5. Today is: <%= new java.util.Date() %>  
6.   
7. </body>  
8. </html>  

The web container will create a method getServletInfo() in the resulting servlet.For example:

1. public String getServletInfo() {  
2.   return "composed by Sonoo Jaiswal";   
3. }  

5)buffer

The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.

Example of buffer attribute

1. <html>  
2. <body>  
3.   
4. <%@ page buffer="16kb" %>  
5. Today is: <%= new java.util.Date() %>  
6.   
7. </body>  
8. </html>  

6)language

The language attribute specifies the scripting language used in the JSP page. The default value is
"java".

7)isELIgnored

We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is false i.e. Expression
Language is enabled by default. We see Expression Language later.

1. <%@ page isELIgnored="true" %>//Now EL will be ignored  

8)isThreadSafe

Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use isThreadSafe
attribute of page directive.The value of isThreadSafe value is true.If you make it false, the web container will serialize the
multiple requests, i.e. it will wait until the JSP finishes responding to a request before passing another request to it.If you
make the value of isThreadSafe attribute like:

<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

1. public class SimplePage_jsp extends HttpJspBase   
2.   implements SingleThreadModel{  
3. .......  
4. }  

9)errorPage

The errorPage attribute is used to define the error page, if exception occurs in the current page, it
will be redirected to the error page.

Example of errorPage attribute

1. //index.jsp  
2. <html>  
3. <body>  
4.   
5. <%@ page errorPage="myerrorpage.jsp" %>  
6.   
7.  <%= 100/0 %>  
8.   
9. </body>  
10. </html>  

10)isErrorPage

The isErrorPage attribute is used to declare that the current page is the error page.

Note: The exception object can only be used in the error page.

Example of isErrorPage attribute

1. //myerrorpage.jsp  
2. <html>  
3. <body>  
4.   
5. <%@ page isErrorPage="true" %>  
6.   
7.  Sorry an exception occured!<br/>  
8. The exception is: <%= exception %>  
9.   
10. </body>  
11. </html>  

You might also like