Struts2注解配置

1. 必要的jar包:
commons-fileupload-1.2.1.jar
commons-io-1.4.jar
commons-logging-1.1.1.jar
commons-logging-api.jar
freemarker-2.3.15.jar
ognl-2.7.3.jar
struts2-core-2.1.8.1.jar
xwork-core-2.1.6.jar
struts2-convention-plugin-2.1.8.1.jar
其中struts2-convention-plugin-2.x.x.jar是用于支持注解的包


2.web.xml 的配置:

[html]  view plain copy print ?
  1. <filter>   
  2. <filter-name>struts2</filter-name>   
  3. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>   
  4. <init-param>   
  5. <param-name>actionPackages</param-name>   
  6. <param-value>com.test.action</param-value>   
  7. </init-param>   
  8. </filter>   
  9.   
  10. <filter-mapping>   
  11. <filter-name>struts2</filter-name>   
  12. <url-pattern>/*</url-pattern>   
  13. </filter-mapping>  



3. struts.xml 的配置:

[html]  view plain copy print ?
  1. <?xml version="1.0" encoding="UTF-8" ?>   
  2. <!DOCTYPE struts PUBLIC   
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"   
  4.     "http://struts.apache.org/dtds/struts-2.1.7.dtd">  
  5.   
  6. <struts>  
  7.     <!-- 请求参数的编码方式 -->  
  8.     <constant name="struts.i18n.encoding" value="UTF-8" />  
  9.     <!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开 -->  
  10.     <constant name="struts.action.extension" value="action,do,htm" />  
  11.     <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开 -->  
  12.     <constant name="struts.configuration.xml.reload" value="true" />  
  13.     <!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开 -->  
  14.     <constant name="struts.devMode" value="false" />  
  15.     <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭 -->  
  16.     <constant name="struts.serve.static.browserCache" value="false" />  
  17.     <!-- 指定由spring负责action对象的创建  
  18.     <constant name="struts.objectFactory" value="spring" />  
  19.     -->  
  20.     <!-- 是否开启动态方法调用 -->  
  21.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
  22. </struts>  


4. 常用的注解如下:Namespace:指定命名空间。
ParentPackage:指定父包。
Result:提供了Action结果的映射。(一个结果的映射)
Results:“Result”注解列表
ResultPath:指定结果页面的基路径。
Action:指定Action的访问URL。
Actions:“Action”注解列表。
ExceptionMapping:指定异常映射。(映射一个声明异常)
ExceptionMappings:一级声明异常的数组。
InterceptorRef:拦截器引用。
InterceptorRefs:拦截器引用组。


5. 示例代码如下:

那些类会被作为Action,
对于Convention插件而言,它会自动搜索位于action,actions,struts,struts2包下的所有java类,
Convention插件会把如下两种java类当成Action处理
①类名以XXXAction命令。
②继承ActionSuppot。

[java]  view plain copy print ?
  1. package com.tjcyjd.web.action;  
  2.   
  3. import org.apache.struts2.convention.annotation.Action;  
  4. import org.apache.struts2.convention.annotation.ExceptionMapping;  
  5. import org.apache.struts2.convention.annotation.ExceptionMappings;  
  6. import org.apache.struts2.convention.annotation.Namespace;  
  7. import org.apache.struts2.convention.annotation.ParentPackage;  
  8. import org.apache.struts2.convention.annotation.Result;  
  9. import org.apache.struts2.convention.annotation.Results;  
  10.   
  11. import com.opensymphony.xwork2.ActionSupport;  
  12.   
  13. /** 
  14.  * Struts2基于注解的Action配置 
  15.  *  
  16.  */  
  17. @ParentPackage("struts-default")  
  18. @Namespace("/annotation_test")  
  19. @Results({ @Result(name = "success", location = "/main.jsp"),  
  20.         @Result(name = "error", location = "/error.jsp") })  
  21. @ExceptionMappings({ @ExceptionMapping(exception = "java.lange.RuntimeException", result = "error") })  
  22. public class LoginAction extends ActionSupport {  
  23.     private static final long serialVersionUID = 2730268055700929183L;  
  24.     private String loginName;  
  25.     private String password;  
  26.   
  27.     @Action("login")  
  28.     // 或者写成 @Action(value = "login")  
  29.     public String login() throws Exception {  
  30.   
  31.         if ("yjd".equals(loginName) && "yjd".equals(password)) {  
  32.             return SUCCESS;  
  33.         } else {  
  34.             return ERROR;  
  35.         }  
  36.     }  
  37.   
  38.     @Action(value = "add", results = { @Result(name = "success", location = "/index.jsp") })  
  39.     public String add() throws Exception {  
  40.         return SUCCESS;  
  41.     }  
  42.   
  43.     public String getLoginName() {  
  44.         return loginName;  
  45.     }  
  46.   
  47.     public void setLoginName(String loginName) {  
  48.         this.loginName = loginName;  
  49.     }  
  50.   
  51.     public String getPassword() {  
  52.         return password;  
  53.     }  
  54.   
  55.     public void setPassword(String password) {  
  56.         this.password = password;  
  57.     }  
  58. }  


6. 查看struts2配置 
为了看到struts2应用里的Action等各种资源的影射情况,struts2提供了Config Browser插件。 
使用方法:将struts2-config-browser-plugin-2.1.6.jar文件复制到struts2应用的WEB-INF/lib目录中。 
打开首页地址:http://localhost:8080/应用名字/config-browser/actionNames.action 这里可以看到Config Browser插件的首页。


