1.下载相关jar包
进入download页面,下载Struts-x.x.xx-min-lib.zip包。
2.创建web项目
2.1 用Eclipse创建Dynamic Web Project
Runtime可以配置tomcat的版本、路径、jre包
Dynamic web module version 选择的是servlet版本
src存放资源文件 class存放编译后的文件 一般用默认配置
WebModules页面 最好选择上默认生成web.xml选项
2.2 引用相关jar包
step1 把这些jar包放在自己指定的lib目录中,如D:\develop\external_libs\struts-2.3.32
step2 项目引用
右击项目名称->properties->Java Build Path->Libraries
Add External JARS->项目名称->D:\develop\external_libs\struts-2.3.32
选中目录下所有的jar包,确定
fileupload上传下载包
io包
lang包
logging日志包
freemarker 模板引擎
core核心包
xwork包 有些类基于此包实现的
ognl 可以理解为el表达式
assit包 解析Java类的包
3. 创建并完善相关配置文件
3.1 在src中创建Struts的核心配置文件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>
</struts>
3.2 配置web.xml
web项目在启动tomcat时,第一个加载的文件是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>
CTRL+单击 filer-class的名字出现链接代表能够找到这个filter,否则可能是名字写错了
4. 创建Action并测试启动
4.1 创建Action
新建一个类new class
填写package包名如:com.hello.action
填写Name如:HelloWorld
Superclass:搜索ActionSupport,选择项目中的ActionSupport类继承
shift+alt+s 选则Override and implement method重写execute()方法
package com.hello.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {
@Override
public String execute() throws Exception {
System.out.println("执行Action");
return SUCCESS;
}
}
4.2 在struts.xml配置文件中配置映射
1.先配置包名、命名空间、扩展
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="helloworld" class="com.imooc.action.HelloWorld">
<result>/result.jsp</result>
</action>
</package>
</struts>
2.新增result.jsp
这样就成功创建了action和视图
3.发布
右击项目 Debug as->Debug on Server
此时访问http://localhost:8080/hello/helloworld.action
就能看到result.jsp页面
struts.xml中的属性及其描述
属性 描述
name(必需) 为package的唯一标识
extends 指定package继承另一package的所有配置。通常情况下,我们使用struts-default作为package的基础。
abstract 定义package为抽象的。如果标记为true,则package不能被最终用户使用。
namespace Actions的唯一命名空间