Syntax
public void init() throws ServletException
Some of the other methods for implementing the controller functionality are,
getModuleConfig()
This method returns the module configuration object for the current module, ModuleConfig interface is the collection of static configuration information that describes a Struts-based module
Syntax
Protected ModuleConfig getModuleConfig(javax.servlet.http.HttpServletRequest request)
Where request represents the Servlet request that is being processed
getProcessorForModule()
The method returns the RequestProcessor object for the given module or null if one does not exist. This method will not create a RequestProcessor object and it accepts the configuration object as a parameter.
Syntax
private RequestProcessor getProcessorForModule(ModuleConfig config)
where config represents an instance of ModuleConfig
parseModuleConfigFile()
This method parses a modules configuration file.
Syntax
protected void parseModuleConfigFile(org.apace.commons.digester. Digester digester , java.lang.String path) throws javax.servlet.UnavailableException
where
digester represents an instance of Digester
path represents the path to the configuration file that is to be parsed
RequestProcessor Class
The RequestProcessor class was added to customize the request handling behavior of an application. The main purpose of the RequestProcessor class is to break down each request into small tasks. Each task is then carried out by a different method. This enables each and every individual part of a request to be customized. Each application module can have its own customized request handler.
Some of the methods for implementing the request processing functionality are,
processActionPerform()
This method will ask the specific Action class object to handle this request and returns an instance of the ActionForward class, which is returned by the Actionclass for further processing.
Syntax
protected ActionForward processActionPerform (javax.servlet.http.HttpServletRequest request , javax.servlet.http.HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping) throws java.io.IOException, javax.servlet.ServletException
where
request represents the servlet request object that is being processed.
response represents the servlet response object that is being created.
action represents the Action object that is to be used.
form represents the ActionForm object that will be parsed to this Action object.
mapping represents the ActionMapping object to pass to this Action.
IOException throws an IOException if an input/output error occurs.
servletException throws a ServletException if a servlet exception occurs.
processValidate()
This method will call the Validate() method of the specific ActionForm object provided the request’s ActionMapping parameter has not disabled validation. If any errors are found during validation they are forwarded to the input path.
Syntax
protected boolean processvalidate(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, ActionForm form, ActionMapping mapping) throws java.io.IOException, javax.servlet.ServletException
where
request represents the servlet request object that is being processed.
response represents the servlet response object that is being created.
form represents the ActionForm object that is being populated.
mapping represents the ActionMapping object that is being used.
IOException throws an IOException if an input/output error occurs.
ServletException throws a ServletException if a servlet exception occurs.
processRoles()
This method will check if the current user has a role that will allow the user to access the requested resource. The method returns a boolean value of true and false. A true value indicates normal processing and the false value indicates that processing should terminate.
Syntax
protected boolean processRoles(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, ActionForm form, ActionMapping mapping) throws java.io.IOException, javax.servlet.ServletException
where
request represents the servlet request object that is being processed.
response represents the servlet response object that is being created.
mapping represents the ActionMapping object that is being used.
IOException throws an IOException if an input/output error occurs.
ServletException throws a ServletException if a servlet exception occurs.
Action Class
The action class is responsible for processing specific requests. In other words, the task performed by the Action class should be cohesive and related to one business operation. This class is also responsible for transferring data between the View layer and the business process in the model layer and vice versa.
Each action is mapped to a path in the struts configuration file as shown in code below,
- <action-mappings>
- <action path=”/UpdateProduct” type=”com.app.struts.UpdateProductAction”/>
- </action-mappings>
Some of the methods of this class are:
getErrors()
The method retrieves errors that are placed by the previous actions in the request object. Instead of creating a new ActionMessages() object this method can be invoked at the beginning of an Action. The method returns errors or an instance of ActionMessages class.
Syntax
protected ActionMessages getErrors(javax.servlet.http.HttpServletRequest req)
where
req represents a servlet request that is being processed
getLocale()
The method returns the currently selected locale of the user.
Syntax
protected java.util.Locale getLocale(javax.servlet.http.HttpServletRequest req)
Where
req represents a servlet request that is being processed
getMessages()
The method retrieves the existing method placed by previous actions in the request. The method returns messages that are present in the HTTP request object or it will create a new instance of ActionMessages class.
Syntax
protected ActionMessages getMessages (javax.servlet.http.HttpServletRequest req)
Where
req represents a servlet request that is being processed
getServlet()
The method returns an object of the attached servlet class.
Syntax
public ActionServlet getServlet()
ActionForward Class
The execute() method of the Action class returns the next view, which should be shown to the user. ActionForward class provides information for the next view. It is an effective wrapper.
The following are the properties of the ActionForward class:
- name: specifies the logical name for the ActionForward.
- path: specifies the URI for the ActionForward
- redirect: Redirects the control, if true. However , default is false.
- contextRelative :Interprets the path value. If false, path value is represent as context relative.
The path property can contain any URI. It can also contain a query. Based on the redirect attribute, the RequestDispatcher interface may either execute forward or redirect for the ActionForward.
ActionForward class is configured in strut-config.xml file so that it represents a destination. The ActionForward is defined in the action-mapping elements as shown in code below:
- <action-mappings>
- <forward name=”success” path=”welcome.do” />
- </action-mappings>
Let's look with the help of an example:
- Copy the “struts-proj.war” to the “…\tomcat\webapps” folder. If you start Tomcat, Tomcat will automatically expand the web archive file. Also, you may manually expand the war file to examine the Struts startup skeleton.
- Name your software application. Under “…\tomcat\webapps”, right-click the “struts-blank” and rename it called “MyProj”. It looks like below:
- Note that skeleton “web.xml”, jars, and TLD files for the Struts tag library are already copied, expanded from “struts-proj.war”.
- Use a Struts tag. Create “index.jsp” in the “\MyProj” folder in a struts framework “Hello World”.
- <%@ page language="java" %>
- <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
- <head><title>Welcome</title></head>
- <body>
- Hello World!!<p>
- <html:link page="/do/searchAct"> Search </html:link>
- </body>
- Note that we are using the Struts HTML taglib to do our link to a page we will create later.
- Browse the “index.jsp” (http://localhost:8080/MyProj/index.jsp).
Struts-Config File
Let’s look at the “…\WEB-INF\web.xml” file.
- <?xml version="1.0" ?>
- <!DOCTYPE "http://java.sun.com/J2EE/DTDS/web-app.dtd">
- <web-app>
- <!-- Action Servlet Configuration -->
- <servlet>
- <servlet-name>action</servlet-name>
- <servletclass>
- org.apache.struts.action.ActionServlet
-
- </servlet-class>
- <init-param>
- <param-name>Application</param-name>
- <param-value>AppResource</param-value>
- </init-param>
- <init-param>
- <param-name>config</param-name>
- <param-value>/WEB-INF/struts-config.xml
- </paramvalue>
- </init-param>
- <init-param>
- <param-name>Debug</param-name>
- <param-value>2</param-value>
- </init-param>
- <init-param>
- <param-name>Detail</param-name>
- <param-value>2</param-value>
- </init-param>
- <init-param>
- <param-name>Validate</param-name>
- <param-value>true</param-value>
- </init-param>
- <load-on-startup>2</load-on-startup>
- </servlet>
- <!-- Action Servlet Mapping -->
- <servlet-mapping>
- <servlet-name>action</servlet-name>
- <url-pattern>/do/*</url-pattern>
- </servlet-mapping>
- <!-- The Welcome File List -->
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <!-- Struts Tag Library Descriptors -->
- <taglib>
- <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
- <taglib-location>/WEB-INF/strutsbean.tld</taglib-location>
- </taglib>
- <taglib>
- <taglib-uri>/WEB-INF/struts-logic.tld
- </tagliburi>
- <taglib-location>/WEB-INF/strutslogic.tld</taglib-location>
- </taglib>
- <taglib>
- Modified the <url-pattern> for the “action” <servlet-name> to “/do/*”. Struts normally has the “/*.do” pattern for the action servlet.
- Have a single servlet that will run things like, a mapping to forward, and tag libraries that will help to develop web application.
- Anything send to “/do/” will be handled by Struts. Struts uses another configuration file, “struts-config.xml”.
- To understand the Struts MVC, let’s create some folders like “data” and “app” in the “…\WEBINF\classes” directory.
In the “data” directory, we will store the classes this will act as a Model Layer, JavaBeans that extend the Struts FormBean. In the “app” directory, we will store the classes that will act as a controller layer, the application code that extends Struts Action with perform() method.
- Create a “pages” folder in the “…\WEB-INF” directory to hold the View (pages) layer which will consist of JSP’s.
- We have the “...\WEB-INF\classes\data” (Model) , the “...\WEB-INF\pages” (View), & the “...\WEBINF\classes\app” (Controller) folders.
- Read the “struts-config.xml” file.
- <?xml version="1.0" ?>
- <struts-config>
- <global-forwards>
- <!-- <forward name="search" path="/do/searchAct"/> -->
- </global-forwards>
- <form-beans>
- <form-bean name="SerchFrom" type="data.SerchFrom"/>
- <form-bean name=" NameLastFrom " type="data.NameLastFrom"/>
- </form-beans>
- <action-mappings>
- <action path= "/searchAct" type= "app.SearchAct" name= "SerchFrom"
- scope="request" input="/WEB-INF/pages/SearchPage.jsp">
- <forward name="SearchPage" path="/WEBINF/pages/SearchPage.jsp"/>
- <forward name=" NameLastAct " path="/do/NameLastAct"/>
- </action>
- <action path= "/NameLastAct" type= "app.NameLastAct" scope="request" input="/WEB-INF/pages/NameLastPage.jsp">
- <forward name="nameLastPage" path="/WEBINF/pages/NameLastPage.jsp"/>
- <forward name="nameZoomAct" path="/do/nameZoomAct"/>
- </action>
- </action-mappings>
- </struts-config>
- Note that “web.xml” will forward “/do” to action servlet. The action servlet will read “struts-config.xml” to determine which class will handle the action.
- “index.jsp” above asks for a “/do/searchAct”. The request is forwarded to the Struts action which determines the handler class. The class is “app.SearchAct”.
- When we click on ‘Search’ link in “index.jsp”, we will ask “app.SearchAct” to handle the request through perform() method. perform() forwards the request to a particular page. Reading “struts-config.xml”, “app.SearchAct” can forward to a “SearchPage” under “/pages” and ask for another action “/do” of ‘NameLastAct’.
Create an action class “…\WEBINF\classes\app\SearchAct.java”
- package app;
- import java.io.*;
- import java.util.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import org.apache.struts.action.*;
- import data.*;
- public class SearchAct extends Action {
- public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,
- ServletException {
- return (mapping.findForward("SearchPage"));
- }
- }
Create a “SearchPage.jsp” in “…\WEB-INF\pages” folder:
- <%@ page language="java" %><%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
- <head>
- <title> Search </title>
- <html:base/>
- </head>
- <body>
- <html:form action="/searchAct">
- <p>First Name:
-
- <html:text property="FirstName"/>
- <p>
- <p>Last Name:
-
- <html:text property="LastName"/>
- <p>
- <html:submit property="submit" value="Submit"/>
- </html:form>
- </body>
Create a JavaBean to handle the data (“…\WEBINF\classes\data\SerchFrom”)
- package data;
- import org.apache.struts.action.*;
- public class SerchFrom extends ActionForm {
- private String FirstName;
- private String LastName;
- public String getFirstName() {
- return (this.FirstName);
- }
- public String getLastName() {
- return (this.LastName);
- }
- public void setFirstName(String aFirstName) {
- this.FirstName = aFirstName;
- }
- public void setLastName(String aLastName) {
- this.LastName = aLastName;
- }
- }
For this simple bean, we have two properties with accessor and mutator methods. How they map with a view? For this “SearchPage.jsp” asks for the name to search in application. The controller forwards to a page that binds data to a bean. This is the foundation of the Struts framework.
Enter Data now, as shown in the fig below:
- Now we have data in our bean and the controller can access it. We need to be able to pass this data to the next page that will eventually display for retrieval.
- Update controller to take data and looks again the “struts-config.xml”. The “SearchAct” controller will forward to 2 different places, in order that the controller should decide where to approach.
- Modified “SearchAct.java” with if / then logic as below:
- package app;
- import java.io.*;
- import java.util.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import org.apache.struts.action.*;
- import data.*;
- public class SearchAct extends Action {
- public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,
- ServletException {
- boolean data = false;
- HttpSession session = request.getSession();
- String fname = ((SerchFrom) form).getFirstName();
- String lname = ((SerchFrom) form).getLastName();
- if ((fname != null) | (lname != null)) {
- session.setAttribute("SerchFrom", form);
- data = true;
- System.out.println("Search" + fname + lname);
- }
- if (data) return (mapping.findForward("NameLastAct"));
- else return (mapping.findForward("SearchPage"));
- }
- }
- In the first case, we had no data, it sent it to a page for us to enter data, and then it got back to the control.
- We have data, and it is captured in the bean. So the controller can now take a peek at that data and forward it to another controller.
- You can see that one of the arguments passed to perform() in the form bean. This is done by Struts.
- So if there is none, we have our first case and we go to the page to enter it.
- If we have data, so go on to our next page, the page that will display the retrieval data later.
- Recall that we should ask the controller to display our page. Sometimes one controller controls many pages.
- In the second case, go to the ‘NameLastAct’ controller. According to “struts-config.xml”, the class is stored in the “app” folder as ‘NameLastAct’ and we have already data in another bean. The bean for the “NameLastPage.jsp” page will have different fields. i,e. it will need a different Form bean. Each page should have its own form bean and its own controller.
- So we have data from one bean that needs to go to another bean. So Action performs () should re-map it, and then display the data searching for, just to make sure that to pass data from one page to another page.
The source code for our second controller “…\WEBINF\classes\app\NameLastAct.java”
- package app;
- import java.io.*;
- import java.util.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import org.apache.struts.action.*;
- import data.*;
- public class NameLastAct extends Action {
- public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException,
- ServletException {
- HttpSession session = request.getSession();
- boolean data = false;
- NameLastFrom nl = new NameLastFrom();
- SerchFrom sfrm = new SerchFrom();
- String fname = null;
- String lname = null;
- sfrm = (SerchFrom) session.getAttribute("SerchFrom");
- if (sfrm != null) {
- fname = sfrm.getFirstName();
- lname = sfrm.getLastName();
- nl.setSearchFirstName(fname);
- nl.setSearchLastName(lname);
- session.setAttribute("NameLastFrom", nl);
- data = true;
- }
- System.out.println("NameLst" + fname + lname + nl.getSearchFirstName() + nl.getSearchLastName());
- if (data) return (mapping.findForward("NameLastPage"));
- else return (mapping.findForward("NameLastPage"));
- }
- }
So we will get the bean out of the session, create a new bean, and then put it in the session.
Second form bean (“…\WEBINF\classes\data\NameLastFrom.java”)
- package data;
- import org.apache.struts.action.*;
- public class NameLastFrom extends ActionForm {
- private String searchFirstName;
- private String searchLastName;
- public String getSearchFirstName() {
- return (this.searchFirstName);
- }
- public String getSearchLastName() {
- return (this.searchLastName);
- }
- public void setSearchFirstName(String aFirstName) {
- this.searchFirstName = aFirstName;
- }
- public void setSearchLastName(String aLastName) {
- this.searchLastName = aLastName;
- }
- }
- Second JSP page (“…\WEBINF\pages\NameLastPage.jsp”)
- <%@ page language="java" %><%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
- <head>
- <title> Names Lst </title>
- <html:base/>
- </head>
- <body>
- <p>
- Search for:
- <p>
- <bean:write name="NameLastFrom" property="searchFirstName"/>
- <p>
- <bean:write name="NameLastFrom" property="searchLastName"/>
- <p>
Note using a <bean:write> tag and not the <html:text> tag this time for just displaying data.
Summary
The core of struts, which is based on MVC architecture, is the controller component. The controller is Servlet. ActionServlet class is responsible for initializing the struts framework for a web application and receiving all the requests. RequestProcessor class breaks down each request into small tasks to be carried out by different methods. Action class is the heart of the framework and acts as a bridge between the client request and business operation. ActionForward class encapsulates a forward. In the given example, first, we created the struts pages and looked at how to create and read the “struts-config.xml” file. In the Struts folders, (“data”, “pages”, and “app”) are consistent with an MVC approach.