1.<constant name="struts.devMode" value="true"/>
value="true"表示在开发时改写代码立即生效
2.<package name="front" extends="struts-default" namespace="/">
<action name="index" class="com.bjsxt.struts2.front.action.IndexAction1">
<result name="success">/ActionIntroduction.jsp</result>
</action>
</package>
访问路径为:http://localhost:8080/Struts2_0300_Action/index
访问路径中不需要package的name,直接是:...+...+项目名称+命名空间+action的name
result的name默认是success,name值用于根据class返回值来选择result
这里class指定的类有execute函数,返回一个String,例如:“success”,用于选择result
3.action中的class有三种写法:
(1) public class IndexAction1 {
public String execute() {
return "success";
}
}
(2) import com.opensymphony.xwork2.Action;
public class IndexAction2 implements Action {
public String execute() {
return "success";
}
}
(3) import com.opensymphony.xworks.ActionSupport;
public class IndexAction3 extends ActionSupport {
public String execute() {
return "success";
}
}
第三种方法最好,ActionSupport帮我们封装了很多方法供使用
4. <package name="front" extends="struts-default" namespace="/">
<action name="index" class="com.bjsxt.struts2.front.action.IndexAction1" method="add">
<result name="success">/ActionIntroduction.jsp</result>
</action>
</package>
如果写method代表指定函数add()
如果不写method,且需要指定调用IndexAction1中的add()方法,访问路径中写...+...+项目名称+/+index!add,这就是动态方法调用DMI
5. 访问路径问题,在JSP中添加<base href="<%=basePath%>" />,在其他访问地址中只需写jsp文件名和后缀名即可如:
<base href="<%=basePath%>" />
<a href="index.jsp">index.jsp</a>
6. 通配符问题,在action中,name可能存在不确定的值,如student*,或者*_*,那么{1},{2}就表示其未显示的部分,class、method、result等中都可以用{1}和{2}来表示未显示部分。
如:<action name="student*" class="......" method="{1}">
<result>/Student{1}_success.jsp</result>
</action>
<action name="*_*" class="com.bjsxt.struts2.action.{1}Action">
<result>/{1}_{2}_success.jsp</result>
</action>
7. 用Action的属性接受参数,例如add()方法中传参name和age
http://localhost:8080/Struts2_0700_ActionAttrParamInput/user/user!add?name=aa&age=8
8. 用DomainModel接收参数,访问路径中写
http://localhost:8080/Struts2_0700_ActionAttrParamInput/user/user!add?user.name=aa&user.age=8
其中user是name为user的action对应的class(userAction)中的一个属性,其也是一个对象,里面有很多属性,如name和age
9. 一般情况下解决中文问题需要加<constant name="struts.i18n.encoding" value="GBK" />
10. 模块包含,struts配置文件struts.xml包含别的struts配置文件login.xml中的内容
直接在struts.xml中写<include file="login.xml" />
11. 简单数据验证,在action的class中对传入的参数进行判断,如下:
public String add() {
if(name==null||!name.equals("admin")) {
this.addFieldError("name","name is error");
return ERROR;
}
return SUCCESS;
}
在jsp文件中取这个name的值,方法:
先引入标签<%@taglib uri="/struts-tags" prefix="s" %>
然后取值<s:fielderror fieldName="name"/>
12. result类型,根据不同的type来用不同的方式返回结果
主要用两种:
<action name="r1">
<result type="dispatcher">/r1.jsp</result> <!--服务器端跳转-->
</action>
<action name="r2">
<result type="redirect">/r2.jsp</result> <!--客户端跳转-->
</action>
13. global-results全局结果集
<global-results>
<result name="mainpage">/main.jsp</result>
</global-results>
如果一个package中需要用另一个package中的内容,则需要继承,那么在packge行写上<package name=".." namespace=".." extends="user(被继承的package名称)">