Thursday, 24 May 2012

ActionServlet

Action Servlet :
The class org.apache.struts.action.ActionServlet is the heart of the Struts Framework. It is the Controller part of the Struts Framework. ActionServlet is configured as Servlet in the web.xml file as shown in the following code snippets.

<servlet>
   <servlet-name>action</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>

This servlet is responsible for handing all the request for the Struts Framework, user can map the specific pattern of request to the ActionServlet. <servlet-mapping> tag in the web.xml file specifies the url pattern to be handled by the servlet. By default it is *.do, but it can be changed to anything. Following code form  the web.xml file shows the mapping.

<servlet-mapping>
  <servlet-name>action</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

The above mapping maps all the requests ending with .do to the ActionServlet. ActionServlet uses the configuration defined in struts-config.xml file to decide the destination of the request. Action Mapping Definitions (described below) is used to map any action.
Example:

Welcome.jsp

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html locale="true">
<head>
   <title><bean:message key="welcome.title"/></title>
   <html:base/>
</head>
  <body bgcolor="white">
  <h3><bean:message key="welcome.heading"/></h3>
  <p><bean:message key="welcome.message"/></p>
</body>
</html:html>

Forwarding the Welcome.do request to Welcome.jsp
  • The "Action Mapping Definitions" is the most important part in the struts-config.xml. This section takes a form defined in the "Form Bean Definitions" section and maps it to an action class.
  • Following code under the <action-mappings> tag is used to forward the request to the Welcome.jsp.
<action  path="/Welcome"
  forward="/pages/Welcome.jsp"
/>

To call this Welcome.jsp file we will use the following code.
<html:link page="/Welcome.do">First Request to the controller
</html:link>

Once the use clicks on on First Request to the controller link on the index page, request (for Welcome.do) is sent to the Controller and the controller forwards the request to Welcome.jsp. The content of Welcome.jsp is displayed to the user.

 

No comments:

Post a Comment