转自:http://blog.csdn.net/bits00/article/details/705258


示例:

package com.struts05.action;


import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.validation.SkipValidation;


import com.actionUtil.ActionUtil;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.pojo.Users;


/**
 * annotation使用:
 * 
 * 导包
 * struts2-convention-plugin-2.3.15.3.jar
 * asm-3.3.jar
 * asm-commons-3.3.jar
 * struts2-config-browser-plugin-2.3.15.3.jar(可选,查看struts2的Action各种资源的映射)
 * 
 * 注意:对于Convention插件而言,它会自动搜索位于action、actions、struts、struts2包下的所有java类.
 * 	   Convention插件会把如下两种java类当成Action处理:
 * 	   1.类名以xxxAction命名
 * 	   2.继承ActionSuppot的类
 * 
 * xml(不是必须配置):
 * <struts>  
 *   <!-- 请求参数的编码方式 -->  
 *   <constant name="struts.i18n.encoding" value="UTF-8" />  
 *   <!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开 -->  
 *   <constant name="struts.action.extension" value="action,do,htm" />  
 *   <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开 -->  
 *   <constant name="struts.configuration.xml.reload" value="true" />  
 *   <!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开 -->  
 *   <constant name="struts.devMode" value="false" />  
 *   <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭 -->  
 *   <constant name="struts.serve.static.browserCache" value="false" />
 *   <!-- 是否开启动态方法调用 -->  
 *   <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
 * </struts>
 * 
 * 常用的注解:
 * @ParentPackage("struts-default"):指定父包
 * @Namespace("/struts05"):指定命名空间
 * @ResultPath("/"):定位资源到指定路径下
 * @Results:指定一组结果集
 * @Result(name="success",location="success.jsp"):指定一个结果集
 * @Action(value="error",results={@Result(name="error",location="error.jsp")}):指定action,建议写在方法上,可以只配value属性,其他引用@Results中结果集
 * @Actions({@Action("login1"),@Action("login2")}):指定一组action,一个方法指定多个action,建议写在方法上,可以只配value属性,其他引用@Results中结果集
 * 指定一组异常:
 * @ExceptionMappings({
 *      @ExceptionMapping(exception="java.lange.RuntimeException",result="error"),
 *      @ExceptionMapping(exception="Exception",result="error")
 * }) 
 * 指定一组验证:
 * @Validations(
 *     requiredStrings={
 *			@RequiredStringValidator(fieldName="user.username",message="username is null !"),
 *			@RequiredStringValidator(fieldName="user.password",message="password is null !")
 *     },
 *     regexFields={@RegexFieldValidator(fieldName="telNum",expression="^(//+86|0|1)//d{10,11}$",message="电话号码格式不正确!")}
 * )
 * @SkipValidation:写在放上可跳过验证
 * 指定一组拦截器:
 * 注意:使用token的话建议放在方法上指定拦截器@Action(value="login",interceptorRefs={@InterceptorRef("token")}),
 * 如果在类上方配置@InterceptorRefs会将所有action配置@InterceptorRef("token").
 * @InterceptorRefs({
 *     @InterceptorRef("defaultStack")
 * })
 * 如果使用自定义拦截器必须配置在struts.xml中一起使用,定义一个包,@ParentPackage继承配置的包,在包中定义自己的拦截器
 * 
 * 查看struts2配置:
 * 为了看到struts2应用里的Action等各种资源的影射情况,struts2提供了Config Browser插件.
 * 使用方法:将struts2-config-browser-plugin-2.1.6.jar文件复制到struts2应用的WEB-INF/lib目录中.
 * 打开首页地址:http://localhost:8090/应用名字/config-browser/actionNames.action 这里可以看到Config Browser插件的首页.
 */
@ParentPackage("struts-default")
@Namespace("/struts05")
@ResultPath("/")
@Results({
	@Result(name="success",location="success.jsp",type="dispatcher"),
	@Result(name="login",location="index.jsp",type="redirect"),
	@Result(name="input",location="index.jsp"),
	@Result(name="invalid.token",location="error.jsp")
})
@ExceptionMappings({
	@ExceptionMapping(exception="java.lange.RuntimeException",result="error")	
})
@Validations(
	requiredStrings={
			@RequiredStringValidator(fieldName="user.username",message="username is null !"),
			@RequiredStringValidator(fieldName="user.password",message="password is null !")
	}
)
@InterceptorRefs({
	@InterceptorRef("defaultStack")
})
public class LoginActino extends ActionUtil  {


	private static final long serialVersionUID = 1L;
	private Users user;
	
	public Users getUser() {
		return user;
	}


	public void setUser(Users user) {
		this.user = user;
	}
	
	private String token;
	
	
	public String getToken() {
		return token;
	}


	public void setToken(String token) {
		this.token = token;
	}


	@Action(value="login",interceptorRefs={@InterceptorRef("token")})
	public String login(){
		if (user.getUsername().equals("lee") && user.getPassword().equals("123")) {
			session.put("isLogin", user.getUsername());
			return SUCCESS;
		}
		return LOGIN;
	}
	
	@SkipValidation
	@Action("reg")
	public String reg(){
		return SUCCESS;
	}
	
	@SkipValidation
	@Action(value="error",results={@Result(name="error",location="error.jsp")})
	public String error(){
		return ERROR;
	}
	
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值