在托管bean中执行SQL语句

时间:2012-03-08 16:21:08

标签: java sql jsf javabeans

我有这个托管bean,它对Oracle数据库进行SQL查询,并返回变量SessionTTL,MAXACTIVEUSERS和ACTIVEUSERS的内容。之后,变量内容显示在JSF页面中。

我的问题是这是从SQL查询中获取多个结果的当前方法,以及在加载bean之后使用GetVariablesDB()方法的连接方式是什么。下面的代码将显示空变量,因为未调用方法GetVariablesDB()

P.S我编辑了代码

import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
   // or import javax.faces.bean.SessionScoped;
import javax.inject.Named;
/* include package for SHA-256 encryption */
import java.security.NoSuchAlgorithmException;
/* include SQL Packages */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
   // or import javax.faces.bean.ManagedBean;   

import org.glassfish.osgicdi.OSGiService;

@Named("DashboardController")

@SessionScoped

public class Dashboard implements Serializable {

    private  String storedPassword = null;               
    private  String stringzoro = null;    
    private  String stringone = null;
    private  String stringtwo = null;
    private  String SQL_Statement = null;


       public Dashboard() throws SQLException{    
           GetVariablesDB();
       }

       /* Call the Oracle JDBC Connection driver */
       @Resource(name="jdbc/Oracle")
       private DataSource ds;


       public String getUser(){
           return stringzoro;       
       }

       public String getPassword(){
           return stringone;
       }




       private void GetVariablesDB() throws SQLException {          

            if (ds == null) throw new SQLException();      
       Connection conn = ds.getConnection();
            if (conn == null) throw new SQLException();      

       try {
            conn.setAutoCommit(false);
            boolean committed = false;
                try {
                       SQL_Statement = "SELECT * from GLOBALSETTINGS";

                       PreparedStatement passwordQuery = conn.prepareStatement(SQL_Statement);

                       ResultSet result = passwordQuery.executeQuery();

                       if(result.next()){
                            stringzoro= result.getString("SessionTTL");
                            stringone = result.getString("MAXACTIVEUSERS");
                            stringtwo = result.getString("ACTIVEUSERS");                            
                       }

                       conn.commit();
                       committed = true;
                 } finally {
                       if (!committed) conn.rollback();
                       }
            }
                finally {               
                conn.close();

                }  

       }                         
}

现在当我尝试执行bean时,我在glassfish中得到了这个错误堆栈:

