struts2.01用法的簡單例子
先按照文件,做一次:
1,建立WEB.XML:
- <!-- 段洪傑 -->
- xml version="1.0" encoding="UTF-8"?>
- <web-app>
- <display-name>Struts Blankdisplay-name>
- <filter>
- <filter-name>struts2filter-name>
- <filter-class>org.apache.struts2.dispatcher.FilterDispatcherfilter-class>
- filter>
- <filter-mapping>
- <filter-name>struts2filter-name>
- <url-pattern>/*url-pattern>
- filter-mapping>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
- listener>
- <welcome-file-list>
- <welcome-file>index.htmlwelcome-file>
- welcome-file-list>
- web-app>
文件中有一個org.apache.struts2.dispatcher.FilterDispatcher的filter
還有org.springframework.web.context.ContextLoaderListener
2.建SPRING的BEAN配置檔案:applicationContext.xml
- xml version="1.0" encoding="UTF-8"?>
- ag">>
- <beans default-autowire="autodetect">
- <!-- add your spring beans here -->
- beans>
3.建struts配置檔案:
- /span>
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- ">
- <struts>
- <include file="example.xml"/>
- <!-- Add packages here -->
- struts>
演示了一下配置檔案分塊的方法,下面這個才起作用:
br />"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
">
- <struts>
- <package name="example" namespace="/example" extends="struts-default">
- <action name="HelloWorld" class="example.HelloWorld">
- <result>/example/HelloWorld.jspresult>
- action>
- <action name="Login!*" method="{1}" class="example.Login">
- <result name="input">/example/Login.jspresult>
- <result type="redirect-action">Menuresult>
- action>
- <action name="*" class="example.ExampleSupport">
- <result>/example/{1}.jspresult>
- action>
- <!-- Add actions here -->
- package>
- struts>
4,錄入驗證:Login-validation.xml
這個很象struts1.x
- /span>
- "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
- ">
- <validators>
- <field name="username">
- <field-validator type="requiredstring">
- <message key="requiredstring"/>
- field-validator>
- field>
- <field name="password">
- <field-validator type="requiredstring">
- <message key="requiredstring"/>
- field-validator>
- field>
- validators>
5.建立資原始檔package.properties,這個也很象struts1.x
- HelloWorld.message= Struts is up and running ...
- requiredstring = ${getText(fieldName)} is required.
- password = Password
- username = User Name
- Missing.message = This feature is under construction. Please try again in the next interation.
6.搞個action類,和WW2一模一樣:
- package example;
- public class Login extends ExampleSupport {
- public String execute() throws Exception {
- if (isInvalid(getUsername())) return INPUT;
- if (isInvalid(getPassword())) return INPUT;
- return SUCCESS;
- }
- private boolean isInvalid(String value) {
- return (value == null || value.length() == 0);
- }
- private String username;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- private String password;
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
7.搞個helloworld類,也和WW2一樣:
這裡呼叫了資原始檔中的 message, 這裡比struts1.X類似功能要直接,會好用一些
- package example;
- /**
- * <code>Set welcome message.code>
- */
- public class HelloWorld extends ExampleSupport {
- public String execute() throws Exception {
- setMessage(getText(MESSAGE));
- return SUCCESS;
- }
- /**
- * Provide default valuie for Message property.
- */
- public static final String MESSAGE = "HelloWorld.message";
- /**
- * Field for Message property.
- */
- private String message;
- /**
- * Return Message property.
- *
- * @return Message property
- */
- public String getMessage() {
- return message;
- }
- /**
- * Set Message property.
- *
- * @param message Text to display on HelloWorld page.
- */
- public void setMessage(String message) {
- this.message = message;
- }
- }
8。搞個父類出來,這裡只是演示用,所以空的
ExampleSupport.java
- package example;
- import com.opensymphony.xwork2.ActionSupport;
- /**
- * Base Action class for the Tutorial package.
- */
- public class ExampleSupport extends ActionSupport {
- }
9。可以測試一下了:
- package example;
- import com.opensymphony.xwork2.ActionSupport;
- import com.opensymphony.xwork2.config.entities.ActionConfig;
- import java.util.Map;
- import java.util.Collection;
- import java.util.List;
- public class LoginTest extends ConfigTest {
- public void FIXME_testLoginConfig() throws Exception {
- ActionConfig config = assertClass("example", "Login!input", "example.Login");
- assertResult(config, ActionSupport.SUCCESS, "Menu");
- assertResult(config, ActionSupport.INPUT, "/example/Login.jsp");
- }
- public void testLoginSubmit() throws Exception {
- Login login = new Login();
- login.setUsername("username");
- login.setPassword("password");
- String result = login.execute();
- assertSuccess(result);
- }
- // Needs access to an envinronment that includes validators
- public void FIXME_testLoginSubmitInput() throws Exception {
- Login login = new Login();
- String result = login.execute();
- assertInput(result);
- Map errors = assertFieldErrors(login);
- assertFieldError(errors,"username","Username is required.");
- assertFieldError(errors,"password","Password is required.");
- }
- }
- package example;
- import com.opensymphony.xwork2.ActionSupport;
- import junit.framework.TestCase;
- public class HelloWorldTest extends TestCase {
- public void testHelloWorld() throws Exception {
- HelloWorld hello_world = new HelloWorld();
- String result = hello_world.execute();
- assertTrue("Expected a success result!",
- ActionSupport.SUCCESS.equals(result));
- assertTrue("Expected the default message!",
- hello_world.getText(HelloWorld.MESSAGE).equals(hello_world.getMessage()));
- }
- }
- package example;
- import com.opensymphony.xwork2.ActionSupport;
- import com.opensymphony.xwork2.config.RuntimeConfiguration;
- import com.opensymphony.xwork2.config.entities.ActionConfig;
- import com.opensymphony.xwork2.config.entities.ResultConfig;
- import com.opensymphony.xwork2.config.providers.XmlConfigurationProvider;
- import java.util.Map;
- import java.util.List;
- import org.apache.struts2.StrutsTestCase;
- public class ConfigTest extends StrutsTestCase {
- protected void assertSuccess(String result) throws Exception {
- assertTrue("Expected a success result!",
- ActionSupport.SUCCESS.equals(result));
- }
- protected void assertInput(String result) throws Exception {
- assertTrue("Expected an input result!",
- ActionSupport.INPUT.equals(result));
- }
- protected Map assertFieldErrors(ActionSupport action) throws Exception {
- assertTrue(action.hasFieldErrors());
- return action.getFieldErrors();
- }
- protected void assertFieldError(Map field_errors, String field_name, String error_message) {
- List errors = (List) field_errors.get(field_name);
- assertNotNull("Expected errors for " + field_name, errors);
- assertTrue("Expected errors for " + field_name, errors.size()>0);
- // TODO: Should be a loop
- assertEquals(error_message,errors.get(0));
- }
- protected void setUp() throws Exception {
- super.setUp();
- XmlConfigurationProvider c = new XmlConfigurationProvider("struts.xml");
- configurationManager.addConfigurationProvider(c);
- configurationManager.reload();
- }
- protected ActionConfig assertClass(String namespace, String action_name, String class_name) {
- RuntimeConfiguration configuration = configurationManager.getConfiguration().getRuntimeConfiguration();
- ActionConfig config = configuration.getActionConfig(namespace, action_name);
- assertNotNull("Mssing action", config);
- assertTrue("Wrong class name: [" + config.getClassName() + "]",
- class_name.equals(config.getClassName()));
- return config;
- }
- protected ActionConfig assertClass(String action_name, String class_name) {
- return assertClass("", action_name, class_name);
- }
- protected void assertResult(ActionConfig config, String result_name, String result_value) {
- Map results = config.getResults();
- ResultConfig result = (ResultConfig) results.get(result_name);
- Map params = result.getParams();
- String value = (String) params.get("actionName");
- if (value == null)
- value = (String) params.get("location");
- assertTrue("Wrong result value: [" + value + "]",
- result_value.equals(value));
- }
- public void testConfig() throws Exception {
- assertNotNull(configurationManager);
- }
- }
哦,測試透過!
10。看看錶示層是如何用的?
HelloWorld.jsp
- <%@ page contentType="text/html; charset=UTF-8" %>
- <%@ taglib prefix="s" uri="/struts-tags" %>
- <html>
- <head>
- <title><s:text name="HelloWorld.message"/>title>
- head>
- <body>
- <h2><s:property value="message"/>h2>
- <h3>Languagesh3>
- <ul>
- <li>
- <s:url id="url" action="HelloWorld">
- <s:param name="request_locale">ens:param>
- s:url>
- <s:a href="%{url}">Englishs:a>
- li>
- <li>
- <s:url id="url" action="HelloWorld">
- <s:param name="request_locale">ess:param>
- s:url>
- <s:a href="%{url}">Espanols:a>
- li>
- ul>
- body>
- html>
Login.jsp
- <%@ page contentType="text/html; charset=UTF-8" %>
- <%@ taglib prefix="s" uri="/struts-tags" %>
- <html>
- <head>
- <title>Sign Ontitle>
- head>
- <body>
- <s:form action="Login">
- <s:textfield label="%{getText('username')}" name="username"/>
- <s:password label="%{getText('password')}" name="password" />
- <s:submit/>
- s:form>
- body>
- html>
恭喜你! 現在您現在已經可以用STRUTS2進行開發了!
[@more@]來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/631872/viewspace-919765/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- XPATH的簡單例子單例
- 一個簡單例子教會你C++動態庫的用法單例C++
- WITH的簡單用法
- java爬蟲簡單例子——附jsoup的select用法詳解Java爬蟲單例JS
- Websocket簡單例子Web單例
- JNI 簡單例子單例
- HttpClient 簡單例子HTTPclient單例
- TensorFlow 的簡單例子單例
- Promise的簡單用法Promise
- Spark Stream 簡單例子Spark單例
- 擼一個簡單的MVVM例子MVVM
- UTL_FILE包的簡單例子單例
- Spark SQL 最簡單例子SparkSQL單例
- 簡單的整合 shiro + SpringMVC 例子SpringMVC
- 一個最簡單的 Github workflow 例子Github
- 一個簡單的觀察者模式例子模式
- smack和openfire通訊的簡單例子Mac單例
- 一個簡單的Ajax請求例子
- getComputedStyle的簡單用法
- javascript的this用法簡單介紹JavaScript
- execute immediate的簡單用法(oracle)Oracle
- android:ListView 的簡單用法AndroidView
- Matplotlib1.簡單例子單例
- web到service簡單原理例子Web
- LRU演算法簡單例子演算法單例
- 尋struts連oracle簡單例子Oracle單例
- golang flag簡單用法Golang
- mysqldumpslow簡單用法MySql
- WebRTC:一個視訊聊天的簡單例子Web單例
- 一個簡單的例子教會您使用javapJava
- 一個簡單的spring-boot例子Springboot
- 一個簡單的例子帶你理解HashmapHashMap
- EBS提交併發請求的簡單例子單例
- Spring定時任務的簡單例子Spring單例
- 一個閉包函式的簡單例子函式單例
- 關於XML序列化的簡單例子XML單例
- 一個簡單的netty通訊的例子Netty
- linux下mail的簡單用法LinuxAI