2013-11-28 79 views
1

我正在設計一個基本的應用程序,用戶在其中提供他的用戶名和密碼,如果登錄成功,他將被重定向到主頁。現在爲了驗證我想使用攔截器,如果用戶名和密碼不是空的。但我無法瞭解如何在攔截器中訪問請求參數的值。 JSP代碼攔截器用於登錄Struts 2.0

<s:form action="Login.action" method="post"> 
     <s:textfield label="Username" name="bean.userId"/> 
     <s:submit value="Login" /> 
</s:form> 

型號

@Entity 
@Table(name="login") 
public class Login implements Serializable 
{ 
public Login() 
{ 
} 
public Login(String userId1, String userPassword1) { 
    userId1 = userId; 
    userPassword1 = userPassword; 
} 
private String userId; 
private String userPassword; 

@Id 
@Column(name="USERID", nullable=false) 
public String getUserId() { 
    return userId; 
} 
public void setUserId(String userId) { 
    this.userId = userId; 
} 
@Column(name="USERPASSWORD", nullable=false) 
public String getUserPassword() { 
    return userPassword; 
} 
public void setUserPassword(String userPassword) { 
    this.userPassword = userPassword; 
} 
} 

查看

public class LoginAction extends ActionSupport 
{ 
    private Login bean; 
public String login() 
{ 
    LoginManager manager=new LoginManager(); 
     try 
     { 
      manager.add(getBean()); 
     } 
     catch(Exception e) 
     { 
      System.out.println(e.getMessage()); 
     } 
     return "success"; 
} 


public Login getBean() { 
    return bean; 
} 

public void setBean(Login bean) { 
    this.bean = bean; 
} 

攔截

public class LoggingInterceptor implements Interceptor 
{ 
public void destroy() 
{ 
    System.out.println("Destorying......"); 
} 

public void init() { 
    System.out.println("Initializing......"); 

} 

public String intercept(ActionInvocation actionInvocation) throws Exception 
{ 
    ActionConfig config = actionInvocation.getProxy().getConfig(); 
    Map parameters  = config.getParams(); 
    String menuId  = (String)parameters.get("userId"); 
    System.out.println("Got it:"+menuId); 
      return actionInvocation.invoke(); 
} 

}

+0

你寫了一個攔截器嗎?顯示代碼。 –

+0

@羅曼:我編輯了這個問題,請現在檢查它 – Pulkit

回答

2

此代碼應該爲您提供來自servlet請求的參數。假設您有一個參數值。

public String intercept(ActionInvocation actionInvocation) throws Exception 
{ 
    Map<String, String[]> parameters = ServletActionContext.getRequest().getParameterMap(); 
    String userId = parameters.get("bean.userId")[0]; 
    System.out.println("Got it:"+userId); 
    return actionInvocation.invoke(); 
} 
+0

它工作的人!!!!!!感謝很多@羅曼C:D。但仍然有一件事我不能得到,我嘗試了在Map中獲取所有參數的方法,但是我調用了ActionInvocation對象,並且獲得了userId的值,但它們不是可讀的形式,我甚至嘗試過使用toString()方法。如何使用ServletActionContext這件事情? – Pulkit

+2

它使用servlet請求來使用直接servlet API獲取其參數。 ServletActionContext是一個輔助類,它使用靜態方法訪問攔截器中的servlet人員。 –