1.通过maven依赖引入Struts2需要的关键jar包,包括:
struts-core-2.3.24.jar :struts2核心框架包
xwork-core-2.3.24.jar:xwork类库,struts2架构在其基础之上
freemarker-2.3.22.jar:struts2 UI标签的模版是用freemarker做的
ognl-3.0.6.jar :对像图导航语言(刚开始学struts2 还不知道其具体用法)
commons.io-2.2.jar
2.web.xml配置
<web-app>
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
<!-- 如果struts.xml文件放在classes目录下,则不需要以下红色部分,可以将struts-constant.xml中的
常量配置合并到struts.xml中-->
<!-- 如果struts.xml是按照classesstruts/struts.xml路径来存放的则需要增加以下红色部分,同时struts- default.xml,struts-plugin.xml也必须要添加-->
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,struts/struts.xml,struts/struts-constant.xml
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
注意点:
1).若设置了<param-name>config</param-name>参数,那struts-default.xml等原来struts2默认加载的文件也要手动指定,否则
不会自动加载
2). struts-plugin.xml也需要指定。因为在struts2使用2.1.6版本时:
若需要和spring集成的话,struts2-spring-plugin-2.1.6.jar中有struts-plugin.xml这个文件。
若struts2要支持json的话, json-plugin-0.34.jar中也有一个叫struts-plugin.xm的文件。
因此这个文件也是要加载的。
3). 若不在这里配置struts-default.xml,struts-plugin.xml,也可以在struts.xml文件中添加include标签将两个文件包括进去。
<include file="struts-default.xml" />和<include file="struts-plugin.xml" />
4).struts/struts-constant.xml用来配置struts2的常量。
为了支持 http://localhost:8080/struts-test/test/login!list.action(动态方法)方式请求,需要增加
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
此处struts2还提供了很多常量配置,可以参考struts2的官方文档
3.struts.xml配置
新建HelloWorld.java
public class HelloWorld extends ActionSupport{
public String login() throws Exception
{
System.out.println("login方法");
return "login";
}
public String list() throws Exception{
System.out.print("list 方法");
return "list";
}
1)动态方法配置:
<struts>
<package name="default" namespace="/test" extends="struts-default">
<action name="login" class="HelloWorld" >
<result name="login">/index.jsp</result>
<result name="list">/index.jsp</result>
</action>
</package>
</struts>
访问路径:http://localhost:8080/struts-test/test/login!list.action 此URL请求的是HelloWorld中的list方法
2)一般常规配置
<result name="login">/index.jsp</result>
</action>
<action name="hello_list" class="HelloWorld" method="list" >
<result name="list">/index.jsp</result>
</action>
请求路径:http://localhost:8080/struts-test/test/hello_list
注:此配置方式的缺点是需要配置太多个action标签