【问题标题】:Web application utility classWeb 应用程序实用程序类
【发布时间】:2010-03-02 13:09:54
【问题描述】:

以下是一个由 LoginBean 调用的实用程序类,用于通过 FacesContext 从会话中添加和获取用户对象。

应用程序使用 Spring。我应该使用注释还是在这种类中使用静态方法是一种公认​​的做法?如果建议使用注解,我应该使用@Component 还是@Service?

// Annotate as Service/Component?
public class WebUtils {

// Add user object to session
public void setUser( User user ){
    FacesContext context = FacesContext.getCurrentInstance();
    context.getExternalContext().getSessionMap().put( "user", user );
}

// Get user from session
public User getUser( FacesContext context ){
    if( context != null )
        return (User) context.getExternalContext().getSessionMap().get("user");

    return null;
}

【问题讨论】:

  • 什么都没有。这是错误的做法。如果您想在会话范围内拥有某些东西,只需使用会话范围的 bean。请参阅 Roman 的正确方法。
  • 感谢 BalusC 的评论。我希望有一个将最佳实践分组的网站:)

标签: java spring jsf annotations utility


【解决方案1】:

我建议您在会话范围内为您的目的创建单独的 spring bean。

您可以将其命名为UserSupportUserController。这个 bean 应该有方法 getUser ()setUser () 可能还有一些调用你的服务层的方法。

【讨论】:

  • UserManager。其他有用的方法是login()logout()isLoggedin()
【解决方案2】:

我喜欢将这样的东西用作 Spring Bean,这样我就可以在上面注入我需要的任何东西。

再一次,如果静态方法现在适合您,您可以随时在以后需要时将其设为 bean。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 2013-05-03
    • 2010-09-21
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多