How to use Struts Framework

This tip will show you the overall architecture of a Strut application. The steps in this tip walk you through building all of the necessary components for struts.

Step 1: Installation of Tomcat 5.0

Download and install the latest stable version of Tomcat (5.0) from http://jakarta.apache.org/site/downloads/index.html

Also make sure that you have installed JDK1.4 before installation of Tomcat 5.0.

Step 2: Create the web application directory

You'll need to know the directory structure of a Struts application, and what's put in the Directories. The "struts-blank" application is well-suited for this presentation, since it contains a Minimum number of files:

Step 3: Understanding and Modifying web.xml

The web.xml file is where servlets and other stuff are defined to the servlet container. We'll remove some unnecessary things from the web.xml file so it looks like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<!-- Standard Action Servlet Configuration (with debugging-->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class> org.apache.struts.action.ActionServlet </servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</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>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
</web-app>

The file contains three sections:

  1. ??The definition of the Struts servlet named "ActionServlet"
  2. ??The URL mapping for the calls to this servlet
  3. ??The definitions of the Struts tag libraries

The servlet is called if our browser requests a file called . So when we submit the form in our one-page application to the action-name "submit.do".

Step 4: Understanding and modifying the struts-config.xml file

When you use Struts then part of this interaction is as follows:

First of all the Struts servlet will automatically transfer the data from your form into a JavaBean that you should supply. This bean is called the ActionForm bean, because your bean must extend the Struts "ActionForm" class. You may think of this bean as a buffer between the browser and your database. The ActionForm bean may also be used to initialize form controls and to validate the data entered by the user.

Secondly the Struts servlet will call a class which you specify and it is referred to as the Action class. This class may use the data in the ActionForm bean. The Action class is where your application coding starts. When your class finishes it returns control to the Struts servlet.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<!-- ========== Data Source Configuration ====================== -->
<data-sources>
<!-- configuration for commons BasicDataSource -->

</data-sources>
<!-- ========== Form Bean Definitions ======================== -->
<form-beans>
<!-- Simple ActionForm Bean -->
<form-bean name="simpleForm" type="com.rohit.SimpleActionForm"/>

</form-beans>

<!-- ========= Global Exception Definitions ======================== -->
<global-exceptions>
</global-exceptions>
<!-- ========== Global Forward Definitions ======================== -->
<global-forwards>
<forward name="home" path="/index.jsp" redirect="true"/>
</global-forwards>
<!-- ========== Action Mapping Definitions ==================== -->
<action-mappings>
<!-- Simple ActionForm Example =================== -->
<action path="/prepareSimple"
type="com.rohit.SuccessAction">
<forward name="success" path="/jsp/simple/Simple.jsp"/>
<forward name="error" path="jsp/database/error.jsp"/>
</action>
<action path="/processSimple"
type="com.rohit.ProcessSimpleAction"
name="simpleForm"
scope="request"
input="/jsp/simple/Simple.jsp"
validate="true">
<forward name="success" path="/jsp/simple/SimpleResults.jsp"/>
</action>

</action-mappings>
<!-- ========== Controller Configuration ========================== -->
<controller/>
<!-- ========== Message Resources Definitions ==================== -->
<message-resources parameter="ApplicationResources" />
<!-- ========== Plug Ins Configuration ============================== -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml" />
</plug-in>
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
<set-property property="definitions-config"
value="/WEB-INF/tiles-defs.xml" />
<set-property property="moduleAware" value="true" />
<set-property property="definitions-parser-validate" value="true" />
</plug-in>
</struts-config>

As you can see the file contains two sections: the form-beans section and the action-mappings. In the form-beans section you give the bean a logical name (referred to in the action-mapping) and specify the path for the class file.

The action-mappings are the most interesting. The attributes given are these:

  1. path - name of the request: "submit.do". You don't enter the ". do"-part here.
  2. ??type - the path for the Action class file
  3. ??name - is the logical name of the form bean (from the form-bean section)
  4. ??input - validation errors should be shown on this page
  5. ??scope - specifies how long the form bean should live. You may specify "session" instead.

The forward tag tells the servlet where to go if it receives either "success" or "failure" from the Action class.

We're now ready to code the ActionForm and the Action classes--and the jsp view.

