在本章節(jié)的學習中,我們會再次使用Struts2 類型轉換章節(jié)中給出的示例,但需要稍作修改。我們可以考慮使用下面的POJO類Environment.java進行類的創(chuàng)建。
package cn.w3cschool.struts2; public class Environment { private String name; public Environment(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }創(chuàng)建以下action類:
package cn.w3cschool.struts2; import com.opensymphony.xwork2.ActionSupport; public class SystemDetails extends ActionSupport { private Environment environment = new Environment("Development"); private String operatingSystem = "Windows XP SP3"; public String execute() { return SUCCESS; } public Environment getEnvironment() { return environment; } public void setEnvironment(Environment environment) { this.environment = environment; } public String getOperatingSystem() { return operatingSystem; } public void setOperatingSystem(String operatingSystem) { this.operatingSystem = operatingSystem; } }
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>System Details</title> </head> <body> <p>The environment name property can be accessed in three ways:</p> (Method 1) Environment Name: <s:property value="environment.name"/><br/> (Method 2) Environment Name: <s:push value="environment"> <s:property value="name"/><br/> </s:push> (Method 3) Environment Name: <s:set name="myenv" value="environment.name"/> <s:property value="myenv"/> </body> </html>現(xiàn)在,我們逐個過一下三個標簽選項:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="system" class="cn.w3cschool.struts2.SystemDetails" method="execute"> <result name="success">/System.jsp</result> </action> </package> </struts>你的web.xml應該如下所示:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>現(xiàn)在,右鍵單擊項目名稱,然后單擊“Export”> “WAR File”以創(chuàng)建WAR文件。然后在Tomcat的webapps目錄中部署WAR文件。最后,啟動Tomcat服務器并嘗試訪問URL http://localhost:8080/HelloWorldStruts2/system.action,將顯示以下界面:
更多建議: