Struts2 HelloWorld!

1. HelloWorld 简介

此Demo基于当前最新的 Struts2.3.28 开发,采用注解方式进行 Action 映射,旨在说明一个最简单的 Struts2 应用的基本开发步骤和相关注意点。

2. 准备工作

  1. 去官网下载 Struts2 的最新版本,地址:http://struts.apache.org/,当前最新版本为 Struts2.3.28,建议下载 Full Distribution(完整版选项),该选项包括 Struts2 的示例应用、核心库、源代码和文档等。
  2. 使用 Eclipse 搭建最简单的 Dynamic Web Project,Servlet 版本 2.5/3.0 均可,主要是一定要生成 web.xml 文件;Tomcat 版本 6/7 均可。

3. Struts2 必备 JAR 包

Struts2 最少 JAR 包列表

这是本人测试的最少 JAR 包,其中:

  • struts2-convention-plugin-2.3.28.jar 是用于注解的,如果是基于配置文件开发,可省略此包,建议使用注解。
  • struts2-config-browser-plugin-2.3.28.jar 是用于查看 Struts2 的相关信息的,仅方便开发时调试,对工程本身没有任何作用,可省略此包。关于此插件的用法,详见:Config Browser 插件

4. 为 Web 应用增加 Struts2 支持

  1. 将上述包全部添加到 /WebContent/WEB-INF/lib 目录下
  2. 在 web.xml 文件中 <web-app> 标签下添加 Struts2 的默认 Filter,代码如下:
<!--
    为 Web 应用增加 Struts2 默认的 filter。
    在 Struts2.0.x 版本时,使用的是org.apache.struts2.dispatcher.FilterDispatcher,从 2.1.x 版本开始,均使用如下的 filter。
    对于 2.0.x 版本,其注解是通过 codebehind-plugin 实现的,使用注解映射 Action 时,需要为 filter 配置如下初始化参数:
    <init-param>
        <param-name>actionPackages</param-name> 参数名是固定的
        <param-value></param-value> 指定 Struts2 搜索含有注解的 Action 类的包名
    </init-param>
    如果不指定需要搜索的包,会出现 404 错误。
    对于 2.1.x+版本,注解是通过 convention-plugin 实现的,无需添加上述初始化参数,该插件有自己的使用方式
-->
<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>

其中:Convention 插件相关说明详见:Convention 插件(1)

5. 定义处理用户请求的 Action 类

/**
 * 实现 Action 接口还是继承 ActionSupport 类
 *  ActionSupport 类也是 Action 接口的实现,
 *  不过它在 Action 的基础上进行了扩展,其功能更加强大,
 *  虽然两者都可以,但开发时建议继承 ActionSupport 类
 */
@Namespace("/demo")
@ParentPackage("struts-default")
public class HelloWorldAction extends ActionSupport {
    @Action(value = "HelloWorld", results = { @Result(location = "/index.jsp") })
    public String helloWorld() throws Exception {
        System.out.println("欢迎使用 Struts2!");
        return SUCCESS;
    }
}

其中:注解相关说明详见:Convention 插件(2)– Annotation

6. 定义物理视图资源

在 /WebContent 目录下新建 index.jsp 文件,内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
    Hello World!
</body>
</html>

7. 发布、访问

将完整工程发布至 Tomcat,启动 Tomcat,输入访问 URL:http://localhost:8080/Struts2/demo/HelloWorld.action,即可看到浏览器中显示 “Hello World!”

最终项目的文件结构如下图:

Struts2 HelloWorld 项目结构图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值