[#|2012-03-08T18:37:44.233+0200|INFO|glassfish3.1.2|org.glassfish.osgijavaeebase|_ThreadID=3393;_ThreadName=Thread-2;|Deleted /tmp/osgiapp6154116770873802943|#]

[#|2012-03-08T18:37:44.233+0200|INFO|glassfish3.1.2|org.glassfish.osgijavaeebase|_ThreadID=3393;_ThreadName=Thread-2;|Undeployed bundle com.DX_57.SM_57 [275]|#]

[#|2012-03-08T18:37:44.234+0200|INFO|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=3393;_ThreadName=Thread-2;|Stopped com.DX_57.SM_57 [275]|#]

[#|2012-03-08T18:37:44.240+0200|INFO|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=3393;_ThreadName=Thread-2;|Uninstalled com.DX_57.SM_57 [275]|#]

[#|2012-03-08T18:37:44.432+0200|INFO|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=3398;_ThreadName=Thread-2;|com.sun.webui.jsf.component.DropDown::The current value of component propertyForm:deployTable:topActionsGroup1:filter does not match any of the selections. 
Did you forget to reset the value after changing the options? |#]

[#|2012-03-08T18:37:54.363+0200|WARNING|glassfish3.1.2|org.apache.catalina.connector.Request|_ThreadID=3942;_ThreadName=Thread-2;|PWC4011: Unable to set request character encoding to UTF-8 from context , because request parameters have already been read, or ServletRequest.getReader() has already been called|#]

[#|2012-03-08T18:37:54.458+0200|INFO|glassfish3.1.2|org.glassfish.admingui|_ThreadID=3942;_ThreadName=Thread-2;|GUI deployment: uploadToTempfile|#]

[#|2012-03-08T18:37:54.459+0200|INFO|glassfish3.1.2|org.glassfish.admingui|_ThreadID=3942;_ThreadName=Thread-2;|uploadFileName=SM_57-1.0-SNAPSHOT.war|#]

[#|2012-03-08T18:37:54.527+0200|INFO|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=68;_ThreadName=Thread-2;|Installed com.DX_57.SM_57 [276] from reference:file:/opt/glassfish3/glassfish/domains/domain1/applications/SM_57-1.0-SNAPSHOT/|#]

[#|2012-03-08T18:37:54.540+0200|INFO|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=68;_ThreadName=Thread-2;|Started com.DX_57.SM_57 [276]|#]

[#|2012-03-08T18:37:54.569+0200|INFO|glassfish3.1.2|javax.enterprise.system.tools.admin.org.glassfish.deployment.admin|_ThreadID=68;_ThreadName=Thread-2;|SM_57-1.0-SNAPSHOT was successfully deployed in 96 milliseconds.|#]

[#|2012-03-08T18:37:54.614+0200|INFO|glassfish3.1.2|org.glassfish.osgijavaeebase|_ThreadID=57;_ThreadName=Thread-2;|Expanded at file:/tmp/osgiapp8052165052141203090/|#]

[#|2012-03-08T18:37:55.059+0200|INFO|glassfish3.1.2|org.glassfish.osgiweb|_ThreadID=57;_ThreadName=Thread-2;|total number of classes with faces annotation = 0|#]

[#|2012-03-08T18:37:55.083+0200|INFO|glassfish3.1.2|javax.enterprise.resource.webcontainer.jsf.config|_ThreadID=57;_ThreadName=Thread-2;|Initializing Mojarra 2.1.6 (SNAPSHOT 20111206) for context '/SM_57-1.0-SNAPSHOT'|#]

[#|2012-03-08T18:37:55.093+0200|INFO|glassfish3.1.2|org.glassfish.osgiweb|_ThreadID=57;_ThreadName=Thread-2;|Faces Config uris excluding the ones named as faces-config.xml = []|#]

[#|2012-03-08T18:37:55.141+0200|INFO|glassfish3.1.2|org.glassfish.osgiweb|_ThreadID=57;_ThreadName=Thread-2;|Facelet Config uris = []|#]

[#|2012-03-08T18:37:55.142+0200|INFO|glassfish3.1.2|javax.enterprise.resource.webcontainer.jsf.config|_ThreadID=57;_ThreadName=Thread-2;|Monitoring jndi:/server/SM_57-1.0-SNAPSHOT/WEB-INF/faces-config.xml for modifications|#]

[#|2012-03-08T18:37:55.165+0200|INFO|glassfish3.1.2|javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=57;_ThreadName=Thread-2;|WEB0671: Loading application [com.DX_57.SM_57_1.0.0.SNAPSHOT] at [/SM_57-1.0-SNAPSHOT]|#]

[#|2012-03-08T18:37:55.183+0200|INFO|glassfish3.1.2|org.glassfish.osgiweb|_ThreadID=57;_ThreadName=Thread-2;|Registered ServletContext as a service with properties: {osgi.web.symbolicname=com.DX_57.SM_57, osgi.web.version=1.0.0.SNAPSHOT, osgi.web.contextpath=/SM_57-1.0-SNAPSHOT} |#]

[#|2012-03-08T18:37:55.186+0200|INFO|glassfish3.1.2|org.glassfish.osgijavaeebase|_ThreadID=57;_ThreadName=Thread-2;|deployed bundle com.DX_57.SM_57 [276] at file:/tmp/osgiapp8052165052141203090/|#]

[#|2012-03-08T18:38:03.560+0200|SEVERE|glassfish3.1.2|javax.enterprise.resource.webcontainer.jsf.application|_ThreadID=322;_ThreadName=Thread-2;|Error Rendering View[/Settings.xhtml]
com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: com.DX_57.SM_57.Dashboard.
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    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 com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:103)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:179)
    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIOutput.getValue(UIOutput.java:169)
    at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
    at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
    at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
    at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:312)
    at com.sun.faces.renderkit.html_basic.TableRenderer.renderHeader(TableRenderer.java:337)
    at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:95)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
    at javax.faces.component.UIData.encodeBegin(UIData.java:1118)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1755)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
    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:594)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1542)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:849)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:746)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1045)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:228)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.sql.SQLException
    at com.DX_57.SM_57.Dashboard.GetVariablesDB(Dashboard.java:70)
    at com.DX_57.SM_57.Dashboard.<init>(Dashboard.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:372)
    at java.lang.Class.newInstance(Class.java:325)
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
    ... 55 more
|#]

这个SQL语句的Java代码是否正确?

1 个答案:

答案 0 :(得分:1)

只需在构造函数中调用GetVariablesDB()即可。为什么你的实例变量和方法是公开的?

如果您在站点启动时需要该数据,那么您应该在构造函数中初始化数据,否则在特定事件中调用public方法。

为了更好的可读性,您应该使用this关键字或至少使用命名约定标记您的实例变量。如果您无法通过名称或访问修饰符来区分变量的范围,则很难遵循代码。