struts2:图解action之HelloWorld示范(从action转到JSP)

虽然Struts 2.x的Action在技术上不需要实现任何接口或继承任何类型,但是,大多情况下我们都会出于方便的原因,使Action类继承com.opensymphony.xwork2.ActionSupport类,并重载(Override)此类里的String execute()方法以实现相关功能。

本文是一个HelloWorld级别的action示范程序。

1. 修改web.xml

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

加入上述代码的作用是添加过滤器,拦截所有请求,将由struts来处理;具体由下面的struts.xml配置决定。

2. 创建struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">
    
<struts>

    <constant name="struts.action.extension" value="action"></constant>
</struts>

注意:

  • 此文件存放于WEB-INF/classes目录下面。
  • 最后一行为我本机环境加入的,含义是只拦截后缀为action的请求。

3. 在struts.xml配置文件中注册Action和result

    <package name="myStruts" extends="struts-default">
            <action name="hello" class="com.clzhang.ssh.demo.action.HelloAction"> 
                <result>/ssh/demo1/hello.jsp</result> 
            </action>      
    </package>

action的name决定调用时的名称;class为实现类名;result的值为action执行完成后转向何页面。如果没有为result指定name名称,默认值为success

4. 创建action处理类

package com.clzhang.ssh.demo.action;

import java.util.Date;
import java.text.SimpleDateFormat;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {
    private String message;

    public String getMessage() {
        return message;
    }

    @Override
    public String execute() {
        message = "Hello there, now is: "
                + new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date());

        return SUCCESS;
    }
}

关于ActionSupport类的更多内容,请参考:http://struts.apache.org/release/2.0.x/struts2-core/apidocs/index.html?overview-summary.html

5. 创建显示JSP文件

<%@page contentType="text/html; charset=UTF-8"%> 
<%@taglib prefix="s" uri="/struts-tags"%> 
<html> 
<head> 
    <title>Hello there!</title> 
</head> 
<body> 
    <h2><s:property  value="message"/></h2> 
</body> 
</html> 

JSP文件中用到了struts标签,以后的章节中会详细描述。

6. 打开IE,测试

输入地址:http://127.0.0.1:8080/st/hello.action,回车结果为:

Hello there, now is: 2013-11-18 11:13

图解:

原文地址:https://www.cnblogs.com/nayitian/p/3429071.html