1 开发环境的配置:
1.1 导包
1.2 书写Action类
public class HelloAction {
public String hello() {
System.out.println("hello world!");
return "success";
}
}
1.3 书写src/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 >
<package name="hello" namespace="/hello" extends="struts-default" >
<action name="HelloAction" class="com.dlj.hello.HelloAction" method="hello">
<result name="success" >/hello.jsp</result>
</action>
</package>
</struts>
1.4 将struts2核心过滤器配置到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>
1.5 访问
http://localhost:8080/struts2_day01/hello/HelloAction
详细过程如下:
2 配置详解
2.1 struts.xml配置详解
1 package :将Action配置封装,就是可以在Package中配置很多action
- name属性:给包起个名字,起到标识作用,随便起,但是不能冲突
- namespace属性:给action的访问路径中定义一个命名空间
- extends属性:继承一个指定包
- abstract属性:包是否为抽象的,标识该包不能独立运行,专门被继承
2 Action属性配置
- name属性:决定了Action访问资源名
- class属性:Action的完整类名
- method属性:指定调用Action中的哪个方法来处理请求
3 result
- name属性:标识结果处理的名称,与action方法的返回值对应
- type属性:指定调用哪一个result类来处理结果,默认使用转发
4include<include file="com/dlj/dynamic/struts.xml"></include>
用来引入其他文件夹下的struts2配置文件
2.2 struts2默认常量配置
默认常量配置位置
修改方式
方式一:通过src/struts.xml修改
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
方式二:通过在src下创建strtus.properties文件进行配置
struts.i18n.encoding=UTF8
方式三:在项目的web.xml中配置
<context-param>
<param-name>struts.i18n.encoding</param-name>
<param-value>UTF-8</param-value>
</context-param>
这也是加载的先后顺序,也就是说后配置的会覆盖之前的配置
常用的常量:
struts.i18n.encoding=UTF-8 //解决post提交乱码
struts.action.extension=action,, //指定访问action时的后缀名,注意后面的两个逗号不能省略,默认情况为空,或者.action
struts.devMode = false //指定struts2开发模式运行,热加载主配置(不需要重启即可生效),提供更多错误信息,方便开发时调试
动态方法调用
有两种方式:
方式一:不配method属性,然后配置动态方法调用常量,设置struts.enable.DynamicMethodInvocation = true,默认是关闭的。
上面这个方式不推荐使用
方式二:通配符调用,使用表达式,{1}匹配星号所对应内容
2.3 struts2默认值
**action的method属性:**默认值是execute,也就是说不配置method属性的时候,默认找execute方法。
**action的class属性:**com.opensymphony.xwork2.ActionSupport
**result的name属性:**默认值是success
**result的type属性:**默认是dipatcher
**default-action-ref:**用来配置当输入的action找不到时,默认的找哪个action
2.5 struts2Action的创建方式
方式一:创建一个类可以是POJO(不用继承任何父类,也不需要实现任何接口,使struts2框架的代码侵入性更低)
方式二:实现一个Action接口,里面有execute方法,提供action方法的规范,Action接口预置了一些字符串。
方式三:继承ActionSupport类,它帮我们实现了很多接口