如何在我所有的bean中使用一个连接

  • 本文关键字:连接 一个 bean java jsf
  • 更新时间 :
  • 英文 :


我创建了3个类:第一个用于连接(Connectionx),第二个用于填充UI作为复选框,选择一个菜单(BeanTools),第三个用于我的"操作"(NumberOfIssue)。1) 我只想连接到数据库一次的问题,我已经在Connectionx类中完成了连接,我想在我的所有Bean上使用相同的连接。但我不知道我是如何尝试将适当的连接添加到托管Bean的,但我不确定这是否是一个好的解决方案,如果是,它对我来说不起作用:(,有我的类:

**1/Class Connectionx**
public class Connectionx implements java.io.Serializable{
public Connection cx=null;
public Statement st;
public Connectionx() {}
public Connection Connx()
{ 
System.out.println("enregister le driver");
    try {
        Class.forName("com.mysql.jdbc.Driver");
    }
    catch( Exception ex )
            {
            System.err.println("Erreur lors du chargement du              driver"+ex.getMessage() );
            }
    try {
        /** Connection  */
         cx =  (Connection) DriverManager.getConnection( "jdbc:mysql://localhost/jiradb","root","root" );
        System.out.println("conexion reussite ");
            }
            catch( SQLException ex )
            {
            System. err. println( "Erreur lors de la connexion à la       baseeeeee" );
            }
  return cx;
}
public void deConnx(Connection cx) throws SQLException{
cx.close();
System. err. println( "deconnection");   
 }
 }

2/类BeanTools

 public class BeanTools implements java.io.Serializable {
 /***************selectonemenu***********************/   
 private List<SelectItem> mesElements;
 private  String maValeur;
 public String[] favNumber1 ; //checkbox
 public PreparedStatement st;
 public Connectionx cx = new Connectionx();
 public Connection con = (Connection)cx.Connx();
 /**************checkbox***************/
  public BeanTools() {
  }
   public String getMaValeur() {
    return maValeur;
  }
   public void setMaValeur(String maValeur) {
    this.maValeur = maValeur;
   }
   public String[] getFavNumber1() {
    return favNumber1;
    }
   public void setFavNumber1(String[] favNumber1) {
    this.favNumber1 = favNumber1;
  }
   public String getFavNumber1InString() {
    return Arrays.toString(favNumber1);
}

    public String getFavNumber1onebyone()
    {  String Val =null;
    for(int i=0;i<favNumber1.length;i++)
    {
    if (favNumber1[i].equals("1"))
        System.out.println("priority checked");
    if (favNumber1[i].equals("2"))
        System.out.println("project checked");
    if (favNumber1[i].equals("3"))
   System.out.println("Month checked");
    }
    return Val;
    }

   public Iterable<String> remplireItem() throws ClassNotFoundException, SQLException
  {
   String sql;
   sql ="select issuestatus.pname from issuestatus;";
   System.out.println("sql");
   st=(PreparedStatement) con.prepareStatement(sql);
   ResultSet rs1 = st.executeQuery();System.out.println("execute");
   String val;
   ArrayList<String> list = new ArrayList<String>();
   while(rs1.next())
    {
      val= rs1.getString("pname");
      System.out.println(val);
      list.add(nbb);
      System.out.println("list"+list.toString());
    }
     return list;
    }

    public List<SelectItem> getMesElements() throws SQLException,ClassNotFoundException {
   if (mesElements == null) {
   mesElements = new ArrayList<SelectItem>();
   for (String val : remplireItem()) {
   mesElements.add(new SelectItem(val));
   }
   }
     return mesElements;
   }

3/class问题编号

public class NumberOfIssue implements java.io.Serializable{
public  String numberIssue;
private  String maValeur;
public Connectionx cx = new Connectionx();
public Connection con = (Connection)cx.Connx();
public PreparedStatement st;

public NumberOfIssue() {
}

   public String getMaValeur() {
    return maValeur;
}
public void setMaValeur(String maValeur) {
    this.maValeur = maValeur;
}
public String getNumberIssue() throws SQLException
{
//Connection con
BeanTools beTools=new BeanTools();
System.out.println("beTools.maValeur");
String sql;
sql ="select count(OS_CURRENTSTEP.entry_id) as nbissue     ,project.pname,priority.pname,issuetype.pname from OS_CURRENTSTEP,jiraissue,issuestatus,issuetype,project,resolution,customfield ,customfieldvalue,priority   where OS_CURRENTSTEP.entry_id = jiraissue.id  and jiraissue.priority=priority.id  and jiraissue.issuestatus=issuestatus.id and issuestatus.pname="+maValeur+" and jiraissue.issuetype=issuetype.id and jiraissue.project=project.id   and resolution.id=jiraissue.resolution  and resolution.pname='Fixed'  Group By project.pname,priority.pname,issuetype.pname;";
st= (PreparedStatement) con.prepareStatement(sql); 
ResultSet rs1 = st.executeQuery();
while(rs1.next())
{
 numberIssue=  rs1.getString(1);
 String strissue2=  rs1.getString(2);
 String strissue3=  rs1.getString(3);
 System.out.println("nb issue  "+numberIssue.toString()+"  ||project      "+strissue2.toString()+"  ||proiority  "+strissue3.toString());
}
return numberIssue;
}

}

4/托管Bean

<managed-bean>
<managed-bean-name>Connectionx</managed-bean-name>
<managed-bean-class>KPIs.Connectionx</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>BeanTools</managed-bean-name>
<managed-bean-class>KPIs.BeanTools</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>cx</property-name>
<property-class>java.sql.Connection</property-class>
<value>#{Connectionx.cx}</value>
</managed-property>
</managed-bean>
<managed-bean>
<managed-bean-name>NumberOfIssue</managed-bean-name>
<managed-bean-class>KPIs.NumberOfIssue</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>maValeur</property-name>
<property-class>java.lang.String</property-class>
<value>#{BeanTools.maValeur}</value>
</managed-property>
<managed-property>
<property-name>cx</property-name>
<property-class>java.sql.Connection</property-class>
<value>#{Connectionx.cx}</value>
</managed-property>
</managed-bean>
<navigation-rule>
<from-view-id>/welcomeJSF.jsp</from-view-id>
<navigation-case>
<from-outcome>submit</from-outcome>
<to-view-id>/Result.jsp</to-view-id> 
</navigation-case>
</navigation-rule>
</faces-config>

堆栈跟踪

com.sun.faces.mgbean.ManagedBeanCreationException: Impossible de créer le bean géré    BeanTools.  Les problèmes suivants ont été détectés :
 - La propriété cx du bean géré BeanTools nexiste pas.
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:265)
at                                        com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
at org.apache.el.parser.AstValue.getValue(AstValue.java:147)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:106)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:193)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:181)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169)
at com.sun.faces.renderkit.html_basic.MenuRenderer.getCurrentSelectedValues(MenuRenderer.java:648)
at com.sun.faces.renderkit.html_basic.MenuRenderer.renderOptions(MenuRenderer.java:749)
at com.sun.faces.renderkit.html_basic.MenuRenderer.renderSelect(MenuRenderer.java:844)
at com.sun.faces.renderkit.html_basic.MenuRenderer.encodeEnd(MenuRenderer.java:298)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:883)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1659)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:853)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1652)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
at com.sun.faces.application.view.JspViewHandlingStrategy.doRenderView(JspViewHandlingStrategy.java:431)
at com.sun.faces.application.view.JspViewHandlingStrategy.renderView(JspViewHandlingStrategy.java:233)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

使用类似commons-dbcp的连接池。

顺便说一下,这种代码

"select count(OS_CURRENTSTEP.entry_id) as nbissue  [.. snip ...]
and issuestatus.pname="+maValeur+" and jiraissue.issuetype=issuetype.id
[... snip ...] and resolution.pname='Fixed'  Group By     
project.pname,priority.pname,issuetype.pname;";

容易受到SQL注入的攻击,应将maValeur变量替换为参数(请参阅http://en.wikipedia.org/wiki/SQL_injection#Parameterized_statements)

更好的方法是使用singleton类,而无需将其注册到faces上下文。只需在上下文启动时初始化它,并从任何bean 中使用它

相关内容

  • 没有找到相关文章

最新更新