零配置
S truts使用Convention Plugin实现零配置,需要导入org.apache.struts.jar包,默认下包含action的包名应该以action结尾,才能够扫描的出来。
Action配置
1.Action默认的映射
package com.example.actions.text;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
public String execute() {
return SUCCESS;
}
}
匹配URL 应用/命名空间/处理过的类名
上例匹配URL 应用/text/hello-world
显示资源路径在WEB-INF/content/下,匹配的具体资源和返回只有关,具体参看docs文档
说明:
默认情况下只有实现了Action接口的类才能算是Action
默认情况下匹配的类名去除类名后面的action,单词和单词之间用"-"连接,大写转化为小写。
这些配置在Convention Plugin配置中可以更改。
2.使用@Action配置
package com.example.actions.textspace;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
public class HelloWorld extends ActionSupport {
@Action("/different/url")
//这里给出了Namespace,默认的包名Namespace不可用了。
public String execute() {
return SUCCESS;
}
@Action("url")
//这里没有给出Namespace,默认是包名的Namespace。匹配URL textspace/url
public String doSomething() {
return SUCCESS;
}
}
3.chain连锁反应
package com.example.actions;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport {
@Action("foo")
public String foo() {
return "bar";
}
@Action("foo-bar")
public String bar() {
return SUCCESS;
}
}
当action执行后找不到返回的result,就会在包下找 Action名-返回值 的Action,
如果找到了就执行,要想连锁反应发生,本例中WEB-INF/content/foo-bar.jsp不能存在。
Result配置(Exception配置 InterceptorRef配置 )
1.全局Result
在类层面上配置2.局部Result
在Action里面配置Namespace配置
package com.example.actions;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
@Namespace("/custom")
//用在类层面上Namespace对所有的Action都有用,
public class HelloWorld extends ActionSupport {
@Action("/different/url")
//对于这个Action有URL匹配,/differnt/url
public String execute() {
return SUCCESS;
}
@Action("url")
//这个只有URL匹配 /custom/url
public String doSomething() {
return SUCCESS;
}
}
类似于一种就进原则,
其他相关
ResultPath annotation
设置Result默认路径,默认为WEB-INF/content/当@Result(location="a.jsp") 会去 应用名/WEB-INF/content/名称空间/a.jsp中查找。
设置@ResultPath("/") 就会去 应用名/名称空间/a.jsp
ParentPackage annotation
配置Action继承的父包。自动加载配置文件不用重启服务器
<constant name="struts.devMode" value="true"/><constant name="struts.convention.classes.reload" value="true" />