Implementing the Action Classes

The servlet mapping rule in the deployment descriptor ensures that all requests reach the Struts servlet, and the action mappings in the struts-config.xml provides the information needed to distinguish different requests from each other. It’s finally time to do some good old coding and implement the action classes.

Struts creates only a single instance of each action class and uses it for all requests, so you have to ensure that the class is thread-safe in the same way as for a servlet class. Thus, you should avoid using instance variables for anything except read-only access, and synchronize the access to shared data that must be modified.

Example 19-10 shows the main part of the action class that handles authentication requests in the Project Billboard application.

Example 19-10. Authenticate action class
package com.ora.jsp.servlets; import java.io.*; import java.net.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import com.ora.jsp.beans.emp.*; import org.apache.struts.action.*; public class AuthenticateAction extends Action { public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String userName = request.getParameter("userName"); String password = request.getParameter("password"); ActionForward nextPage = mapping.findForward("main"); EmployeeBean emp = null; try { EmployeeRegistryBean empReg = (EmployeeRegistryBean) ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.