Step 5: Building JSP page

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html xhtml="true" locale="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple form using ActionForm</title>
<html:base/>
<link rel="stylesheet" type="text/css" href="../../css/example.css" />
</head>
<body>
<h1>Simple form using ActionForm</h1>
<html:errors/>
<html:form action="/processSimple">
<p>* What's your first name?:<html:text property="name" size="40" maxlength="50"/></p>
<p>* Enter a secret word or phrase:<html:password property="secret" size="40"
maxlength="50"/></p>
<p>What is your favorite color?:
<html:select property="color">
<html:option value="red">Red</html:option>
<html:option value="green">Green</html:option>
<html:option value="blue">Blue</html:option>
</html:select>
</p>
<p><html:checkbox property="confirm"/> Is that really your favorite color?</p>
<p>How much do you like your chosen color?:<br/>
<html:radio property="rating" value="1">Actually, I hate it.</html:radio><br />
<html:radio property="rating" value="2">Not so much.</html:radio><br />
<html:radio property="rating" value="3">I'm indifferent</html:radio><br />
<html:radio property="rating" value="4">It's pretty neat</html:radio><br />
<html:radio property="rating" value="5">I painted my whole house with it.</html:radio>
</p>
<p>Enter a message (you may use html tags):<br />
<html:textarea property="message" cols="40" rows="6"/>
</p>
<html:hidden property="hidden" value="Sssh! It's a secret. Nobody knows I'm here."/>
<hr noshade="noshade" />
<p><center>
<html:submit styleClass=" customButton"><bean:message key="button.submit"/></html:submit>
<html:cancel styleClass="customButton"/></center>
</p>
</html:form>
</body>
</html:html>

Step 6: Building SimpleResults.jsp page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<html:html xhtml="true" locale="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple ActionForm Example</title>
<html:base/>
<link rel="stylesheet" type="text/css" href="../../css/example.css" />
</head>
<body>
<h1>Simple Form Results</h1>
<hr noshade="noshade"/>
<p>Hello <bean:write name="simpleForm" property="name" />,</p>
<p><strong>You told me a secret:</strong> <bean:write name="simpleForm" 
property="secret" /></p>
<p><strong>You said that your favorite color is:</strong> <bean:write name="simpleForm"
property="color" /></p>
<logic:equal name="simpleForm" property="confirm" value="true">
<p>You confirmed that this <em>is</em> your favorite color.</p>
</logic:equal>
<logic:notEqual name="simpleForm" property="confirm" value="true">
<p>... but you lied. Shame on you!</p>
</logic:notEqual>
<p><strong>On scale of to you rated your color:</strong>
<bean:write name="simpleForm" property="rating" />
</p>
<p><strong>This was lurking in a hidden field:</strong><br />
<bean:write name="simpleForm" property="hidden" /></p>
<p><strong>You wrote this message:</strong></p>
<p><bean:write name="simpleForm" property="message" filter="false"/></p>
<center><html:button property="Back" styleClass="customButton" 
onclick="javascript:history.go(-1)"><bean:message key="button.back"/></html:button> </center>
</body>
</html:html>

Step 7: Coding the ActionForm class

This class must extend the Struts ActionForm, and must have setters and getters for all the form Controls in the jsp-page. Optionally it may have a validation method for validating inputs at server side.

package com.xyz;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;

public final class SubmitForm extends ActionForm {
    
    /* Last Name */
    private String lastName = "Rohitl"// default value
    
