从struts2.1开始,struts2不再推荐使用Codebehind作为零配置插件,而是改为使用Convention插件来支持零配置,和Codebehind相比,Convention插件更彻底,该插件完全抛弃配置信息,不仅不需要是使用struts.xml文件进行配置,甚至不需要使用Annotation进行配置,而是由struts2根据约定自动配置。
第一步:引入struts2-convention-plugin包(asm和asm-commons包也需要引入,这几个包都在struts的lib中)到lib中
第二步:配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>config</param-name>
<param-value>struts-default.xml,struts-plugin.xml,/resources/struts.xml</param-value>
</init-param>
<init-param>
<param-name>actionPackages</param-name>
<param-value>action</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
其中标红的部分标书需要配置供StrutsPrepareAndExecuteFilter扫描注解建立ActionMapper的package。
第三步:编写Action类
/**
*
*/
package action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import com.opensymphony.xwork2.ActionSupport;
/**
* @author yfei
*
*/
@Namespace(value = "/login")
@ParentPackage("struts-default")
public class LoginAction extends ActionSupport {
private String userName;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Action(results = {
@Result(name = "success", location = "/login/success.jsp") },
value = "loginAction",params={"password","123"})
public String login() {
System.out.println("userName========" + userName);
System.out.println("password========" + password);
System.out.println("in here");
return SUCCESS;
}
}
这样,在浏览器地址栏里访问http://host:port/app/login/loginAction.action?userName=sdf 就可以了。输出结果为:
userName========sdf
password========123
in here
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<!-- 修改默认的后缀 -->
<constant name="struts.action.extension" value="do,action"></constant>
</struts>
现在,不管是那个框架,都在普及annotation,已达到减少配置文件的目的。spring和hibernate集成中的hibernate.cfg.xml配置文件也可以通过annotation注解来实现(具体参考 http://blog.csdn.net/yfei_sjq/article/details/9345343)。