Имя [jdbc/mydb] не связано в этом контексте


Я вижу, что этот вопрос поднимался уже несколько раз, и я прошел через все из них. Но я все еще не могу решить свою проблему.

Может ли кто - нибудь помочь мне определить, что я делаю неправильно?

При попытке доступа к базе данных появляется следующее сообщение об ошибке.jsp:

    HTTP Status 500 - An exception occurred processing JSP page /database.jsp at line 24

type Exception report

message An exception occurred processing JSP page /database.jsp at line 24

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: An exception occurred processing JSP page /database.jsp at line 24

21:         <%
22:                 Context init = new InitialContext();
23:                 Context env = (Context) init.lookup("java:/comp/env/");
24:                 DataSource data = (DataSource) env.lookup("jdbc/mydb");
25:                 Connection conn = data.getConnection();
26:                 Statement stmt = conn.createStatement();
27: 


Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause

javax.servlet.ServletException: javax.naming.NameNotFoundException: Name [jdbc/mydb] is not bound in this Context. Unable to find [jdbc].
    org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:916)
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:845)
    org.apache.jsp.database_jsp._jspService(database_jsp.java:185)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Вот несколько фрагментов информации о моей установке: Мой компьютер работает на Mac OS X. веб-сервер Tomcat версии 7.0.52, установлен под /Пользователи / Имя пользователя / Dropbox / сервер / apache-tomcat-7.0.52. Я пытаюсь запустить Derby 10.10.1.1 как встроенную базу данных. Я скопировал дерби.Джар в папке /users/имя_пользователя/на Dropbox/сервер/Апач-котяра-7.0.52/Либ. Я написал следующее В своем файле пути (я не уверен, что это уместно):

export DERBY_HOME=/Users/username/Dropbox/Server/apache-tomcat-7.0.52/lib
export PATH=$PATH:$DERBY_HOME/bin

Вот содержание веба.xml-файл:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
    <resource-ref>
       <description>DB Connection</description>
       <res-ref-name>jdbc/mydb</res-ref-name>
       <res-type>javax.sql.DataSource</res-type>
       <res-auth>Container</res-auth>
    </resource-ref>
  </description>

</web-app>

Контекст.xml

<?xml version='1.0' encoding='utf-8'?>
<!-- The contents of this file will be loaded for each web application -->
<Context>
    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Сервер.xml

<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <Listener className="org.apache.catalina.core.JasperListener" />
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <GlobalNamingResources>
        <!-- Added by LC #2 @19/3/2014 -->
            <!-- Global Datasource for Derby mydb database -->
            <Resource name="jdbc/mydb"
                     type="javax.sql.DataSource"  auth="Container"
                     description="Derby database for Stocktails"
                     maxActive="20" maxIdle="10" maxWait="-1"
                     username="" password="" 
                     driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
                     url="jdbc:derby:/Users/username/Dropbox/Server/apache-tomcat-7.0.52/databases/mydb"/>
        <!-- End #2 -->

  </GlobalNamingResources>

  <Service name="Catalina">

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />

    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

    <Engine name="Catalina" defaultHost="localhost">
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

        <!-- Added by LC #1 @19/3/2014 -->
        <Context
           docBase="ROOT" path="" debug="0"
           reloadable="true">
        </Context>
        <!-- End #1 -->

      </Host>
    </Engine>
  </Service>
</Server>

Наконец, вот база данных.JSP-страница Страница:

<html>
<head>
  <title>Quote Query</title>
</head>
<body>
  <h1>retrieve stock quotes</h1>
  <h3>Choose Ticker(s):</h3>
  <form method="get">
    <input type="checkbox" name="ticker" value="AAPL">AAPL
    <input type="checkbox" name="ticker" value="MSFT">MSFT
    <input type="submit" value="Query">
  </form>

  <%
    String[] tickers = request.getParameterValues("ticker");
    if (tickers != null) {
  %>


        <%@ page import="javax.naming.*,java.sql.*,javax.sql.*" %>
        <%
                Context init = new InitialContext();
                Context env = (Context) init.lookup("java:/comp/env/");
                DataSource data = (DataSource) env.lookup("jdbc/mydb");
                Connection conn = data.getConnection();
                Statement stmt = conn.createStatement();

                String sqlStr = "SELECT * FROM Quotes WHERE Ticker IN (";
                sqlStr += "'" + tickers[0] + "'";  // First ticker
                for (int i = 1; i < tickers.length; ++i) {
                   sqlStr += ", '" + tickers[i] + "'";  // Subsequent tickers need a leading commas
                }
                sqlStr += ") ORDER BY Date ASC";

                // for debugging
                System.out.println("Query statement is " + sqlStr);

                ResultSet rset = stmt.executeQuery(sqlStr);
        %>

      <hr>
      <form method="get" action="quotes.jsp">
        <table border=1 cellpadding=5>
          <tr>
            <th>Ticker</th>
            <th>Date</th>
            <th>PriceOpen</th>
            <th>PriceHigh</th>
            <th>PriceLow</th>
            <th>PriceClose</th>
            <th>Volume</th>
            <th>PriceAdjClose</th>
          </tr>
  <%
      while (rset.next()) {
        int id = rset.getInt("id");
  %>
          <tr>
            <td><input type="checkbox" name="id" value="<%= id %>"></td>
            <td><%= rset.getString("Ticker") %></td>
            <td><%= rset.getString("Date") %></td>
            <td>$<%= rset.getInt("PriceOpen") %></td>
            <td><%= rset.getInt("PriceHigh") %></td>
            <td><%= rset.getString("PriceLow") %></td>
            <td><%= rset.getString("PriceClose") %></td>
            <td>$<%= rset.getInt("Volume") %></td>
            <td><%= rset.getInt("PriceAdjClose") %></td>
          </tr>
  <%
      }
  %>
        </table>
        <br>
        <input type="submit" value="Order">
        <input type="reset" value="Clear">
      </form>
      <a href="<%= request.getRequestURI() %>"><h3>Back</h3></a>
  <%
      rset.close();
      stmt.close();
      conn.close();
    }
  %>
