Struts2通过自己定义拦截器实现登录之后跳转到原页面

这个功能对用户体验来说是非常重要的。实现起来事实上非常easy。

拦截器的代码例如以下:

package go.derek.advice;

import go.derek.entity.User;
import go.derek.util.CommonChecks;
import go.derek.util.Constant;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class JumpBeforeInterceptor extends AbstractInterceptor implements ApplicationContextAware{

	private static final long serialVersionUID = 7224871247223705569L;
	
	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		ActionContext actionContext = ai.getInvocationContext();
		Map<String, Object> session = actionContext.getSession();
		User currentUser = (User) session.get(Constant.USER_INFO);
		if (null != currentUser
				&& CommonChecks.isNotEmpty(currentUser.getUserId())) {
			return ai.invoke();//运行下一个拦截器,假设没有拦截器了,就运行action
		}
		else{
				HttpServletRequest request = (HttpServletRequest) actionContext
					.get(StrutsStatics.HTTP_REQUEST);	
				String queryString = request.getQueryString();
			    // 预防空指针
			    if (queryString == null) {
					queryString = "";
			    }
			    // 拼凑得到登陆之前的地址
			    String realPath = request.getRequestURI() + "?" + queryString;
			    System.out.println(realPath+"	realPath");
				session.put(Constant.GOING_TO_URL, realPath);
				return ai.invoke();//放行
			}
	}
			
	@Override
	public void setApplicationContext(ApplicationContext arg0)
			throws BeansException {
		// TODO Auto-generated method stub
		
	}
}
将上一页面的url放到session中,然后登录的时候再从session中取出来,再重定向就能够了。

loginAction中这样写

String url = (String) this.getSession().get(Constant.GOING_TO_URL);
		if (CommonChecks.isNotEmpty(url)) {
			this.getResponse().sendRedirect(url);
			return null;
		}

struts.xml配置文件里。要对上面的自己定义拦截器做配置:

<interceptor name="jumpBefore" 
				class="go.derek.advice.JumpBeforeInterceptor"/>
			<interceptor-stack name="jumpTo">
			<!-- 定义拦截器栈包括checkLogin拦截器 -->
			<interceptor-ref name="jumpBefore"></interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			</interceptor-stack>

还要在之前的那个页面相应的action中,把拦截器配置上,比方:

<action name="problems" class="problemsAction">
			<result>/problems.jsp</result>
			<interceptor-ref name="jumpTo" />
		</action>

经过上面的过程,就能够实现登陆之后跳转回原页面了~


posted @ 2016-01-16 15:00  zfyouxi  阅读(802)  评论(0编辑  收藏  举报