struts2.01用法的簡單例子

hljhrbsjf發表於2007-06-20

先按照文件,做一次:

1,建立WEB.XML:

程式碼
  1. <!-- 段洪傑 --&gt
  2. xml version="1.0" encoding="UTF-8"?>
  3. <web-app>
  4. <display-name>Struts Blankdisplay-name>
  5. <filter>
  6. <filter-name>struts2filter-name>
  7. <filter-class>org.apache.struts2.dispatcher.FilterDispatcherfilter-class>
  8. filter>
  9. <filter-mapping>
  10. <filter-name>struts2filter-name>
  11. <url-pattern>/*url-pattern>
  12. filter-mapping>
  13. <listener>
  14. <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  15. listener>
  16. <welcome-file-list>
  17. <welcome-file>index.htmlwelcome-file>
  18. welcome-file-list>
  19. web-app>

文件中有一個org.apache.struts2.dispatcher.FilterDispatcher的filter
還有org.springframework.web.context.ContextLoaderListener

2.建SPRING的BEAN配置檔案:applicationContext.xml

程式碼
  1. xml version="1.0" encoding="UTF-8"?>
  2. ag">>
  3. <beans default-autowire="autodetect">
  4. <!-- add your spring beans here --&gt
  5. beans>

3.建struts配置檔案:

程式碼
  1. /span>
  2. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  3. ">
  4. <struts>
  5. <include file="example.xml"/>
  6. <!-- Add packages here --&gt
  7. struts>

演示了一下配置檔案分塊的方法,下面這個才起作用:

br />"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
">

程式碼
  1. <struts>
  2. <package name="example" namespace="/example" extends="struts-default">
  3. <action name="HelloWorld" class="example.HelloWorld">
  4. <result>/example/HelloWorld.jspresult>
  5. action>
  6. <action name="Login!*" method="{1}" class="example.Login">
  7. <result name="input">/example/Login.jspresult>
  8. <result type="redirect-action">Menuresult>
  9. action>
  10. <action name="*" class="example.ExampleSupport">
  11. <result>/example/{1}.jspresult>
  12. action>
  13. <!-- Add actions here --&gt
  14. package>
  15. struts>

4,錄入驗證:Login-validation.xml
這個很象struts1.x

程式碼
  1. /span>
  2. "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  3. ">
  4. <validators>
  5. <field name="username">
  6. <field-validator type="requiredstring">
  7. <message key="requiredstring"/>
  8. field-validator>
  9. field>
  10. <field name="password">
  11. <field-validator type="requiredstring">
  12. <message key="requiredstring"/>
  13. field-validator>
  14. field>
  15. validators>

5.建立資原始檔package.properties,這個也很象struts1.x

程式碼
  1. HelloWorld.message= Struts is up and running ...
  2. requiredstring = ${getText(fieldName)} is required.
  3. password = Password
  4. username = User Name
  5. Missing.message = This feature is under construction. Please try again in the next interation.

6.搞個action類,和WW2一模一樣:

程式碼
  1. package example;
  2. public class Login extends ExampleSupport {
  3. public String execute() throws Exception {
  4. if (isInvalid(getUsername())) return INPUT;
  5. if (isInvalid(getPassword())) return INPUT;
  6. return SUCCESS;
  7. }
  8. private boolean isInvalid(String value) {
  9. return (value == null || value.length() == 0);
  10. }
  11. private String username;
  12. public String getUsername() {
  13. return username;
  14. }
  15. public void setUsername(String username) {
  16. this.username = username;
  17. }
  18. private String password;
  19. public String getPassword() {
  20. return password;
  21. }
  22. public void setPassword(String password) {
  23. this.password = password;
  24. }
  25. }

7.搞個helloworld類,也和WW2一樣:
這裡呼叫了資原始檔中的 message, 這裡比struts1.X類似功能要直接,會好用一些

程式碼
  1. package example;
  2. /**
  3. * <code>Set welcome message.code>
  4. */
  5. public class HelloWorld extends ExampleSupport {
  6. public String execute() throws Exception {
  7. setMessage(getText(MESSAGE));
  8. return SUCCESS;
  9. }
  10. /**
  11. * Provide default valuie for Message property.
  12. */
  13. public static final String MESSAGE = "HelloWorld.message";
  14. /**
  15. * Field for Message property.
  16. */
  17. private String message;
  18. /**
  19. * Return Message property.
  20. *
  21. * @return Message property
  22. */
  23. public String getMessage() {
  24. return message;
  25. }
  26. /**
  27. * Set Message property.
  28. *
  29. * @param message Text to display on HelloWorld page.
  30. */
  31. public void setMessage(String message) {
  32. this.message = message;
  33. }
  34. }

8。搞個父類出來,這裡只是演示用,所以空的

ExampleSupport.java

程式碼
  1. package example;
  2. import com.opensymphony.xwork2.ActionSupport;
  3. /**
  4. * Base Action class for the Tutorial package.
  5. */
  6. public class ExampleSupport extends ActionSupport {
  7. }

9。可以測試一下了:

程式碼
  1. package example;
  2. import com.opensymphony.xwork2.ActionSupport;
  3. import com.opensymphony.xwork2.config.entities.ActionConfig;
  4. import java.util.Map;
  5. import java.util.Collection;
  6. import java.util.List;
  7. public class LoginTest extends ConfigTest {
  8. public void FIXME_testLoginConfig() throws Exception {
  9. ActionConfig config = assertClass("example", "Login!input", "example.Login");
  10. assertResult(config, ActionSupport.SUCCESS, "Menu");
  11. assertResult(config, ActionSupport.INPUT, "/example/Login.jsp");
  12. }
  13. public void testLoginSubmit() throws Exception {
  14. Login login = new Login();
  15. login.setUsername("username");
  16. login.setPassword("password");
  17. String result = login.execute();
  18. assertSuccess(result);
  19. }
  20. // Needs access to an envinronment that includes validators
  21. public void FIXME_testLoginSubmitInput() throws Exception {
  22. Login login = new Login();
  23. String result = login.execute();
  24. assertInput(result);
  25. Map errors = assertFieldErrors(login);
  26. assertFieldError(errors,"username","Username is required.");
  27. assertFieldError(errors,"password","Password is required.");
  28. }
  29. }

