欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-28 23:45:46
...

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

这个功能对用户体验来说是非常重要的。实现起来其实很简单。

拦截器的代码如下:

 

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>


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