【问题标题】:JSP pass setProperty into a java class with beanJSP 将 setProperty 传递给带有 bean 的 java 类
【发布时间】:2013-01-14 18:05:30
【问题描述】:

我如何在一些不是 servlet 的 java 类中使用 session.getAttribute。可能是这样的东西或其他技巧?

<%    
    <jsp:useBean id="bean" class="ProfitBean" scope="application"/>
        <jsp:setProperty name="bean" value='<%=session.getAttribute("idUser")%>'/>
    %>

    public class ProfitBean{
    private int idUser;
    public void setIdUser(int IdUser){
    ...
    }
    public int getIdUser(){
    ...
    }
    }



    public class SomeClass{
    public void doSomething(){
    ProfitBean pb =new ProfitBean
    int userId = pb.getIdUser();

    }
    }

【问题讨论】:

    标签: java jsp


    【解决方案1】:

    一个会话需要一个请求。因此,请求必须将 userId 传递给您的 Application-Scope-ProfitBean。

    在这种情况下,您可以使用 Singleton 反模式,因此 ProfitBean.getInstance().get/setIdUser() 将包含相同的值。

    private static ProfitBean profitBeanInstance;
    
    @Deprecated
    public ProfitBean(){
        profitBeanInstance=this;
    }
    
    public static ProfitBean getInstance(){
        if (profitBeanInstance == null) {
            NullPointerException cause = new NullPointerException();
            throw new IllegalStateException("The instance has not been created by blabla.jsp!", cause);
        }
        return profitBeanInstance;
    }
    

    警告:此单例可供任何用户使用。在“SomeClass”中,您无法确定是哪个用户设置了此值。

    【讨论】:

    • 我承认这个问题几乎无法理解,但我不确定这个答案是否有意义。老实说,这是一段糟糕的代码。
    • 更有创意 BalusC,如果我能在这种情况下提供帮助,我很幸运。
    【解决方案2】:

    如果班级不能得到它,它应该要求它。

    换句话说,只需在调用方法时将所需的值传递给它。

    someClass.doSomething(session.getAttribute("idUser"));
    

    或者,取决于上下文。

    someClass.doSomething(profitBean);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 2011-12-10
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2015-06-29
      相关资源
      最近更新 更多