程式碼
  1. package example;
  2. import com.opensymphony.xwork2.ActionSupport;
  3. import junit.framework.TestCase;
  4. public class HelloWorldTest extends TestCase {
  5. public void testHelloWorld() throws Exception {
  6. HelloWorld hello_world = new HelloWorld();
  7. String result = hello_world.execute();
  8. assertTrue("Expected a success result!",
  9. ActionSupport.SUCCESS.equals(result));
  10. assertTrue("Expected the default message!",
  11. hello_world.getText(HelloWorld.MESSAGE).equals(hello_world.getMessage()));
  12. }
  13. }

程式碼
  1. package example;
  2. import com.opensymphony.xwork2.ActionSupport;
  3. import com.opensymphony.xwork2.config.RuntimeConfiguration;
  4. import com.opensymphony.xwork2.config.entities.ActionConfig;
  5. import com.opensymphony.xwork2.config.entities.ResultConfig;
  6. import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider;
  7. import java.util.Map;
  8. import java.util.List;
  9. import org.apache.struts2.StrutsTestCase;
  10. public class ConfigTest extends StrutsTestCase {
  11. protected void assertSuccess(String result) throws Exception {
  12. assertTrue("Expected a success result!",
  13. ActionSupport.SUCCESS.equals(result));
  14. }
  15. protected void assertInput(String result) throws Exception {
  16. assertTrue("Expected an input result!",
  17. ActionSupport.INPUT.equals(result));
  18. }
  19. protected Map assertFieldErrors(ActionSupport action) throws Exception {
  20. assertTrue(action.hasFieldErrors());
  21. return action.getFieldErrors();
  22. }
  23. protected void assertFieldError(Map field_errors, String field_name, String error_message) {
  24. List errors = (List) field_errors.get(field_name);
  25. assertNotNull("Expected errors for " + field_name, errors);
  26. assertTrue("Expected errors for " + field_name, errors.size()>0);
  27. // TODO: Should be a loop
  28. assertEquals(error_message,errors.get(0));
  29. }
  30. protected void setUp() throws Exception {
  31. super.setUp();
  32. XmlConfigurationProvider c = new XmlConfigurationProvider("struts.xml");
  33. configurationManager.addConfigurationProvider(c);
  34. configurationManager.reload();
  35. }
  36. protected ActionConfig assertClass(String namespace, String action_name, String class_name) {
  37. RuntimeConfiguration configuration = configurationManager.getConfiguration().getRuntimeConfiguration();
  38. ActionConfig config = configuration.getActionConfig(namespace, action_name);
  39. assertNotNull("Mssing action", config);
  40. assertTrue("Wrong class name: [" + config.getClassName() + "]",
  41. class_name.equals(config.getClassName()));
  42. return config;
  43. }
  44. protected ActionConfig assertClass(String action_name, String class_name) {
  45. return assertClass("", action_name, class_name);
  46. }
  47. protected void assertResult(ActionConfig config, String result_name, String result_value) {
  48. Map results = config.getResults();
  49. ResultConfig result = (ResultConfig) results.get(result_name);
  50. Map params = result.getParams();
  51. String value = (String) params.get("actionName");
  52. if (value == null)
  53. value = (String) params.get("location");
  54. assertTrue("Wrong result value: [" + value + "]",
  55. result_value.equals(value));
  56. }
  57. public void testConfig() throws Exception {
  58. assertNotNull(configurationManager);
  59. }
  60. }

哦,測試透過!

10。看看錶示層是如何用的?
HelloWorld.jsp

程式碼
  1. <%@ page contentType="text/html; charset=UTF-8" %>
  2. <%@ taglib prefix="s" uri="/struts-tags" %>
  3. <html>
  4. <head>
  5. <title><s:text name="HelloWorld.message"/>title>
  6. head>
  7. <body>
  8. <h2><s:property value="message"/>h2>
  9. <h3>Languagesh3>
  10. <ul>
  11. <li>
  12. <s:url id="url" action="HelloWorld">
  13. <s:param name="request_locale">ens:param>
  14. s:url>
  15. <s:a href="%{url}">Englishs:a>
  16. li>
  17. <li>
  18. <s:url id="url" action="HelloWorld">
  19. <s:param name="request_locale">ess:param>
  20. s:url>
  21. <s:a href="%{url}">Espanols:a>
  22. li>
  23. ul>
  24. body>
  25. html>

Login.jsp

程式碼
  1. <%@ page contentType="text/html; charset=UTF-8" %>
  2. <%@ taglib prefix="s" uri="/struts-tags" %>
  3. <html>
  4. <head>
  5. <title>Sign Ontitle>
  6. head>
  7. <body>
  8. <s:form action="Login">
  9. <s:textfield label="%{getText('username')}" name="username"/>
  10. <s:password label="%{getText('password')}" name="password" />
  11. <s:submit/>
  12. s:form>
  13. body>
  14. html>

恭喜你! 現在您現在已經可以用STRUTS2進行開發了!

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/631872/viewspace-919765/,如需轉載,請註明出處,否則將追究法律責任。

相關文章