简体   繁体   English

Struts2登录拦截器不起作用

[英]Struts2 login interceptor is not working

I am not able to stop user accessing a page say welcome.jsp when he is not in session, please help me in implementing login interceptor. 当他不在会话中时,我无法阻止用户访问诸如welcome.jsp的页面,请帮助我实现登录拦截器。 here is my code. 这是我的代码。 All I want to do is when user logs in with his user id, check wether he is in session, if he is in session, let him access any resouce else, redirect user to "somePage". 我要做的就是当用户使用其用户ID登录时,检查他是否在会话中,如果他在会话中,则让他访问其他资源,将用户重定向到“ somePage”。 TIA TIA

<?xml version="1.0" encoding="UTF-8" ?>

<constant name="struts.convention.default.parent.package"
    value="default" />
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.custom.i18n.resources" value="global" />
<constant name="struts.objectFactory"
    value="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<constant name="struts.i18n.reload" value="false" />
<constant name="struts.configuration.xml.reload" value="false" />

<package name="default" namespace="/default" extends="json-default,struts-default">

    <interceptors>
        <interceptor name="authentication"
            class="com.mycompany.abc.webapp.action.AuthenticationInterceptor" />
        <interceptor-stack name="authStack">
            <interceptor-ref name="authentication"></interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
        </interceptor-stack>

            /> -->
        <interceptor-stack name="acc-stack">
            <!-- <interceptor-ref name="sessionCheck" /> -->

            <interceptor-ref name="json">
                <param name="enableSMD">true</param>
            </interceptor-ref>
            <interceptor-ref name="exception" />
            <interceptor-ref name="alias" />
            <interceptor-ref name="servletConfig" />
            <interceptor-ref name="i18n" />
            <interceptor-ref name="prepare" />
            <interceptor-ref name="chain" />
            <interceptor-ref name="debugging" />
            <interceptor-ref name="scopedModelDriven" />
            <interceptor-ref name="modelDriven" />
            <interceptor-ref name="fileUpload" />
            <interceptor-ref name="checkbox" />
            <interceptor-ref name="multiselect" />
            <interceptor-ref name="staticParams" />
            <interceptor-ref name="actionMappingParams" />
            <interceptor-ref name="params">
                <param name="excludeParams">dojo\..*,^struts\..*</param>
            </interceptor-ref>
            <interceptor-ref name="conversionError" />
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="timer" />
        </interceptor-stack>
    </interceptors>

    <default-interceptor-ref name="authStack"></default-interceptor-ref>

        <global-results>
         <result name="login" type="redirect">/home.action</result>
        </global-results>
    <action name="home">
        <interceptor-ref name="defaultStack"></interceptor-ref>
        <result name="somePage">/jsp/somePage.jsp</result>
         <result name="success">/jsp/xyz.jsp</result>
          <result name="homePage">/jsp/homePage.jsp</result>
    </action>
 <!-- <action class="com.mycompany.abc.webapp.action.LoginAction" name="login">
        <interceptor-ref name="defaultStack"></interceptor-ref>
        <result name="success">/jsp/welcome.jsp</result>
        <result name="somePage">/jsp/somePage.jsp</result>
    </action>

    <action name="welcome" class="com.mycompany.abc.webapp.action.WelcomeAction">
    <interceptor-ref name="defaultStack"></interceptor-ref>
        <result name="success">/jsp/welcome.jsp</result>
    </action> -->

</package>

LoginAction: LoginAction:

@InterceptorRef(value = "defaultStack")
@ParentPackage("struts-default")

@Results({ @Result(name = "success", location = "/jsp/xyz.jsp"),
        @Result(name = "error", location = "/jsp/error.jsp"),
        @Result(name = "noAccess", location = "/jsp/abc.jsp"),
        @Result(name = "somePage", location = "/jsp/somePage.jsp"),
        @Result(name = "input", location = "/jsp/login.jsp"), })
