ZeePedia

JAVA: More on Servlets

<< JAVA: Servlets Lifecycle
JAVA: Dispatching Requests >>
img
Web Design & Development ­ CS506
VU
Lesson 29
More on Servlets
The objective of this handout is to learn about the use and implementation of initialization parameters for a
Servlet. Moreover different ways of redirecting response and forwarding or including requests also
discussed in detail.
Initialization Parameters
Some times at the time of starting up the application we need to provide some initial information e,g, name
of the file where server can store logging information, DSN for database etc. Initial configuration can be
defined for a Servlet by defining some string parameters in web.xml. This allows a Servlet to have initial
parameters from outside. This is similar to providing command line parameters to a standard console based
application.
Example: setting init parameters in web.xml
Let's have a look on the way of defining these parameters in web.xml
<init-param> //defining param 1
<param-name> param1 </param-name>
<param-value> value1 </param-value>
</init-param>
<init-param> //defining param 2
<param-name> param2 </param-name>
<param-value> value2 </param-value>
In the above code, it is shown that for each parameter we need to define separate <initparam> tag that have
two sub tags <param-name> and <param-value>, which contain the name and values of the parameter
respectively.
ServletConfig
Every Servlet has an object called ServletConfig associated with it as shown in the fig. below. It contains
relevant information about the Servlet like initialization parameters defined in web.xml
Reading Initialization Parameters
Now let's see, how we can access init parameters inside the Servlet. The method getInitParameter()of
ServletConfig is usually used to access init parameters. It takes a String as parameter, matches it with
<param-name> tag under all <init-param> tags and returns <param-value> from the web.xml
One way is to override init() method as shown in the code below. The ServletConfig object can then be
used to read initialization parameter.
public void init(ServletConfig config) throws ServletException {
String name = config.getInitParameter("paramName");
}
Another way to read initialization parameters out side the init () method is
Call getServletConfig() to obtain the ServletConfig object
Use getInitParameter() of ServletConfig to read initialization parameters
211
img
Web Design & Development ­ CS506
VU
public void anyMethod() // defined inside servlet{
ServletConfig config = getServletConfig();
String name = config.getInitParameter("param_name");
}
Example Code: Reading init parameters
MyServlet.java will read the init parameter (log file name) defined inside web.xml. The code is given
below:
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
// attribute used to store init-parameter value
String fileName;
// overriding init() method
public void init(ServletConfig config) throws ServletException{
super.init(config);
// reading init-parameter "logfilename" stored in web.xmlfileName =
config.getInitParameter("logfilename");
}
/* Both doGet() & doPost() methods are override over here.processRequest() is called from both these
methods. This makespossible for a servlet to handle both POST and GET requestsidentically.
*/
// Handles the HTTP GET request type
protected void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException{
processRequest(request, response);
}
// Handles the HTTP POST request type
protected void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException{
processRequest(request, response);
}
// called from doGet() & doPost()
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException{
PrintWriter out = response.getWriter();
// writing init-parameter value that is store in fileNameout.println(fileName);
out.close();
}
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app>
<servlet> <servlet-name> MyServlet </servlet-name> <servlet-class> MyServlet </servlet-class>
<init-param> <param-name> logfilename </param-name> <param-value> logoutput.txt
212
img
Web Design & Development ­ CS506
VU
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name> MyServlet </servlet-name>
<url-pattern> /myservlet </url-pattern>
</servlet-mapping>
</web-app>
Response Redirection
We can redirect the response of the Servlet to another application resource (another Servlet, an HTML
page or a JSP) but the resource (URL) must be available to the calling Servlet, in the same Servlet
context (discussed later).
There are two forms of response redirection that can be possible:
Sending a standard redirect
Sending a redirect to an error page
Sending a standard Redirect
Using response.sendRedirect("myHtml.html") method, a new request is generated which redirects
the user to the specified URL.
If the URL is of another Servlet, that second Servlet will not have access to the original request
object. For example, if the request is redirected from servlet1 to servlet2, then servlet2 would not
be able to access the request object of servlet1.
To have access to the original request object, you must use the request dispatching technique
(discussed later) instead of redirect.
Sending a redirect to an error page
Instead of using response.sendRedirect(), we can use response.sendEorror() to show user an error page.
This methods takes two parameters, first the error number that is a predefined constant of the response class
(listed below) and second the appropriate error message. The steps to redirect the user to an error page are:
An error code is sent as a parameter of response.sendError(int, msg)method
The error page is displayed with the msg passed to method
The error numbers are predefined constants of the HttpServletResponse class. For example:
-SC_NOT_FOUND (404)
-SC_NO_CONTENT (204)
-SC_REQUEST_TIMEOUT (408)
Example Code: Response Redirection
The example given below demonstrates a typical sign on example in which a user is asked to provide
login/password, providing correct information leads to welcome page or otherwise to a registration page.
This example consists of login.html, welcome.html, register.html and MyServlet.java files. Let's examine
these one after another.
login.html
This page contains two text fields; one for entering username and another for password. The data from this
page is submitted to MyServlet.java.
213
img
Web Design & Development ­ CS506
VU
<html>
<body>
<h2> Please provide login details</h2>
<FROM METHOD="POST"
ACTION="http://localhost:8084/redirectionex/myservlet"NAME="myForm" >
<BR> User Id:
<INPUT TYPE="text" name="userid"/>
<BR> Password:
<INPUT TYPE="password" name="pwd"/>
<BR> <BR>
<input type="submit" value="Submit Form"/>
</form>
</body>
</html>
welcome.html
The user is directed to this page only if user provides correct login / password. This page only displays a
successfully logged-in message to the user.
<html>
<body>
<h2> You have successfully logged in </h2> </body>
</body>
</html>
register.html
The user is redirected to this page in case of providing incorrect login/password information. The user can
enter user id, address and phone number here to register.
Note: The code given below will only show fields to the user. It does not register user as no such
functionality is added into this small example.
<html>
<body>
<h2>Your login is incorrect. Please register yourself</h2>
<FORM METHOD="POST" ACTION="" NAME="myForm">
<BR> Name:
<INPUT TYPE="text" NAME="userid"/>
<BR> Address:
<INPUT TYPE="text" NAME="address"/>
<BR> Phone No:
<INPUT TYPE="text" NAME="phoneno"/>
<BR> <BR>
<input type="submit" value="Register"/>
</form>
</body>
</html>
MyServle.java
MyServlet.java accepts requests from login.html and redirects the user to welcome.html or register.html
based on the verification of username & password provided. Username & password are compared with fix
values in this example, however you can verify these from database or from a text file etc.
import java.io.*;
import java.net.*;
import javax.servlet.*;
214
img
Web Design & Development ­ CS506
VU
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
// Handles the HTTP GET request type
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException{
processRequest(request, response);
}
// Handles the HTTP POST request type
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException{
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws
ServletException, IOException{
String id = request.getParameter("userid");String pwd = request.getParameter("pwd");
// comparing id & password with fix values
if(id.equals("ali") && pwd.equals("vu")) {
// redirectign user to welcome.html
response.sendRedirect("welcome.html");
else {// redirecting user to register.htmlresponse.sendRedirect("register.html");
/* if you want to display an error message to theuser, you can use the following method
response.sendError(response.SC_PROXY_AUTHENTICATION_REQUIRED,"Send
Error Demo" );*/
}// end else
}
}
ServletContext
ServletContext belongs to one web application. Therefore it can be used for sharing resources among
servlets in the same web application.
As initialization parameters, for a single servlet are stored in ServletConfig, ServetContext can store
initialization parameters for the entire web application. These parameters are also called context attributes
and exist for the lifetime of the application. The following figure illustrates the sharing of context attributes
among all the servlets of a web application.
Note:
There is a single ServletContextper web application
Different Sevlets will get the same ServletContext object, when calling getServletContext()during
different sessions
Request Dispatcher
RequestDispatcher provides a way to forward or include data from another source. The method
215
img
Web Design & Development ­ CS506
VU
getRequestDispatcher(String path) of ServletContext returns a RequestDispatcher object associated with
the resource at the given path passed as a parameter.
Two important methods of RequestDispatcher are:
forward(ServletRequest req, ServletResponse resp)
include(ServletRequest req, ServletResponse resp)
RequestDispatcher: forward
Characteristics of forward methods are:
It allows a Servlet to forward the request to another resource (Servlet, JSP or HTML file) in the
same Servlet context.
Forwarding remains transparent to the client unlike res.sendRedirect(String location). You can not
see the changes in the URL.
Request Object is available to the called resource. In other words, it remains in scope.
Before forwarding request to another source, headers or status codes can be set, but
output content cannot be added.
To clarify the concepts, lets take the help from following figure. User initates the request to servlet1.
servlet1 forwards the request to servlet2 by calling forward(request,response). Finally a response is
returned back to the user by servlet2.
RequestDispatcher: include
It allows a Servlet to include the results of another resource in its response. The two major differences from
forward are:
Data can be written to the response before an include
The first Servlet which receive the request, is the one which finishes the response
It will be more cleared from the following figure. User sends a HTTPRequest to Servlet1. Serlet2 is called
by Servlet1 by using include(request, response) method. The response generated by Servlet2 sends back to
Servlet1. Servlet1 can also add its own response content and finally send it back to user.
216
img
Web Design & Development ­ CS506
VU
References:
Java A Lab Course by Umair Javed
Core Servlets and JSP by Marty Hall
Java API documentation
217