使用@Resource

时间:2017-02-20 08:29:35

标签: java tomcat jdbc

了解我的Java技能人员。我曾经在Java里面用类声明我的连接细节。我这次决定尝试使用context和@Resource方法,并且遇到了一些错误

  

信息:服务器启动时间为1701毫秒   java.sql.SQLException:无法为连接URL' jdbc:oracle:thin @ // 10.30.30.30:1521/mydatabase?useSSL=false”       at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2065)       at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:1939)       at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1412)       在com.pldt.itms.FirstServlet.doGet(FirstServlet.java:40)       在javax.servlet.http.HttpServlet.service(HttpServlet.java:618)       在javax.servlet.http.HttpServlet.service(HttpServlet.java:725)       在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)       在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)       在org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)       在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)       在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)       在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)       在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)       在org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)       在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)       at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)       at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)       在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)       在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)       在org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)       at org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:658)       在org.apache.coyote.http11.Http11NioProtocol $ Http11ConnectionHandler.process(Http11NioProtocol.java:222)       在org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1556)       在org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.run(NioEndpoint.java:1513)       at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)       at java.util.concurrent.ThreadPoolExecutor $ Worker.run(Unknown Source)       at org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)       在java.lang.Thread.run(未知来源)   引起:java.sql.SQLException:没有合适的驱动程序       at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2056)       ......还有27个

下面是我在WebContent / META-INF

中的context.xml
<?xml version="1.0"?>
<Context>

<Resource url="jdbc:oracle:thin@//10.30.30.30:1521/mydatabase?useSSL=false" driverClassName="oracle.jdbc.driver.OracleDriver" password="password" username="username" maxWait="10000" maxIdle="5" maxActive="20" type="javax.sql.DataSource" auth="Container" name="jdbc/web_my_context"/>

</Context>

这是我的Java类

package com.company.project;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class FirstServlet
 */
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Resource(name="jdbc/web_my_context")
    DataSource dataSource;
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1 printwriter
        PrintWriter out = response.getWriter();
        response.setContentType("text/plain");
        //2 connect to db
        Connection myConn = null;
        Statement myStmt = null;
        ResultSet myRs = null;

        try{
            myConn = dataSource.getConnection();

        //3 create sql
            String sql = "select * from table_authorities";
            myStmt = myConn.createStatement();
        //4 execute sql
            myRs = myStmt.executeQuery(sql);
        //5 process resultset of sql statment

            while (myRs.next()){
                String email = myRs.getString("username");
                out.println(email);
            }

        } catch (Exception exc) {
            exc.printStackTrace();
        }
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

}

enter image description here

修改 我纠正了我的xml

<?xml version="1.0"?>

<Context>

<Resource url="jdbc:oracle:thin:@//10.30.30.30:1521/mydatabase?useSSL=false" driverClassName="oracle.jdbc.driver.OracleDriver" password="password" username="username" maxWait="10000" maxIdle="5" maxActive="20" type="javax.sql.DataSource" auth="Container" name="jdbc/web_my_context"/>

</Context>

但现在它仍然是一个错误:

  

引起:oracle.net.ns.NetException:监听器拒绝连接   出现以下错误:ORA-12514,TNS:当前没有侦听器   知道连接描述符中请求的服务   oracle.net.ns.NSProtocolStream.negotiateConnection(NSProtocolStream.java:272)     在oracle.net.ns.NSProtocol.connect(NSProtocol.java:263)at   oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1360)at at   oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:486)... 35   更

1 个答案:

答案 0 :(得分:1)

正如其他人指出你的xml中存在语法错误,正确的语法是

def main():
    scores = input("Enter five test scores separated by commas: ")
    return [int(num) for num in scores.split(",")]


def determine_grade(num):
    if 90 <= num <= 100:
        letter_grade = "A"
    elif 80 <= num <= 89:
        letter_grade = "B"
    elif 70 <= num <= 79:
        letter_grade = "C"
    elif 60 <= num <= 69:
        letter_grade = "D"
    else:
        letter_grade = "F"
    return letter_grade


def calc_average(grades):
    average = sum(grades) / len(grades)
    grade = determine_grade(average)
    print("The average is: {:.1f} which is {}".format(average, grade))


def show_letters(num, letter_grade):
    print("{:.1f} is {}\n".format(num, letter_grade))


lst = main()
for n in lst:
    show_letters(n, determine_grade(n))
calc_average(lst)

我认为你只是在Oracle和MySQL之间切换时出错,我建议在发布问题时不这样做,这样我们就可以准确地帮助你,并且我们需要最新的语法。

更新回答

我认为造成错误的那个实际上就是这一行

  

&#39; JDBC:预言:薄@ // 10.30.30.30:1521/mydatabase?useSSL=false'

AFAIK useSSL = false 仅适用于MySQL,不适用于Oracle数据库。

尝试删除xml中的 useSSL = false 。您的代码现在应该如下所示

jdbc:oracle:thin:@//HOSTNAME:PORT/SERVICENAME

我认为默认情况下Oracle不使用SSL,您不再需要明确地说它不使用SSL。如果你想使用SSL for Oracle,你将不得不使用 tcps 协议,你可以使用像这样的长详细TNS样式。

'jdbc:oracle:thin@//10.30.30.30:1521/mydatabase'

如果您有兴趣配置Oracle连接以使用SSL,可以查看他们的documentation over at this LINK