日期:2014-05-17  浏览次数:20709 次

struts2登录拦截
用户没有登录的情况下,如果要进行操作,则直接跳到登录页面先进行登录,想问一下各位大牛要怎么写?求代码

------解决方案--------------------
1.创建拦截器类,需要继承AbstractInterceptor,需要重写intercept方法。在intercept方法里面判断用户是否已登录(主要是在session里面取用户信息),然后做相应的页面导向。
2.在struts中配置刚才的拦截器类,然后与default拦截器组成拦截器组,然后设置该拦截器组为默认拦截器。搞定!
------解决方案--------------------

public class CheckLoginInterceptor implements Interceptor {

private String sessionAttribute;
private String reloginResult;

public void setSessionAttribute(String sessionAttribute) {
this.sessionAttribute = sessionAttribute;
}

public void setReloginResult(String reloginResult) {
this.reloginResult = reloginResult;
}

@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public void init() {
// TODO Auto-generated method stub

}

@SuppressWarnings("rawtypes")
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// 读取session
Map session = invocation.getInvocationContext().getSession();
// 判断session中是否有相应的attribute
if (session.containsKey(sessionAttribute)) {
String resultCode = invocation.invoke();
return resultCode;
} else {
return reloginResult;
}

}

}


然后在struts.xml中引入即可
------解决方案--------------------

package org.ohshit.common.interceptors;

import java.util.Map;


import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;


import org.springframework.stereotype.Component;


import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
 * 权限控制拦截器   对用户信息 进行查看 或者修改的操作  都将被拦截
 * @author Tone
 *
 */
@Component("OhShitPowerInterceptor")
public class OhShitPowerInterceptor extends AbstractInterceptor {


private static final long serialVersionUID = 1L;

@Override
public String intercept(ActionInvocation actioninvocation) throws Exception {

        HttpServletRequest request = ServletActionContext.getRequest();
        
        String url = request.getRequestURI();
//System.out.println("url:"+url);

Map<String,Object> session = actioninvocation.getInvocationContext().getSession();


if (url.indexOf("UserInfoAction")!=-1) {
if (session.get("LOGIN_USER")==null) {
request.setAttribute("nomsg", "请先登录");
return "login";