JavaServlet Material2
JavaServlet Material2
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. <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>
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 respons
e)
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. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>DemoServlet</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6.
7. <init-param>
8. <param-name>driver</param-name>
9. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10. </init-param>
11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name>DemoServlet</servlet-name>
16. <url-pattern>/servlet1</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>
DemoServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import java.util.Enumeration;
4. import javax.servlet.ServletConfig;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9.
10.
11. public class DemoServlet extends HttpServlet {
12. public void doGet(HttpServletRequest request, HttpServletResponse respons
e)
13. throws ServletException, IOException {
14.
15. response.setContentType("text/html");
16. PrintWriter out = response.getWriter();
17.
18. ServletConfig config=getServletConfig();
19. Enumeration<String> e=config.getInitParameterNames();
20.
21. String str="";
22. while(e.hasMoreElements()){
23. str=e.nextElement();
24. out.print("<br>Name: "+str);
25. out.print(" value: "+config.getInitParameter(str));
26. }
27.
28. out.close();
29. }
30.
31. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>DemoServlet</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6.
7. <init-param>
8. <param-name>username</param-name>
9. <param-value>system</param-value>
10. </init-param>
11.
12. <init-param>
13. <param-name>password</param-name>
14. <param-value>oracle</param-value>
15. </init-param>
16.
17. </servlet>
18.
19. <servlet-mapping>
20. <servlet-name>DemoServlet</servlet-name>
21. <url-pattern>/servlet1</url-pattern>
22. </servlet-mapping>
23.
24. </web-app>
ServletContext Interface
An object of ServletContext is created by the web container at time of deploying the
project. This object can be used to get configuration information from web.xml file.
There is only one ServletContext object per web application.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make
it available for all the servlet. We provide this information from the web.xml file, so
if the information is changed, we don't need to modify the servlet. Thus it removes
maintenance problem.
3. The ServletContext object can be used to set, get or remove attribute from
the web.xml file.
initialization parameters.
application scope.
name.
parameter in the application scope. The param-name and param-value are the sub-elements
of the context-param. The param-name element defines parameter name and and
1. <web-app>
2. ......
3.
4. <context-param>
5. <param-name>parametername</param-name>
6. <param-value>parametervalue</param-value>
7. </context-param>
8. ......
9. </web-app>
Example of ServletContext to get the initialization
parameter
In this example, we are getting the initialization parameter from the web.xml file and
printing the value of the initialization parameter. Notice that the object of ServletContext
represents the application scope. So if we change the value of the parameter from the
web.xml file, all the servlet classes will get the changed value. So we don't need to modify
the servlet. So it is better to have the common information for most of the servlets in the
web.xml file by
DemoServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class DemoServlet extends HttpServlet{
7. public void doGet(HttpServletRequest req,HttpServletResponse res)
8. throws ServletException,IOException
9. {
10. res.setContentType("text/html");
11. PrintWriter pw=res.getWriter();
12.
13. //creating ServletContext object
14. ServletContext context=getServletContext();
15.
16. //Getting the value of the initialization parameter and printing it
17. String driverName=context.getInitParameter("dname");
18. pw.println("driver name is="+driverName);
19.
20. pw.close();
21.
22. }}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
11. </context-param>
12.
13. <servlet-mapping>
14. <servlet-name>sonoojaiswal</servlet-name>
15. <url-pattern>/context</url-pattern>
16. </servlet-mapping>
17.
18. </web-app>
For getting all the parameters, we have used the getInitParameterNames() method
DemoServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class DemoServlet extends HttpServlet{
7. public void doGet(HttpServletRequest req,HttpServletResponse res)
8. throws ServletException,IOException
9. {
10. res.setContentType("text/html");
11. PrintWriter out=res.getWriter();
12.
13. ServletContext context=getServletContext();
14. Enumeration<String> e=context.getInitParameterNames();
15.
16. String str="";
17. while(e.hasMoreElements()){
18. str=e.nextElement();
19. out.print("<br> "+context.getInitParameter(str));
20. }
21. }}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
11. </context-param>
12.
13. <context-param>
14. <param-name>username</param-name>
15. <param-value>system</param-value>
16. </context-param>
17.
18. <context-param>
19. <param-name>password</param-name>
20. <param-value>oracle</param-value>
21. </context-param>
22.
23. <servlet-mapping>
24. <servlet-name>sonoo jaiswal</servlet-name>
25. <url-pattern>/context</url-pattern>
26. </servlet-mapping>
27.
28. </web-app>
Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from one of the
following scopes:
1. request scope
2. session scope
3. application scope
The servlet programmer can pass information from one servlet to another using
attributes. It is just like passing object from one class to another so that we can
reuse the same object again and again.
specified name.
Servlet Filter
1.Filter
2.Usage of Filter
3.Advantage of Filter
4.Filter API
1.Filter interface
2.FilterChain interface
3.FilterConfig interface
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed automatically
and we don't need to change the servlet.
Note: Unlike Servlet, One filter doesn't have dependency on another filter.
Usage of Filter
o recording all incoming requests
o logs the IP addresses of the computers from which the requests originate
o conversion
o data compression
3. Less Maintenance
Filter API
Like servlet filter have its own API. The javax.servlet package contains the three
interfaces of Filter API.
1. Filter
2. FilterChain
3. FilterConfig
1) Filter interface
For creating any filter, you must implement the Filter interface. Filter interface
provides the life cycle methods for a filter.
Method Description
public void init(FilterConfig config) init() method is invoked only once. It is used
filtering tasks.
2) FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the
chain.This object is passed in the doFilter method of Filter interface.The FilterChain
interface contains only one method:
1. public void doFilter(HttpServletRequest request, HttpServletResponse
response): it passes the control to the next filter or resource.
1. <web-app>
2.
3. <filter>
4. <filter-name>...</filter-name>
5. <filter-class>...</filter-class>
6. </filter>
7.
8. <filter-mapping>
9. <filter-name>...</filter-name>
10. <url-pattern>...</url-pattern>
11. </filter-mapping>
12.
13. </web-app>
For mapping filter we can use, either url-pattern or servlet-name. The url-pattern
elements has an advantage over servlet-name element i.e. it can be applied on
servlet, JSP or HTML.
index.html
1. <a href="servlet1">click here</a>
MyFilter.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.*;
5.
6. public class MyFilter implements Filter{
7.
8. public void init(FilterConfig arg0) throws ServletException {}
9.
10. public void doFilter(ServletRequest req, ServletResponse resp,
11. FilterChain chain) throws IOException, ServletException {
12.
13. PrintWriter out=resp.getWriter();
14. out.print("filter is invoked before");
15.
16. chain.doFilter(req, resp);//sends request to next resource
17.
18. out.print("filter is invoked after");
19. }
20. public void destroy() {}
21. }
HelloServlet.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 HelloServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse resp
onse)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. out.print("<br>welcome to servlet<br>");
15.
16. }
17.
18. }
web.xml
For defining the filter, filter element of web-app must be defined just like servlet.
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>HelloServlet</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. <filter>
14. <filter-name>f1</filter-name>
15. <filter-class>MyFilter</filter-class>
16. </filter>
17.
18. <filter-mapping>
19. <filter-name>f1</filter-name>
20. <url-pattern>/servlet1</url-pattern>
21. </filter-mapping>
22.
23.
24. </web-app>
Authentication Filter
We can perform authentication in filter. Here, we are going to check to password
given by the user in filter class, if given password is admin, it will forward the
request to the WelcomeAdmin servlet otherwise it will display error message.
o index.html
o MyFilter.java
o AdminServlet.java
o 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 respons
e)
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>
FilterConfig
An object of FilterConfig is created by the web container. This object can be used to
get the configuration information from the web.xml file.
Example of FilterConfig
In this example, if you change the param-value to no, request will be forwarded to
the servlet otherwise filter will create the response with the message: this page is
underprocessing. Let's see the simple example of FilterConfig. Here, we have
created 4 files:
o index.html
o MyFilter.java
o HelloServlet.java
o web.xml
index.html
1. <a href="servlet1">click here</a>
MyFilter.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.*;
5.
6. public class MyFilter implements Filter{
7. FilterConfig config;
8.
9. public void init(FilterConfig config) throws ServletException {
10. this.config=config;
11. }
12.
13. public void doFilter(ServletRequest req, ServletResponse resp,
14. FilterChain chain) throws IOException, ServletException {
15.
16. PrintWriter out=resp.getWriter();
17.
18. String s=config.getInitParameter("construction");
19.
20. if(s.equals("yes")){
21. out.print("This page is under construction");
22. }
23. else{
24. chain.doFilter(req, resp);//sends request to next resource
25. }
26.
27. }
28. public void destroy() {}
29. }
HelloServlet.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 HelloServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse respons
e)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. out.print("<br>welcome to servlet<br>");
15.
16. }
17.
18. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>HelloServlet</servlet-name>
5. <servlet-class>HelloServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>HelloServlet</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <filter>
14. <filter-name>f1</filter-name>
15. <filter-class>MyFilter</filter-class>
16. <init-param>
17. <param-name>construction</param-name>
18. <param-value>no</param-value>
19. </init-param>
20. </filter>
21. <filter-mapping>
22. <filter-name>f1</filter-name>
23. <url-pattern>/servlet1</url-pattern>
24. </filter-mapping>
25.
26.
27. </web-app>
RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility of dispatching the request to
another resource it may be html, servlet or jsp. This interface can also be used to
include the content of another resource also. It is one of the way of servlet
collaboration.
As you can see in the above figure, response of second servlet is included in the
Login.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class Login extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse respon
se)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. String p=request.getParameter("userPass");
16.
17. if(p.equals("servlet"){
18. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
19. rd.forward(request, response);
20. }
21. else{
22. out.print("Sorry UserName or Password Error!");
23. RequestDispatcher rd=request.getRequestDispatcher("/index.html");
24. rd.include(request, response);
25.
26. }
27. }
28.
29. }
WelcomeServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class WelcomeServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse resp
onse)
8. throws ServletException, IOException {
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. String n=request.getParameter("userName");
14. out.print("Welcome "+n);
15. }
16.
17. }
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>Login</servlet-name>
4. <servlet-class>Login</servlet-class>
5. </servlet>
6. <servlet>
7. <servlet-name>WelcomeServlet</servlet-name>
8. <servlet-class>WelcomeServlet</servlet-class>
9. </servlet>
10.
11.
12. <servlet-mapping>
13. <servlet-name>Login</servlet-name>
14. <url-pattern>/servlet1</url-pattern>
15. </servlet-mapping>
16. <servlet-mapping>
17. <servlet-name>WelcomeServlet</servlet-name>
18. <url-pattern>/servlet2</url-pattern>
19. </servlet-mapping>
20.
21. <welcome-file-list>
22. <welcome-file>index.html</welcome-file>
23. </welcome-file-list>
24. </web-app>
download this example
download this example (developed in Myeclipse IDE)
download this example (developed in eclipse IDE)
download this example (developed in netbeans IDE)
Servlets - Cookies Handling
Cookies are text files stored on the client computer and they are kept for various
information tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
• Server script sends a set of cookies to the browser. For example name, age,
or identification number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it sends those
cookies information to the server and server uses that information to identify
the user.
This chapter will teach you how to set or reset cookies, how to access them and how
to delete them.
out.println(docType +
"<html>\n" +
"<head>
<title>" + title + "</title>
</head>\n" +
Compile the above servlet HelloForm and create appropriate entry in web.xml file
and finally try following HTML page to call servlet.
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button. This would
display first name and last name on your screen and same time it would set two
cookies firstName and lastName which would be passed back to the server when
next time you would press Submit button.
Next section would explain you how you would access these cookies back in your
web application.
Reading Cookies with Servlet
To read cookies, you need to create an array of javax.servlet.http.Cookie objects by
calling the getCookies() method of HttpServletRequest. Then cycle through the
array, and use getName() and getValue() methods to access each cookie and
associated value.
Example
Let us read cookies which we have set in previous example −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );
Compile above servlet ReadCookies and create appropriate entry in web.xml file. If
you would have set first_name cookie as "John" and last_name cookie as "Player"
then running http://localhost:8080/ReadCookies would display the following result −
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );
if((cookie.getName( )).compareTo("first_name") == 0 )
{
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie : " + cookie.getName( )
+ "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
out.println("</body>");
out.println("</html>");
}
}
Compile above servlet DeleteCookies and create appropriate entry in web.xml file.
Now running http://localhost:8080/DeleteCookies would display the following result −
Cookies
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the recieved
cookie.
This may not be an effective way because many time browser does not support a
cookie, so I would not recommend to use this procedure to maintain the sessions.
URL Rewriting
You can append some extra data on the end of each URL that identifies the session,
and the server can associate that session identifier with data it has stored about that
session.
For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session
identifier is attached as sessionid = 12345 which can be accessed at the web server
to identify the client.
URL rewriting is a better way to maintain sessions and it works even when browsers
don't support cookies. The drawback of URL re-writing is that you would have to
generate every URL dynamically to assign a session ID, even in case of a simple
static HTML page.
The HttpSession Object
Apart from the above mentioned three ways, servlet provides HttpSession Interface
which provides a way to identify a user across more than one page request or visit to
a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client
and an HTTP server. The session persists for a specified time period, across more
than one connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below −
HttpSession session = request.getSession();
You need to call request.getSession() before you send any document content to the
client. Here is a summary of the important methods available through HttpSession
object −
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td>
</tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime + " </td>
</tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime + " </td>
</tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID + " </td>
</tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td>
</tr>\n" +
"</table>\n" +
"</body>
</html>"
);
}
}
Compile the above servlet SessionTrack and create appropriate entry in web.xml
file. Now running http://localhost:8080/SessionTrack would display the following
result when you would run for the first time −
Welcome to my website
Session Infomation
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 0
Now try to run the same servlet for second time, it would display following result.
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 1