(更直接好用的方法请见下一篇文章)
通过在拦截器里添加request的Attribute属性,然后在前台分别使用struts2标签和request.getAttribute()方法接收,拦截器代码如下:
/**
* 用户登录认证拦截器
*/
package com.test.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import com.test.entity.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @author LuTinghuan
* @date 2014-1-10 上午11:44:31
* @version 1.0
*/
public class AuthorizationInterceptor extends AbstractInterceptor {
/* (non-Javadoc)
* @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
* 如果用户没有登录,刚返回登录界面;否则继续执行原来的操作
*/
@Override
public String intercept(ActionInvocation invocation) throws Exception {
HttpSession session = ServletActionContext.getRequest().getSession();
User currentUser = (User)session.getAttribute("currentUser");
//如果没用登录
if(currentUser == null)
{
String loginMsg = "You have to login first.";
//方法一:前台只能通过request.getAttribute()接收
ServletActionContext.getRequest().setAttribute("loginMsg1", loginMsg);
//方法二:前台只能通过request.getAttribute()接收
ActionContext actionContext1 = invocation.getInvocationContext();
HttpServletRequest request= (HttpServletRequest) actionContext1.get(StrutsStatics.HTTP_REQUEST);
request.setAttribute("loginMsg2", loginMsg);
//方法三:前台通过struts2标签和request.getAttribute()都可以接收到
ActionContext actionContext2 = invocation.getInvocationContext();
actionContext2.put("loginMsg3", loginMsg);
return "NotLogin";
}
return invocation.invoke();
}
}
拦截器的配置略,上面的拦截器最后会转向指定的NotLogin页面,页面代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
方法1的结果:</br>
struts2 tag收到的是“<s:property value="loginMsg1"/>”</br>
request.getAttribute收到的是“<%=request.getAttribute("loginMsg1") %>”<br>
<br>------------------------------------------------------------<br>
方法2的结果:</br>
struts2 tag收到的是“<s:property value="loginMsg2"/>”</br>
request.getAttribute收到的是“<%=request.getAttribute("loginMsg2") %>”<br>
<br>------------------------------------------------------------<br>
方法3的结果:</br>
struts2 tag收到的是“<s:property value="loginMsg3"/>”</br>
request.getAttribute收到的是“<%=request.getAttribute("loginMsg3") %>”<br>
<br>------------------------------------------------------------<br>
</body>
</html>
最终测试结果,如下图:
总结:估计是由于在拦截器里那三种取得的requst的方式不同(拿到的形式本质不一样),所以导致前台取值结果有所不同。纯属瞎猜,如有不对请指正。反正,知道用第三种方法就好了。
参考资料:
http://www.iteye.com/topic/147701
http://zhidao.baidu.com/question/77553302.html
http://www.iteye.com/topic/391849