GenericServlet Class
GenericServlet Class
GenericServlet Class
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.
Let's see the simple example of servlet by inheriting the GenericServlet class.
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.
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.
There are many methods defined in the ServletRequest interface. Some of them are as follows:
Method Description
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.
public int getContentLength() Returns the size of the request entity data, or -1 if not known.
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
A. File: index.html
HTML
<html>
<body>
<br><br>
<br><br>
</form>
</body>
</html>
Java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
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.
1. public ServletConfig getServletConfig();
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>
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. }
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.
<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.
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.
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.
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.
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 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.
1. <%! field or method declaration %>
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.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
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.
o page directive
o include directive
o taglib directive
1. <%@ directive attribute="value" %>
1. <%@ page attribute="value" %>
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.
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".
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.
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.
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:
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.
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.
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>