    public String getLastName() {
        return (this.lastName);
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    /* Address */
    private String address = null;
    
    public String getAddress() {
        return (this.address);
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    
    /* Sex */    
    private String sex = null;
    
    public String getSex() {
        return (this.sex);
    }
    
    public void setSex(String sex) {
        this.sex = sex;
    }
    
    /* Married status */
    private String married = null;
    
    public String getMarried() {
        return (this.married);
    }
    
    public void setMarried(String married) {
        this.married = married;
    }
    
    /* Age */
    private String age = null;
    
    public String getAge() {
        return (this.age);
    }
    
    public void setAge(String age) {
        this.age = age;
    }
}

Compile this class by including struts.jar and servlet-api.jar files in the classpath. The struts .jar file is available in the lib directory of your application and servlet-api.jar is available at <TOMCAT-HOME>\common\lib.

Step 8: Coding the Action class

The Action class is the heart of the application. This is where you must decide how you'll separate your own application code. Most often the Action class should be kept as "thin" as possible, placing business logic in other beans or even EJB's on other servers. The implementation of the Action class must contain a "execute" method, which receives the request and response objects, the instance of the ActionForm bean and the action mapping information from the configuration file. A very simple Action class, which simply lets the request pass unaltered, is given as follows:

package com.rohit;

import javax.servlet.http.*;
import org.apache.struts.action.*;

public final class SubmitAction extends Action {
    
    public ActionForward execute(ActionMapping mapping,
           ActionForm form, HttpServletRequest request, 
           HttpServletResponse response) {
        
        SubmitForm f = (SubmitFormform; // get the form bean
        
        // and take the last name value
        String lastName = f.getLastName();
        
        // Translate the name to upper case
        //and save it in the request object
        request.setAttribute("lastName", lastName.toUpperCase());
        
        // Forward control to the specified success target
        return (mapping.findForward("success"));
    }
}

The manipulation of the "last name" value is only done to show how to access the form bean and how you may store data for use by other components, e.g. the jsp-file.

You may recall that the target of "success", which was specified in the Struts config file, was the submit.jsp file.

This class is also placed in the WEB-INF/classes/com/rohit directory.

An important thing to remember is that Struts only creates a single instance of the Action class shared amongst all users of the application. You should therefore not use member variables, but only local variables.

To test our example, enter this URL in the browser:

http://localhost:8080/myproject/submit.jsp.

If your application works, you'll see that "Last Name" is filled with "Anil" (which means that Struts has already created an instance of the ActionForm bean, and extracted the data from it). Now enter data in all the controls and press "Submit". Note that the URL changes to "submit.do", and that all data stays unchanged in the form.

You might also want to try to enter some "problematic" characters like single and double quotes or the "<" and ">" characters in the text fields to see that Struts is perfectly capable of handling them correctly. Use the browsers "view source" to see how Struts does it.

Step 9: Create .war file

Create myproject.war using jar command provided with JDK. Open command window and change directory to your application directory (i.e.myproject).

Exceute jar –cvf myproject.war command. This creates myproject.war file in myproject directory. If jar command is not recognized, set path environment to jdk bin directory (ex. Execute command: set path=c:\jdk1.3.1\bin )

Step 10: Deploying war file

Deploy myproject.war using manager application of Tomcat 5.0 server Log to manager application by visiting the page http://ttc_ejb_srv/manager/htm. This opens dialog to enter username and password to log in the manager application. Provide the user name and password as admin (Contact your Server administrator for username and password). Once you logs in the application you should see the page as shown in the following figure.


Image

Step 11: Testing application

Visit pages(index.jsp) using url http://ttc_ejb_srv:8080/myproject/index.jsp.

Repeat the steps for whenever you do changes in your application on client and want to test them.

Step 12: Validating your input

Let's assume that the user of our form must enter his or her last name, address, sex and age. The Simplest way to implement validation is in the ActionForm bean, but you can also do it in the Action class.

Code the "validate" method in ActionForm While we're modifying the code, we also add some log messages so we can check the data we Receive from the form:


public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    
    ActionErrors errors = new ActionErrors();
    
    //   Name must be entered
    if ((name == null|| (name.length() 1)) {
        errors.add("name"new ActionError("errors.name.required"));
    }
    
    //   Secret Phrase must be entered
    if ((secret == null|| (secret.length() 1)) {
        errors.add("secret"new ActionError("errors.secret.required"));
    }
    
    return (errors);
}

The servlet controller will check if the returned ActionErrors object is empty or not. If not empty the controller will return to the page specified by the "input" parameter in the config file. In our example this is the submit.jsp page. Define the error message text.The error messages are taken from the ApplicationResources.properties file. The messages are Inserted in the jsp-page by using the Struts tag or . In order to have a nice formatting of the messages you must also define two keys called errors.header and errors.footer. This is our ApplicationResources.properties file (note that HTML tags may be included as you like it):

ApplicationResources.properties

errors.header=<h4>Validation Error(s)</h4><ul>
errors.footer=</ul><hr>
error.lastName=<li>Enter your last name
error.address=<li>Enter your address
error.sex=<li>Enter your sex
error.age=<li>Enter your age

Now restart the servlet container (Tomcat Server) and test the validations. If we don't enter anything in the form we'll get this answer: Note that age 0-19 is selected as default according to normal HTML selection list practice. Modify the Submit Page to display validation errors next to the field using <html:errors property=”propertyname” /> tag.

Output screen when validation fails


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值