前言
struts2配置action类访问路径的时候,可以采用@Action(value="")这样的注解,当然也可以不配置这个注解。假如不配置的时候,默认的路径是怎么样的呢?
struts2-convention-plugin-2.2.3.jar
用idea打开struts2-convention-plugin-2.2.3.jar的源码,如果是其他ide的,请反编译或者下载这个jar的源码查看。
打开org.apache.struts2.convention.SEOActionNameBuilder类,类注释如下:
<span style="font-size:18px;">/**
* <p>
* This class converts the class name into a SEO friendly name by recognizing
* camel casing and inserting dashes. This also converts everything to
* lower case if desired. And this will also strip off the word <b>Action</b>
* from the class name.
* </p>
*/</span>
根据类注释,可以大概知道一些情况。意思就是奖类名转化为对于SEO来说友好的名称,通过识别驼峰法命名和插入连接号(“-”),如果需要的话,还会将所有单词转化为小写,并去掉类名当中的“Action“。
源码分析
<span style="font-size:18px;">private static final Logger LOG = LoggerFactory.getLogger(SEOActionNameBuilder.class);
private String actionSuffix = "Action";
private boolean lowerCase;
private String separator;
@Inject
public SEOActionNameBuilder(@Inject(value="struts.convention.action.name.lowercase") String lowerCase,
@Inject(value="struts.convention.action.name.separator") String separator) {
this.lowerCase = Boolean.parseBoolean(lowerCase);
this.separator = separator;
}
/**
* @param actionSuffix (Optional) Classes that end with these value will be mapped as actions
* (defaults to "Action")
*/
@Inject(value = "struts.convention.action.suffix", required = false)
public void setActionSuffix(String actionSuffix) {
if (StringUtils.isNotBlank(actionSuffix)) {
this.actionSuffix = actionSuffix;
}
}</span>
1、后缀可以用struts.convention.action.suffix配置;
2、是否小写和分隔符可以用struts.convention.action.name.lowercase和struts.convention.action.name.separator配置。
3、默认值可以查看struts-plugin.xml配置文件。
<span style="font-size:18px;">public String build(String className) {
String actionName = className;
if (actionName.equals(actionSuffix))
throw new IllegalStateException("The action name cannot be the same as the action suffix [" + actionSuffix + "]");
// Truncate Action suffix if found
if (actionName.endsWith(actionSuffix)) {
actionName = actionName.substring(0, actionName.length() - actionSuffix.length());
}
// Convert to underscores
char[] ca = actionName.toCharArray();
StringBuilder build = new StringBuilder("" + ca[0]);
boolean lower = true;
for (int i = 1; i < ca.length; i++) {
char c = ca[i];
if (Character.isUpperCase(c) && lower) {
build.append(separator);
lower = false;
} else if (!Character.isUpperCase(c)) {
lower = true;
}
build.append(c);
}
actionName = build.toString();
if (lowerCase) {
actionName = actionName.toLowerCase();
}
if (LOG.isTraceEnabled()) {
LOG.trace("Changed action name from [#0] to [#1]", className, actionName);
}
return actionName;
}</span>
1、类名称不能等于后缀;
2、加入类名称是以后缀结尾的,则会去掉后缀字符串;
3、遇到大写字母,会在大写字母前面加入分隔符;
4、根据是否小写配置,决定是否讲所有字符串小写。
例子
AbcdEfg------------------------>abcd-efg
ABcdEfg------------------------>a-bcd-efg