O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.2. Using an External Configuration to Include a Resource in a Servlet

Problem

You want to use an external configuration file (such as web.xml) to configure the resource that is included in a servlet.

Solution

Use init parameters with the including servlet to allow the external configuration of the include mechanism, then include the resource with the javax.servlet.RequestDispatcher.include(request,response) method.

Discussion

You may want to periodically change the resource that a servlet includes, without changing and recompiling the servlet code. You can make these changes by altering the servlet's init parameters in web.xml. Using this strategy, either the included resource's file location itself or the method of retrieving the resource (such as from a database) can change. You can ensure that the servlet imports the correct resource by altering the content of the param-value element. Example 6-3 shows a servlet that is configured to include a file named privacy.jspf. This represents a standard privacy statement for the web application.

Example 6-3. Specifying an included resource by using the servlet's init-param element

<servlet>
    <servlet-name>PrivacyServlet</servlet-name>
    <servlet-class>com.jspservletcookbook.IncludeServlet</servlet-class>
    <init-param>
        <param-name>included-resource</param-name>
        <param-value>privacy.jspf</param-value>
    <init-param>
</servlet>

Example 6-4 shows the doGet( ) method of the PrivacyServlet. This method gets the value of the included-resource init ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required