Struts2通過自訂攔截器實現登入之後跳轉到原頁面

來源:互聯網
上載者:User

這個功能對使用者體驗來說是非常重要的。實現起來其實很簡單。

攔截器的代碼如下:

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>

經過上面的過程,就可以實現登陸之後跳回原頁面了~


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.