1、原理
可参考:http://blog.csdn.net/laner0515/article/details/27692673/ 、 http://blog.csdn.net/wuwenxiang91322/article/details/11070513
2、第一个项目——HelloWorld
(1)步骤:
①建立web项目,拷贝struts-2.5.10.1-min-lib/lib中的jar包。还需添加一个log4j-core
②在web.xml中配置Struts2的前端控制器-StrutsPrepareAndExecuteFilter
③定义一个POJO类:HelloAction
public class HelloAction {
public String sayHello(){
System.out.println("Hello World!");
//返回逻辑视图
return "success";
}
}
④拷贝struts.xml文件到项目的类路径或资源文件中,文件名不能修改
但可以针对每个action类设定一个struts的xml配置文件,该文件可改名字
但是在struts.xml配置文件中需要引入该配置文件
<include file="\action\helloworld\struts-hello.xml"></include>
⑤在struts.xml文件中,配置HelloAction.(把HelloAction交给Struts框架管理)
⑥访问Action
协议+主机地址+端口号+上下文路径+命名空间(namespace)+资源名称(action name)
3、Struts2中的6大配置文件
(1)Struts2框架按照如下顺序加载struts2配置:
①default.properties 该文件保存在 struts2-core-2.5.10.1.jar 中 org.apache.struts2包里面:包含了Struts2的默认常量配置
②struts-default.xml 该文件保存在 struts2-core-2.5.10.1.jar:包含了框架依赖的对象配置和结果类型,拦截器等配置.
③struts-plugin.xml 该文件保存在Struts2框架的插件中:struts-Xxx-2.5.10.1.jar.由插件提供
上述三个文件时框架自带的,不能修改,只能使用。
---------------------------------------------------------
④struts.xml 该文件是web应用默认的struts配置文件.重点.配置自定义的Action和其他信息.
⑤struts.properties 该文件是Struts的默认配置文件-->可以修改default.properties 的常量配置.
⑥web.xml 该文件是Web应用的配置文件
上述三个文件是可以修改操作的。
---------------------------------------------------------
如果多个文件配置了同一个struts2 常量,则后一个文件中配置的常量值会覆盖前面文件配置的常量值.
注意:一般在struts.xml中做常量配置.
4、常见常量配置
(1)指定默认编码集,作用于HttpServletRequest的setCharacterEncoding方法和freemarker 、velocity的输出
<constantname="struts.i18n.encoding" value="UTF-8"/>
(2)指定需要Struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开
<constant name="struts.action.extension" value="action,,"/>(3)开发模式下使用,这样可以打印出更详细的错误信息
<constant name="struts.devMode" value="true" />:修改struts.xml之后,不需要重启Tomcat.
5、struts.xml配置文件元素详解
(1)package元素—— <struts>根元素的子元素
用来对多个<action>元素分类管理,和Java中的package没有关系.
①常见的属性:
name: <package>的名字
extends: 表示当前<package>继承哪一个<package>,一般都是:struts-default。而struts-default其实就是struts-default.xml中<pac