您的位置:首页 > 编程语言 > Java开发

Struts2 HelloWorld!

2016-05-22 13:18 656 查看
HelloWorld 简介

准备工作

Struts2 必备 JAR 包

为 Web 应用增加 Struts2 支持

定义处理用户请求的 Action 类

定义物理视图资源

发布访问

1. HelloWorld 简介

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

2. 准备工作

去官网下载 Struts2 的最新版本,地址:http://struts.apache.org/,当前最新版本为 Struts2.3.28,建议下载 Full Distribution(完整版选项),该选项包括 Struts2 的示例应用、核心库、源代码和文档等。

使用 Eclipse 搭建最简单的 Dynamic Web Project,Servlet 版本 2.5/3.0 均可,主要是一定要生成 web.xml 文件;Tomcat 版本 6/7 均可。

3. Struts2 必备 JAR 包



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

struts2-convention-plugin-2.3.28.jar 是用于注解的,如果是基于配置文件开发,可省略此包,建议使用注解。

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

4. 为 Web 应用增加 Struts2 支持

将上述包全部添加到 /WebContent/WEB-INF/lib 目录下

在 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