Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

10.4 Example: Monitoring Changes to Commonly Used Data

Section 10.2 shows how to read the current and former company names when the Web application is loaded and how to make use of those values in JSP pages. But what if you want to change the company name during the execution of the Web application? It is reasonable to expect a routine that makes this change to modify the companyName servlet context attribute. After all, in this context, that's what it means to change the company name. It is not reasonable, however, to expect that routine to modify (or even know about) the formerCompanyName attribute. But, if the company name changes, the former company name must change as well. Enter servlet context attribute listeners!

The following steps summarize a listener that automatically updates the former company name whenever the current company name changes.

  1. Implement the ServletContextAttributeListenerinter-face. Listing 10.5 shows a class (ChangedCompanyNameListener) that implements this interface.

  2. Override attributeAdded, attributeReplaced, and attributeRemoved. The attributeReplacedmethod is used to detect modification to context attributes. Empty bodies are supplied for the attributeAddedand attributeRemovedmethods.

  3. Obtain references to the attribute name, attribute value, and servlet context. The attributeReplacedmethod calls getName and getValueon its ServletContextAttributeEventargu-ment to obtain the name and value of the modified attribute. The method also calls getServletContexton its argument to get a reference to the servlet context.

  4. Use the objects. The attribute name is compared to "company-Name". If the name matches, the attribute value is used as the new value of the formerCompanyNameservlet context attribute.

  5. Declare the listener. The listener is declared in the deployment descriptor with the listenerand listener-classelements, as below.

    <listener>
      <listener-class>
       moreservlets.listeners.ChangedCompanyNameListener
      </listener-class>
    </listener>

    The web.xml file is shown in Listing 10.6.

Listing 10.7 presents a JSP page containing a form that displays the current company name, lets users enter a new name, and submits the new name to the Change-CompanyName servlet (Listing 10.8). Since changing the company name is a privileged operation, access to the form and the servlet should be restricted.

So, the form is placed in the admin directory and the servlet and servlet-mapping elements are used to assign the servlet a URL that also starts with /admin. See Section 5.3 (Assigning Names and Custom URLs) for details on servlet and servlet-mapping; see the deployment descriptor in Listing 10.6 for the usage in this example.

Next, the security-constraint element is used to stipulate that only authenticated users in the ceo role can access the admin directory. Then, the login-config element is used to specify that form-based authentication be used, with login.jsp (Listing 10.9) collecting usernames and passwords and login-error.jsp (Listing 10.10) displaying messages to users who failed authentication. Listing 10.11 shows a Tomcat-specific password file used to designate a user who is in the ceo role. See Section 7.1 (Form-Based Authentication) for details on these types of security settings; see the deployment descriptor in Listing 10.6 for the usage in this example.

Figures 10–3 through 10–8 show the results of logging in, changing the company name, and revisiting the pages that display the current and former company names.

Figures 10–3 Only users who are in the ceo role can access the form that changes the company name.

Figures 10–4 A failed login attempt.

Figures 10–5 The form to change the company name when the page is accessed by an authenticated user who is in the ceo role.

Figures 10–6 The name change confirmation page.

Figures 10–7 When the company name changes, the company home page (Listing 10.3) is automatically updated.

Figures 10–8 When the company name changes, the company information page (Listing 10.4) is also updated automatically.

Listing 10.5 ChangedCompanyNameListener.java

package moreservlets.listeners;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Listener that monitors changes in the company
 * name (which is stored in the companyName attribute
 * of the servlet context).
 */