public class LoginAction extends ActionSupport implements SessionAware,
        ModelDriven<MySession> {
private static final long serialVersionUID = -3369875299120377549L;
private String userId;
private String result = null;
@Autowired
CompService CompService;

MySession MySession = new MySession();
@Autowired
MyServices MyServices;

private Map<String, Object> sessionAttributes = null;
/*private User user = new User();*/

@Override
public String execute() {
    System.out.println("inside execute");
    System.out.println("userid************" + this.userid);
    if (this.userid != null) {

        HttpSession session = ServletActionContext.getRequest()
        .getSession();
        useridProfile profile = MyServices.getuseridProfile(this.userid);
        if (profile != null) {
            //here i am getting  a collection say my Coll
            if (myColl.isEmpty()) {
                result = "noAcess";
            }
            else{
                sessionAttributes.put("userId", userId);
                result = "success";
            }

        }

        return result;
    } else if (sessionAttributes.get("userid") == null) {

        System.out.println("Not logged in");
        System.out.println("userid************" + this.userid);
        result = "somePage";
    } 
    return result;
}

@Override
public void setSession(Map<String, Object> sessionAttributes) {
    this.sessionAttributes = sessionAttributes;
}

public String getuserId() {
    return userid;
}

public void setuserId(String userid) {
    this.userid = userid;
}

@Override
public MySession getModel() {
    // TODO Auto-generated method stub
    return MySession;
}

}

AuthenticationInterceptor 身份验证拦截器

public class AuthenticationInterceptor implements Interceptor{

    private static final long serialVersionUID = -5011962009065225959L;

     String result=null;
@Override
public void destroy() {
    //release resources here
}

@Override
public void init() {
    // create resources here
}

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

    ActionContext sessionAttributes = actionInvocation.getInvocationContext();
    System.out.println("inside auth interceptor");
    Object sess = sessionAttributes.get("userid");

    System.out.println("inside auth interceptor"+sess);
   // User user = (User) sessionAttributes.get("USER");

    if(sess == null){

        if(sessionAttributes.get("userId") != null){
             result = actionInvocation.invoke();


    }
        return result;
    }
        else{

        return actionInvocation.invoke();

    }


}
}

login jsp 登录jsp

    <%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%-- Using Struts2 Tags in JSP --%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Welcome User, please login below</h3>
<s:form action="login">
    <s:textfield name="userId" label="userId"></s:textfield>
    <s:submit value="Login"></s:submit>
</s:form>
</body>
</html>

You are not using the authStack you defined in the action: 您没有使用在操作中定义的authStack:

 <action name="welcome" class="com.mycompany.abc.webapp.action.WelcomeAction">
<interceptor-ref name="authStack"></interceptor-ref>
    <result name="success">/jsp/welcome.jsp</result>
</action>

If you're using annotations, then the WelcomeAction should have @InterceptorRef(value = "authStack"). 如果使用批注,则WelcomeAction应具有@InterceptorRef(value =“ authStack”)。

Also note that this line of code is not needed (you're not using session): 另请注意,不需要以下代码行(您不使用会话):

HttpSession session = ServletActionContext.getRequest().getSession();

Finally (and most importantly), your interceptor is wrong. 最后(也是最重要的),您的拦截器是错误的。 The following line returns the ActionContext, not the session: 以下行返回ActionContext,而不是会话:

ActionContext sessionAttributes = actionInvocation.getInvocationContext();

If you want to return the session, try: 如果要返回会话,请尝试:

Map<String, Object> session = ActionContext.getContext().getSession();

Your interceptor code is complete nonsense. 您的拦截器代码是完全废话。

public String intercept(ActionInvocation actionInvocation) throws Exception {
    ActionContext sessionAttributes = actionInvocation.getInvocationContext();

    Object sess = sessionAttributes.get("userid");
    if (sess == null) {
        if (sessionAttributes.get("userId") != null) {
            result = actionInvocation.invoke();
        }
        return result;
    }

    return actionInvocation.invoke();
}
  1. Get "userid" 获取“用户ID”
  2. If it's null... 如果为空...
  3. ...check to see if it's not null, and... ...检查它是否不为空,并且...
  4. ...if it isn't, invoke and return the action's result. ...如果不是,请调用并返回操作的结果。
  5. If it isn't... 1....invoke and return the action's result. 如果不是... 1 ....调用并返回操作结果。

And that assumes you're actually looking at the session, which you're not . 假设你实际看到的会议, 这你不是

What you meant to do, roughly, from memory: 您打算从内存中大致做什么:

public String intercept(ActionInvocation actionInvocation) throws Exception {
    Map<String, Object> session = actionInvocation.getInvocationContext().getSession();
    return session.containsKey(SESSION_USER_KEY) ? actionInvocation.invoke() 
                                                 : GLOBAL_RESULT_LOGIN;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM