2014-11-25 2 views
1

Я столкнулся с проблемой перехватчика, блокирующего пользователя, выполняющего любой jsp, проверяя, что логическая переменная истинна или ложна; эта переменная находится в bean-компоненте (heyBean), который предварительно устанавливается с помощью метода действия в сеансе (действие реализует сеанс). Если true, пользователь может продолжить действие; если нет, пользователь перенаправляется на страницу входа. Очевидно, что страница входа не должна быть защищена этим перехватчиком. Проблема заключается в том, перехватчик не вызывается, когда я называю защищенное действие перед входом вПроблемы с перехватчиком struts2

Вот мой heyBean:.

package hey.model; 

import java.util.ArrayList; 
import java.rmi.Naming; 
import java.rmi.NotBoundException; 
import java.net.MalformedURLException; 
import java.rmi.RemoteException; 
import rmiserver.RMIServerInterface; 

public class HeyBean { 
    private RMIServerInterface server; 
    private String username; // username and password supplied by the user 
    private String password; 
    private boolean isAuthenticated; 

    public HeyBean() { 
     try { 
      server = (RMIServerInterface) Naming.lookup("server"); 
     } catch(NotBoundException|MalformedURLException|RemoteException e) { 
      e.printStackTrace(); // what happens *after* we reach this line? 
     } 
    } 

    public String getUsername() { 
     return this.username; 
    } 

    public void setUsername(String username) { 
     this.username = username; 
    } 

    public String getPassword() { 
     return this.password; 
    } 

    public void setPassword(String password) { 
     this.password = password; 
    } 

    public boolean isIsAuthenticated() { 
      return isAuthenticated; 
    } 

    public void setIsAuthenticated(boolean isAuthenticated) { 
      this.isAuthenticated = isAuthenticated; 
    } 

    public boolean getUserMatchesPassword() throws RemoteException { 
     return server.userMatchesPassword(this.username, this.password); 
    } 

    public ArrayList<String> getAllUsers() throws RemoteException { 
     return server.getAllUsers(); // are you going to throw all exceptions? 
    } 

    public void sayHey(String whoSaidHey, String toWhoSaidHey) throws RemoteException { 
     server.markAsHeyed(whoSaidHey, toWhoSaidHey); 
    } 

    public ArrayList<String> getAllWhoSaidHey() throws RemoteException { 
     return server.getAllWhoSaidHey(); // are you going to throw all exceptions? 
    } 
} 

Вот мой перехватчик:

package hey.interceptor; 

import java.util.Map; 
import com.opensymphony.xwork2.Action; 
import com.opensymphony.xwork2.ActionInvocation; 
import com.opensymphony.xwork2.interceptor.Interceptor; 
import hey.model.HeyBean; 

public class LoginInterceptor implements Interceptor { 
    private static final long serialVersionUID = 189237412378L; 

    @Override 
    public String intercept(ActionInvocation invocation) throws Exception { 
     Map<String, Object> session = invocation.getInvocationContext().getSession(); 

     // this method intercepts the execution of the action and we get access 
     // to the session, to the action, and to the context of this invocation 
     HeyBean hB = (HeyBean) session.get("heyBean"); 
     if(hB != null && hB.isIsAuthenticated()) { 
      System.out.println("PASSOU!"); 
      return invocation.invoke(); 
     } 
     else { 
      System.out.println("NAO PASSOU!"); 
      return Action.LOGIN; 
     } 
    } 

    @Override 
    public void init() { } 

    @Override 
    public void destroy() { } 
} 

Вот мои struts.xml:

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

<!-- The core configuration file for the framework is the default (struts.xml) file 
and should reside on the classpath of the webapp (generally /WEB-INF/classes). --> 

<!DOCTYPE struts PUBLIC 
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 
    "http://struts.apache.org/dtds/struts-2.0.dtd"> 

<struts> 

    <!-- devMode equals debug information and reload everything for every request --> 
    <constant name="struts.devMode" value="true" /> 
    <constant name="struts.ui.theme" value="simple" /> 

    <package name="hey" extends="struts-default"> 


     <!-- interceptor --> 
     <interceptors> 
      <interceptor name="loginInterceptor" class="hey.interceptor.LoginInterceptor" /> 
      <interceptor-stack name="loginStack"> 
       <interceptor-ref name="loginInterceptor" /> 
       <interceptor-ref name="defaultStack" /> 
      </interceptor-stack> 
     </interceptors> 
     <default-interceptor-ref name="loginStack" /> 

     <default-action-ref name="index" /> 

     <global-results> 
      <result name="error">/error.jsp</result> 
      <result name="login">/index.jsp</result> 
     </global-results> 

     <!-- all exceptions not caught by the application will lead to error.jsp --> 
     <global-exception-mappings> 
      <exception-mapping exception="java.lang.Exception" result="error" /> 
     </global-exception-mappings> 

     <!-- 'index' action leads to the view provided by index.jsp --> 
     <action name="index"> 
      <result>/index.jsp</result> 
     </action> 

     <!-- 'login' action calls 'execute' or 'logout' in 'LoginAction' --> 
     <action name="login" class="hey.action.LoginAction" method="execute"> 
      <interceptor-ref name="defaultStack" /> 
      <result name="success">/hey.jsp</result> 
      <result name="input">/index.jsp</result> 
     </action> 

     <action name="logout" class="hey.action.LogoutAction" method="execute"> 
      <result name="success">/index.jsp</result> 
     </action> 

     <action name="sayHey" class="hey.action.SayHeyAction" method="execute"> 
      <result name="success">/hey.jsp</result> 
     </action> 

    </package> 

</struts> 
+0

Вы уверены, что это НЕ ПРОХОДИТ через перехватчик? Или это просто не работает? Кажется, что вы должны провести сеанс другим способом. –

+0

Это не проблема, есть только три действия, которые были защищены. В большинстве случаев вы не защищены. –

ответ

0

Я только что решил! Оказывается, я делал getHeyBean() в коде действия, что бы построить новый экземпляр HeyBean, если он ранее не существовал.

+0

Примите ваш ответ тогда :) – Pravin

Смежные вопросы