struts2拦截器总结(1)以及ValueStack和StackContext的一点细节

struts2拦截器小结(1)以及ValueStack和StackContext的一点细节
1.使用自定义拦截器来判断用户提交action时是否登录
public String intercept(ActionInvocation invocation) throws Exception {
		// TODO Auto-generated method stub
		//如果是登录或注册请求,跳过拦截器
		String actionName=invocation.getInvocationContext().getName();
		if (actionName.startsWith("login")||actionName.startsWith("regist")) {
            return invocation.invoke();
		} else {
			HttpSession sess = ServletActionContext.getRequest().getSession();
			String username = (String) sess.getAttribute("username");
			if (username == null || username.trim().equals("")) {
                ActionSupport as=(ActionSupport)invocation.getAction();
                as.addActionError(as.getText("error.login.first"));
				return "index";
			}
			return invocation.invoke();
		}
	}


如果验证过程要发送actionerror或actionmessage等消息,如果验证过程要使用国际化资源文件内容等等问题怎么办?
可以通过ActionInvocation的getAction方法来获得一个Action对象,再把它强制转化为struts2为我们提供的ActionSupport对象,这样,就可以在拦截器中实现在Action中一样的操作,调用addActionError等方法。

2.关于ValueStack 和 StackContext

官网说明。
http://www.vaannila.com/struts-2/struts-2-tutorial/struts-2-framework-tutorial-1.html
引用
struts2拦截器总结(1)以及ValueStack和StackContext的一点细节
In Struts 2 the action resides on the ValueStack which is a part of the ActionContext. ActionContext is a global storage area that holds all the data associated with the processing of a request.

When a request comes the params interceptor helps in moving the request data to the ValueStack.

Now the OGNL does the job of converting the string based form data to their corresponding java types. OGNL does this by using the set of available built-in type converters.

Again when the results are generated the OGNL converts the java types of the property on the ValueStack to the string-based HTML output.

ActionContext is thread local which means that the values stored in the ActionContext are unique per thread, this makes the Struts 2 actions thread safe.

这里只大概介绍了下:
ValueStack是存放Action有关的数据,而ActionContext则是存放所有与用户请求相关的数据,当然也就包括ValueStack。
当用户发起一个请求的时候,会被params拦截器取出请求数据放入ValueStack中。
ONNL能提供类型转换的功能,将浏览器的基于文本的数据转化为java数据,反之亦然。
ActionContext使用的是“本地线程”(参考:http://baike.baidu.com/view/4498010.htm),是线程安全的。

struts2中,将ValueStack设置为OGNL的根,所以,可以用OGNL直接访问ValueStack中的对象,如果是存放在非根栈ActionContext中的对象,如session,request等就需要加上“#”号,可以在页面中使用<s:debug/>来查看两个存储区域中的对象数据。
如果不通过OGNL来访问ValueStack或ActionContext中的对象,则可以通过request的getAttribute()方法来访问,我是这样理解的,因为requst包含ActionContext包含ValueStack,不知道对不对。
如果还有其他的一些信息,欢迎补充。

转载请注明出处:http://383984216-qq-com.iteye.com/admin/blogs/1150029
1 楼 仅此而已 2011-08-16  
谢谢分享!
2 楼 liguocai2009 2012-04-12  
很好,对我很有帮助