Struts2:在MyEclipse中創建一個簡單的Action2009-04-04 23:30

這是我學Struts2以來的編寫的第一個Action,雖然簡單,但也把我折騰得夠愴的,不過,倒也從中讓我收益良多,至少,讓我對Struts2框架有了比較感性的認識。

首先,在MyEclipse中創建一個web project,我命名為Hello,在Hello工程下的WebRootWEB-INFlib中添加以下幾個Struts2中的包(不用將Struts2中的所有包都添加進來,以下幾個就行),它們分別是commons-logging-1.0.4.jarognl-2.6.11.jartiles-jsp-2.0.4.jarstruts2-core-2.0.9.jarxwork-2.0.4.jarfreemarker-2.3.8.jar

接下來,創建相應的文件並編寫代碼(注意其創建的位置)

helloworld.java(在src文件夾中的example包中)package example;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class helloworld extends ActionSupport{ public String message; //實現execute的方法,為message賦值 public String execute(){ message="hello world!
"; return SUCCESS; } public String getMessage(){ return message; }}

struts.xml(在src文件夾中)<?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" /> <!-- 在包中導入Struts自帶的配置文件struts-default.xml --> <package name="default" extends="struts-default"> <!-- 配置自已定義的Action --> <action name="hello" class="example.helloworld"> <!-- 根據不同的返回字元串類型,跳轉到不同的頁面 --> <result name="success">hello.jsp</result> </action> </package></struts>

hello.jsp<%@ page contentType="text/html;charset=GBK"%><%@ taglib prefix="s" uri="/struts-tags"%><%-- 在這裡用到Struts 2的標籤,需要先導入標籤庫,並為之定義一個前綴 --%>

<html><head> <title>Hello Page</title></head><body> The message generated by my first action is: <%-- 取出Action中對應的message的值 --%> <s:property value="message" /></body></html>

web.xml(默認位置,只是對其配置做修改而已)<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Struts 2 First</display-name> <filter> <filter-name>struts-cleanup</filter-name> <filter-class> org.apache.struts2.dispatcher.ActionContextCleanUp </filter-class> </filter> <filter-mapping> <filter-name>struts-cleanup</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <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>

<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>

</web-app>

最後,在地址欄中輸入http://localhost:8080/Hello/hello.action

如果成功的話,會顯示The message generated by my first action is: hello world!

推薦閱讀:

查看原文 >>
相關文章