public class ChangedCompanyNameListener
   implements ServletContextAttributeListener {
  /** When the companyName attribute changes, put
  * the previous value into the formerCompanyName
  * attribute.
  */

  public void attributeReplaced
               (ServletContextAttributeEvent event) {
   if (event.getName().equals("companyName")) {
     String oldName = (String)event.getValue();
     ServletContext context = event.getServletContext();
     context.setAttribute("formerCompanyName", oldName);
   }
  }
  public void attributeAdded
              (ServletContextAttributeEvent event) {}
  public void attributeRemoved
              (ServletContextAttributeEvent event) {}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC
   "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
   "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <!-- ... -->

  <!-- Register the listener that monitors changes to
    the company name.
  -->
  <listener>
   <listener-class>
     moreservlets.listeners.ChangedCompanyNameListener
   </listener-class>
  </listener>
  <!-- ... -->

  <!-- Assign the name ChangeCompanyName to
    moreservlets.ChangeCompanyName. -->
  <servlet>
   <servlet-name>ChangeCompanyName</servlet-name>
   <servlet-class>moreservlets.ChangeCompanyName</servlet-class>
  </servlet>

  <!-- Give a name to the servlet that redirects users
    to the home page.
  -->
  <servlet>
   <servlet-name>Redirector</servlet-name>
   <servlet-class>moreservlets.RedirectorServlet</servlet-class>
  </servlet>

  <!-- Assign the URL /admin/ChangeCompanyName to the
    servlet that is named ChangeCompanyName.
  -->
  <servlet-mapping>
   <servlet-name>ChangeCompanyName</servlet-name>
   <url-pattern>/admin/ChangeCompanyName</url-pattern>
  </servlet-mapping>

  <!-- Turn off invoker. Send requests to index.jsp. -->
  <servlet-mapping>
   <servlet-name>Redirector</servlet-name>
   <url-pattern>/servlet/*</url-pattern>
  </servlet-mapping>
  <!-- ... -->

  <!-- Protect everything within the "admin" directory.
     Direct client access to this directory requires
     authentication.
  -->
  <security-constraint>
   <web-resource-collection>
     <web-resource-name>Admin</web-resource-name>
     <url-pattern>/admin/*</url-pattern>
   </web-resource-collection>
   <auth-constraint>
     <role-name>ceo</role-name>
   </auth-constraint>
  </security-constraint>

  <!-- Tell the server to use form-based authentication. -->
  <login-config>
   <auth-method>FORM</auth-method>
   <form-login-config>
     <form-login-page>/admin/login.jsp</form-login-page>
    <form-error-page>/admin/login-error.jsp</form-error-page>
   </form-login-config>
  </login-config>
</web-app>

Listing 10.7 change-company-name.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<%@ page import="moreservlets.listeners.*" %>
<%
String companyName =
  InitialCompanyNameListener.getCompanyName(application);
%>
<TITLE>Changing Company Name</TITLE>
<LINK REL=STYLESHEET
      HREF="../events-styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">Changing Company Name
</TABLE>
<P>

<FORM ACTION="ChangeCompanyName">
New name:
<INPUT TYPE="TEXT" NAME="newName" VALUE="<%= companyName %>">
<P>
<CENTER><INPUT TYPE="SUBMIT" VALUE="Submit Change"></CENTER>
</FORM>

</BODY>
</HTML>

Listing 10.8 ChangeCompanyName.java

package moreservlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Servlet that changes the company name. The web.xml
 * file specifies that only authenticated users in the
 * ceo role can access the servlet. A servlet context
 * attribute listener updates the former company name
 * when this servlet (or any other program) changes
 * the current company name.
 */

public class ChangeCompanyName extends HttpServlet {
  public void doGet(HttpServletRequest request,
               HttpServletResponse response)
     throws ServletException, IOException {
   boolean isNameChanged = false;
   String newName = request.getParameter("newName");
   if ((newName != null) && (!newName.equals(""))) {
     isNameChanged = true;
     getServletContext().setAttribute("companyName",
                             newName);
}
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  String docType =
   "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
   "Transitional//EN\">\n";
  String title = "Company Name";
   out.println
     (docType +
     "<HTML>\n" +
     "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
     "<BODY BGCOLOR=\"#FDF5E6\">\n" +
     "<H2 ALIGN=\"CENTER\">" + title + "</H2>");
   if (isNameChanged) {
     out.println("Company name changed to " + newName + ".");
   } else {
     out.println("Company name not changed.");
   }
   out.println("</BODY></HTML>");
  }
}

Listing 10.9 login.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Log In</TITLE>
<LINK REL=STYLESHEET
     HREF="../events-styles.css"
     TYPE="text/css">
</HEAD>

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">Log In</TABLE>
<P>
<H3>Sorry, you must log in before accessing this resource.</H3>
<FORM ACTION="j_security_check" METHOD="POST">
<TABLE>
<TR><TD>User name: <INPUT TYPE="TEXT" NAME="j_username">
<TR><TD>Password: <INPUT TYPE="PASSWORD" NAME="j_password">
<TR><TH><INPUT TYPE="SUBMIT" VALUE="Log In">
</TABLE>
</FORM>

</BODY>
</HTML>

Listing 10.10 login-error.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Begone!</TITLE>
<LINK REL=STYLESHEET
     HREF="../events-styles.css"
     TYPE="text/css">
</HEAD>

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">Begone!</TABLE>

<H3>Begone, ye unauthorized peon.</H3>

</BODY>
</HTML>

Listing 10.11 tomcat-users.xml (Excerpt for events examples)

<?xml version="1.0" encoding="ISO-8859-1"?>
<tomcat-users>
  <!-- ... -->
  <user name="gerstner" password="lou"
      roles="ceo" />
</tomcat-users>
  • + Share This
  • 🔖 Save To Your Account