在Struts2中实现登陆后跳转到登录前页面

很常见的一个应用就是访问某个页面,因为权限不够,进入登陆页面。人性化的设计是能够在登陆之后,系统跳转到用户原本需要访问的页面。这可以借助拦截器来实现。

在我们验证用户登陆的拦截器里面获取请求地址,并存入session。

package com.tuanplus.interceptor;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 验证用户登陆
 * 
 * @author MZULE
 * 
 */
public class UserLoginInterceptor implements Interceptor {

	private static final long serialVersionUID = 1593745236481514166L;

	public void destroy() {
	}

	public void init() {
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext context = invocation.getInvocationContext();
		// 获取session
		Map<String, Object> session = context.getSession();
		Object user = session.get("user");
		// 用户还未登陆
		if (user == null) {
			// 获取HttpServletRequest对象
			HttpServletRequest req = ServletActionContext.getRequest();
			// 获取此请求的地址,请求地址包含application name,进行subString操作,去除application name
			String path = req.getRequestURI().substring(10);
			// 获得请求中的参数
			String queryString = req.getQueryString();
			// 预防空指针
			if (queryString == null) {
				queryString = "";
			}
			// 拼凑得到登陆之前的地址
			String realPath = path + "?" + queryString;
			// 存入session,方便调用
			session.put("prePage", realPath);
			return "login";
		}
		// 用户已经登陆,放行
		return invocation.invoke();
	}

}

在用户登陆的action中加入字符串类型的prePage属性,用来存储拦截器放入session的prePage值(即登陆前的请求地址)。

package com.tuanplus.action;

import com.tuanplus.po.User;
import com.tuanplus.service.IUserService;
import com.tuanplus.util.AuthCodeUtil;

/**
 * 登陆Action
 * 
 * @author MZULE
 * 
 */
public class LoginAction extends BaseAction {

	private static final long serialVersionUID = -6179170126070438432L;
	private IUserService userService;
	private User user;
	//验证码
	private String auth;
	//登录前页面
	private String prePage;

	public String execute() {
		// 获取登陆的User对象
		User seuser = userService.get(user.getEmail());
		// 加入session
		session.put("user", seuser);
		//获取跳转到登陆界面之前的页面地址,由拦截器提供
		prePage = (String) session.get("prePage");
		//清除session中的数据
		session.remove("prePage");
		if (prePage == null) {
			//不是拦截器跳转到登陆页面的,直接访问的登陆页面
			return "myorder";
		} else {
			return SUCCESS;
		}
	}
	...
}

在struts.xml中配置使用action的属性prePage决定物理视图资源。

...
<!-- 登陆 -->
<action name="login" class="loginAction">
	<result type="redirectAction">${prePage}</result>
	<result name="myorder" type="redirectAction">myOrder</result>
	<result name="input">/login.jsp</result>
</action>
...

嗯,一个小技巧,希望对大家有用。

posted @ 2011-08-09 14:35  小瓶子  阅读(16296)  评论(2编辑  收藏  举报
L
i
f
e

i
s

t
o
o

c
r
u
e
l
.

I
f

w
e

c
e
a
s
e

t
o

b
e
l
i
e
v
e

i
n

l
o
v
e
,

w
h
y

w
o
u
l
d

w
e

w
a
n
t

t
o

l
i
v
e
?