struts2 拦截器的设置

struts2 需要加一个拦截器在action中做登录验证校验,主要的思想是登录后在session中存储一个标志,然后在过滤器中验证这个标志,如果有则通过验证。如果没有,则返回到登录页面。

过滤器代码如下,我把标志就设置为username,需要修改的同学自己改名字

package com.tc.blacktea.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.ServletRedirectResult;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginInterceptor implements Interceptor {
 private static final long serialVersionUID = -2255797147687651066L;
 private static final Log log = LogFactory.getLog(LoginInterceptor.class);
 public String intercept(ActionInvocation invocation) throws Exception {
  final ActionContext context = invocation.getInvocationContext();
  HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
  HttpSession session = request.getSession();
  String username=(String)session.getAttribute("username");
  if (username == null) {
   ServletRedirectResult result = new ServletRedirectResult();
   result.setLocation("/toLogin.action");
   try {
    result.execute(invocation);
   } catch (Exception ex) {
    log.error("Unable to create debugging console", ex);
   }
   return Action.NONE;
  }
  return invocation.invoke();
 }

public void destroy() {

}

public void init() {

}
 
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/da4134779ed9367d8ed5f42ae5f738ea.html