2016-04-26 13 views
0

私は特に(私も正しく理解するために開始されません)接続プールで、JavaのEEに新たなんだからJDBCリソースとサーブレットを使用しました。私は、New >> JDBC Resourceを使ってNetbeansで基本的なJDBCリソースを作ろうとしました。それは以下ののglassfish-resources.xmlの作成:この後Netbeansの

<resources> 
    <jdbc-resource enabled="true" jndi-name="jdbc/myDB" object-type="user" pool-name="miConnectionPool"> 
    <description/> 
    </jdbc-resource> 
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="miConnectionPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false"> 
    <property name="URL" value="jdbc:mysql://localhost:3306/pruebasbd?relaxAutoCommit=&quot;true&quot;"/> 
    <property name="User" value="root"/> 
    <property name="Password" value="root"/> 
    </jdbc-connection-pool> 
</resources> 

を、私はデフォルトのパッケージにある古いサーブレット、 "MiServlet" を、再利用します。このサーブレットは、以前はサーブレットの典型的な初心者の習慣で動作していましたが、現在は応答を送信しません。私は、それが「localhostの/ MyProjectと/インデックス」URLパターンで呼び出されるように、それは、web.xmlで設定され持っているが、何も示されていないされます。

<servlet> 
    <servlet-name>MiServlet</servlet-name> 
    <servlet-class>MiServlet</servlet-class> 
</servlet> 

(...)

<servlet-mapping> 
    <servlet-name>MiServlet</servlet-name> 
    <url-pattern>/index</url-pattern> 
</servlet-mapping> 

これが今のサーブレットのprocessRequestメソッドです:

ここでは、XMLの設定を持っています。私は私が私の新しく作成されたJDBCリソースを使用しようとしている部分を強調した(私は間違っているかやっている場合、私は真剣には考えている!):

protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     try { 
      **// Context creation 
      Context initContext = new InitialContext(); 
      Context webContext = (Context) initContext.lookup("java:/comp/env"); 

      DataSource ds = (DataSource) webContext.lookup("jdbc/myDB"); 
      Connection dbCon = ds.getConnection();** 
      PreparedStatement ps = dbCon.prepareStatement("SELECT * FROM person"); 
      ResultSet rs = ps.executeQuery(); 
      String res = "BEGINNING\n"; 
      while(rs.next()){ 
       res += rs.getString(1)+"\n"; 
      } 

      response.setContentType("text/html;charset=UTF-8"); 
      try (PrintWriter out = response.getWriter()) { 
       /* TODO output your page here. You may use following sample code. */ 
       out.println("<!DOCTYPE html>"); 
       out.println("<html>"); 
       out.println("<head>"); 
       out.println("<title>Servlet MiServlet</title>"); 
       out.println("</head>"); 
       out.println("<body>"); 
       out.println("<h1>Servlet MiServlet at " + request.getContextPath() + "</h1>"); 
       out.println("<p>"+res+"</p>"); 
       out.println("</body>"); 
       out.println("</html>"); 
      } 
     } catch (NamingException ex) { 
      Logger.getLogger(MiServlet.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (SQLException ex) { 
      Logger.getLogger(MiServlet.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

がアップすべて表示する必要があります。この簡単なテストをNetBeansウィザードで以前に作成したJDBCリソースを使用して、この同じコンピュータにあるWAMP MySQLサーバーの最初の列を作成します。私は

https://localhost:8181/PruebasJ2EE-war/index

で呼び出す

:しかし、私が得るすべては、サーブレットで書かれていなくても、静的なコンテンツ(それはさえ呼ばなっていないことを示している)と、この空のHTMLページです

...と私が取得:

<html> 
<head> 
<link rel="alternate stylesheet" type="text/css" href="resource://gre-resources/plaintext.css" title="Ajustar líneas largas"> 
</head> 
<body> 
<pre></pre> 
</body> 
</html> 

は私が間違って何をしているのですか?

編集:M-マリスカルの答えのコードで今すぐ

、それが接続するために管理し、それはまだ任意のテーブルまたはスキーマを見つけることができません。 org.apache.derby.client.am.SqlException:

によって引き起こさ:エルesquema 'PRUEBASBDに' no existe私はpruebasbd.personaにクエリを指している場合。 (私はすでにのGlassFish-resources.xmlでのそのスキーマを選択したので、以前に示されているように) Iは、テーブル "ペルソナ" をポイントしている場合

(スキーマPRUEBASBDが存在しない):

墓:java.sql.SQLSyntaxErrorException:ラタブラ/ Vistaの 'PERSONA' ノー existe。 (テーブル/ビューPERSONAは存在しません)

答えて

1

私は今Java EEを学習しています!そして私は、「initは」メソッドにContextConfigurationをやって、私の運動は役に立ち「colega」ことを願って、私はあなたを助けていた場合、私は知りませんが、あなたはちょうどより多くのコードが必要な場合、私はあなたのためにできることが最善ですよ頼む!;)

public class JdbcServlet extends HttpServlet { 

    private DataSource pool; 

    @Override 
    public void init(ServletConfig config) throws ServletException {   
     Context env = null; 
     try { 
      env = (Context) new InitialContext().lookup("java:comp/env"); 
      pool = (DataSource) env.lookup("sample"); //nombre en web.xml 
      if (pool == null) { 
       throw new ServletException("No se encontró el DataSource"); 
      } 
     } catch (NamingException ex) { 
      Logger.getLogger(JdbcServlet.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    }   

    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 

     Connection conexion = null; 
     ResultSet resultSet = null; 

     response.setContentType("text/html;charset=UTF-8"); 

     try (PrintWriter out = response.getWriter()) { 
      out.println("<h1>Lista de amigos</h1>"); 
      try {     
       conexion = pool.getConnection(); 
       Statement statement = conexion.createStatement(); 
       String sql = "SELECT * FROM personas"; 
       ResultSet res = statement.executeQuery(sql); 
       if (res.next()) {            
        do { 
         out.println("<p>Nombre: "+res.getString("nombre")+ 
           "<br/>Edad:"+res.getInt("edad")+"</p>"); 
        } while (res.next()); 
       } else { 
        out.println("<p>No hay amigos dados de alta</p>"); 
       } 
       out.println("<a href='index.html'>Volver al inicio</a>"); 
      } catch (SQLException ex) { 
       Logger.getLogger(JdbcServlet.class.getName()).log(Level.SEVERE, null, ex); 
      } finally { 
       try { 
        if (conexion != null && !conexion.isClosed()) 
         conexion.close(); 
       } catch (SQLException ex) { 
        Logger.getLogger(JdbcServlet.class.getName()).log(Level.SEVERE, null, ex); 
       } 
      } 
     } 
    } 

    @Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 

     String nombre = request.getParameter("nombre"); 
     String edad = request.getParameter("edad"); 

     if (nombre != null && edad != null) { 
      Connection conexion = null; 
      Statement statement = null; 
      try { 
       int numEdad = Integer.parseInt(edad); 
       String sql = "INSERT INTO personas VALUES('"+nombre+"',"+numEdad+")"; 
       conexion = pool.getConnection(); 
       statement = conexion.createStatement(); 
       statement.executeUpdate(sql);     
       doGet(request, response); 
      } catch (NumberFormatException | SQLException ex) { 
       Logger.getLogger(JdbcServlet.class.getName()).log(Level.SEVERE, null, ex); 
      } finally { 
       try { 
        if (conexion != null && !conexion.isClosed()) 
         conexion.close(); 
       } catch (SQLException ex) { 
        Logger.getLogger(JdbcServlet.class.getName()).log(Level.SEVERE, null, ex); 
       } 
      } 
     } 
    } 

    @Override 
    public String getServletInfo() { 
     return "Short description"; 
    }// </editor-fold> 

} 
+0

ありがとうございました!しかし、それでもまだ動作していません: "この例外をチェックしてください:"サーブレットJdbcServletのServver.service() "プール"オブジェクトが "init"メソッドで初期化されていないようです。 – Zerok

+0

質問に例外を投稿してください;) –

+0

私はそれを動作させることができました!しかし、それはまだ "テーブルPERSONA"のようなエラーをスローします(はい、私のテーブルの名前は "ペルソナ"です、それをチェック)。前にdbスキーマ "pruebasbd"を置いてもうまくいきません。私は質問を更新しましょう。 – Zerok