</body>
</html>

Log

Mar 21, 2014 7:57:26 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/lcazarre/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
Mar 21, 2014 7:57:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'debug' to '0' did not find a matching property.
Mar 21, 2014 7:57:28 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Mar 21, 2014 7:57:28 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 21, 2014 7:57:28 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 3227 ms
Mar 21, 2014 7:57:28 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 21, 2014 7:57:28 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.52
Mar 21, 2014 7:57:28 AM org.apache.catalina.realm.UserDatabaseRealm startInternal
SEVERE: Exception looking up UserDatabase under key UserDatabase
javax.naming.NameNotFoundException: Name [UserDatabase] is not bound in this Context. Unable to find [UserDatabase].
    at org.apache.naming.NamingContext.lookup(NamingContext.java:819)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:167)
    at org.apache.catalina.realm.UserDatabaseRealm.startInternal(UserDatabaseRealm.java:253)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.realm.CombinedRealm.startInternal(CombinedRealm.java:201)
    at org.apache.catalina.realm.LockOutRealm.startInternal(LockOutRealm.java:120)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1109)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:731)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)

Mar 21, 2014 7:57:28 AM org.apache.catalina.realm.CombinedRealm startInternal
SEVERE: Failed to start "org.apache.catalina.realm.UserDatabaseRealm/1.0" realm
org.apache.catalina.LifecycleException: Failed to start component [Realm[UserDatabaseRealm]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.realm.CombinedRealm.startInternal(CombinedRealm.java:201)
    at org.apache.catalina.realm.LockOutRealm.startInternal(LockOutRealm.java:120)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1109)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:300)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:731)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:689)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:321)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:455)
Caused by: org.apache.catalina.LifecycleException: No UserDatabase component found under key UserDatabase
    at org.apache.catalina.realm.UserDatabaseRealm.startInternal(UserDatabaseRealm.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 17 more

Mar 21, 2014 7:57:31 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /Users/lcazarre/Dropbox/Work/MS50/COMSM0104/Server/apache-tomcat-7.0.52/webapps/docs
Mar 21, 2014 7:57:32 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /Users/lcazarre/Dropbox/Work/MS50/COMSM0104/Server/apache-tomcat-7.0.52/webapps/examples
Mar 21, 2014 7:57:33 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /Users/lcazarre/Dropbox/Work/MS50/COMSM0104/Server/apache-tomcat-7.0.52/webapps/host-manager
Mar 21, 2014 7:57:33 AM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory /Users/lcazarre/Dropbox/Work/MS50/COMSM0104/Server/apache-tomcat-7.0.52/webapps/manager
Mar 21, 2014 7:57:34 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 21, 2014 7:57:34 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Mar 21, 2014 7:57:34 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 6321 ms

Спасибо, LC

3 37

3 ответа:

Вам нужна ссылка ResourceLink в вашем файле META-INF/context.xml, чтобы сделать глобальный ресурс доступным для веб-приложения.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

Для тех, кто использует Tomcat с Bitronix, это исправит проблему:

Ошибка указывает на то, что обработчик не может быть найден для вашего источника данных'jdbc/mydb', поэтому вам нужно убедиться, что ваш сервер tomcat ссылается на ваши файлы конфигурации bitronix по мере необходимости.

В случае, если вы используете btm-config.свойства и ресурсы.файлы свойств для настройки источника данных укажите в tomcat следующие два аргумента JVM:

(Если вы уже использовав их, убедитесь, что ваши ссылки верны):

  • БТМ.корень
  • bitronix.tm. configuration

Например

-Dbtm.root="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59" 
-Dbitronix.tm.configuration="C:\Program Files\Apache Software Foundation\Tomcat 7.0.59\conf\btm-config.properties" 

Теперь перезагрузите сервер и проверьте журнал.

Вы ставите resource-ref в описании тега в web.xml