为什么我们在 Struts 2 中使用 PrincipalAware

Why we use PrincipalAware in Struts 2

我们在我们的应用程序中使用 PrincipalAware 界面来获取一些用户相关的东西。

我在网上搜索了有关它的信息,但结果很差,这是我得到的 Google:

public interface PrincipalAware

Actions that want access to the Principal information from HttpServletRequest object should implement this interface.

This interface is only relevant if the Action is used in a servlet environment. By using this interface you will not become tied to servlet environment.

请帮我理解一下。

PrincipalAware 接口允许 Struts 将 PrincipalProxy 对象注入到动作实例中。该代理可用于访问 servlet 安全机制。像这样

public class MyAction extends ActionSupport implements PrincipalAware {

  protected PrincipalProxy principal;

  public void setPrincipalProxy(PrincipalProxy principalProxy) {
    this.principal = principalProxy;
  }

  public PrincipalProxy getPrincipal() {
    return principal;
  }
}

现在,您可以在操作方法或视图层上使用PrincipalProxy

<s:if test="principal.isUserInRole('role1')">

注意,如果你想根据角色限制某些动作的执行,那么你可以使用 roles 拦截器。