您可以使用Java Annotations来评估方法中的某些内容吗?

Kro*_*tos 7 java annotations

我想看看是否可以使用注释来评估用户是否登录.

@AuthRequired
public String myProtectedArea() {
  return View("view/protectedArea"); // If user is NOT authenticated, return "view/login"
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ete 3

根据您的编辑:检查此帖子:

在运行时扫描Java注释

我仍然建议使用Spring Security,它已经过测试并且安全:

@PreAuthorize("hasRole('ROLE_USER')")
public String myProtectedArea() {
  return View("view/protectedArea"); 
}
Run Code Online (Sandbox Code Playgroud)

注释将检查用户是否已登录并具有所需的凭据。

Spring Security 的另一种方法是通过在 spring.security-settings.xml 中设置来拦截 URL 模式:

    <intercept-url pattern="/view/protectedArea/*" access="hasRole('ROLE_USER')" />
Run Code Online (Sandbox Code Playgroud)

我建议同时使用两者以最大限度地提高安全性。

在安全设置文件中,您可以告诉 spring security 将用户重定向到何处登录。如果用户已经登录,您可以将他重定向到另一个页面:

<form-login login-page="/view/login.xhtml" default-target-url="/view/protectedArea/home.xhtml"
            authentication-failure-url="/view/login.xhtml" />
Run Code Online (Sandbox Code Playgroud)

它是一个经过测试的框架,因此安全且多功能。但是,如果您想要的不仅仅是标准行为,则需要进行一些设置。