這個功能對使用者體驗來說是非常重要的。實現起來其實很簡單。
攔截器的代碼如下:
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;@Overridepublic 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(); // 預防null 指標 if (queryString == null) {queryString = ""; } // 拼湊得到登陸之前的地址 String realPath = request.getRequestURI() + "?" + queryString; System.out.println(realPath+"realPath");session.put(Constant.GOING_TO_URL, realPath);return ai.invoke();//允許存取}}@Overridepublic 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>
經過上面的過程,就可以實現登陸之後跳回原頁面了~