struts2 convention-plugin实现零配置

零配置并不是没有配置,而是通过约定大于配置的方式,大量通过约定来调度页面的跳转而使得配置大大减少。使得Action等配置不必写在Struts.xml中。

convention-plugin的约定

1. 默认所有的结果页面都存储在WEB-INF/content下,你可以通过设置struts.convention.result.path这个属性的值来改变到其他路径。

 <constant name="struts.convention.result.path" value="/WEB-INF/page" />  

2. 默认包路径包含action,actions,struts,struts2的所有包都会被struts作为含有Action类的路径来搜索。

你可以通过设置struts.convention.package.locators属性来修改这个配置。

<constant name="struts.convention.package.locators" value="web,action" /> 
<!--包路径包含web和action的将被视为Action存在的路径来进行搜索。-->

3.Convention 从找到的package以及其子package中寻找 com.opensymphony.xwork2.Action 的实现以及以Action结尾的类

com.example.actions.MainAction  
com.example.actions.products.Display (implements com.opensymphony.xwork2.Action)  

4.Convention通过如下规则确定URL的具体资源部分:去掉类名的Action部分。然后将将每个分部的首字母转为小写,用’-’分割

可以自定义分隔符:

<constant name="struts.convention.action.name.separator" value="-" />  

举例:

  • UserAction->user 
  • UserDetailAction ->user-detail
  • com.ustb.web.user.detail.UserDetailAction ->/WEB-INF/content/user/detail/user-detail.jsp

通过注解来配置

一个方法被@Action注释后,只是多了一种调用方式,而不是说覆盖了原来的调用方式

public class HelloAction extends ActionSupport {  
    @Action("action1")
    //调用路径:/action1!method1.action
    //映射路径: /WEB-INF/content/action1.jsp
    public String method1() {  
        return SUCCESS;  
    }  
    //调用路径:/user/action2!method2.action
    //映射路径: /WEB-INF/content/user/action2.jsp
    @Action("/user/action2")  
    public String method2() {  
        return SUCCESS;  
    }  
}

@Actions注释

public class HelloAction extends ActionSupport {  
  //可以通过两种路径调用注释方法,会映射到对应的文件
  @Actions({  
    @Action("/different/url"),    //调用:/different/url!method1.action 映射:/WEB-INF/content/different/url-error.jsp
    @Action("/another/url")      //调用:/another/url!method1.action 映射:/WEB-INF/content/another/url-error.jsp
  })
  public String method1() {  
    return “error”;  
  }  

@Namespace 注释

@Namespace("/other")  //记得加斜杠
public class HelloWorld extends ActionSupport {  
    // 调用:/other/hello-world!method1.action 
    public String method1() {  
        return “error”;  
    }  
    @Action("url")
    // 调用:/other/url!method2.action   
    public String method2() {  
        return “error”;  
    }  
    @Action("/different/url")  
    // 调用:/different/url!method3.action  
    public String method3() {  
        return “error”;  
    }  
}  

@Result注释

public class HelloWorld extends ActionSupport {  
    @Action(
        value="test01",
        results={
            @Result(
                name="error",
                location="/pages/test01/say-hello.jsp",
                params={
                    "param1","${param1}",    
                    "param2","${param2}"
                }
            )
        }
    )
    public String AgentLogin() throws Exception{
    
    }
} 
原文地址:https://www.cnblogs.com/DajiangDev/p/3384709.html