Servlet访问数据库报错500

这是网页提示的错误
HTTP Status 500 - 查询失败


type Exception report

message 查询失败

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

exception

java.lang.RuntimeException: 查询失败
Dao.EmpDao.finAll(EmpDao.java:32)
web.SqlServlet.service(SqlServlet.java:23)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver'
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1429)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
util.DBUtil.getConnection(DBUtil.java:36)
Dao.EmpDao.finAll(EmpDao.java:16)
web.SqlServlet.service(SqlServlet.java:23)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1856)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1705)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
util.DBUtil.getConnection(DBUtil.java:36)
Dao.EmpDao.finAll(EmpDao.java:16)
web.SqlServlet.service(SqlServlet.java:23)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.67 logs.

这是我的代码,我用测试代码访问数据库的时候,都没有问题,一旦用Servlet访问就出现500问题
package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Dao.EmpDao;
import entity.Emp;

public class SqlServlet extends HttpServlet {

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    res.setContentType("text/html;charset=utf-8");
    EmpDao dao = new EmpDao();
    List<Emp> list = dao.finAll();
    PrintWriter out = res.getWriter();
    out.println("<table border='1px' cellspacing='0' width='40%'>");
    out.println("  <tr>");
    out.println("   <th>编号</th>");
    out.println("   <th>姓名</th>");
    out.println("   <th>职位</th>");
    out.println("   <th>月薪</th>");
    out.println("  </tr>");
    for(Emp emp:list){
        out.println("<tr>");
        out.println("   <td>"+emp.getEmpno()+"</td>");
        out.println("   <td>"+emp.getEname()+"</td>");
        out.println("   <td>"+emp.getJob()+"</td>");
        out.println("   <td>"+emp.getSal()+"</td>");
        out.println("</tr>");
    }
    out.println("</table>");
    out.close();
}

}

下面是dao包的代码package Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import entity.Emp;
import util.DBUtil;

public class EmpDao {
public List finAll(){
Connection con = null;
try {
con=DBUtil.getConnection();
String sql = "select * from student";
PreparedStatement ps = con.prepareStatement(sql);
List list = new ArrayList();
ResultSet rs = ps.executeQuery();
while(rs.next()){
Emp emp = new Emp();
emp.setEmpno(rs.getInt("empno"));
emp.setEname(rs.getString("ename"));
emp.setJob(rs.getString("job"));
emp.setSal(rs.getDouble("sal"));
list.add(emp);
}
return list;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("查询失败",e);
}finally{
DBUtil.close(con);

    }
}

}

请各位大神帮帮忙 谢谢

7个回答

500问题是响应问题,说明响应出错,org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver' 和 java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver 很明显的说明了你服务器中没有添加oracle6.jar类似的驱动包,添加进去就可以了

cyq6567916
cyqhaha 多谢,我把包放错地方了,我放在了main包里,应该放在WEB-INF包里。
3 年多之前 回复

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver'
这里说得很明白了,你没有添加Oracle用java连接的驱动包。

cyq6567916
cyqhaha 谢谢
3 年多之前 回复

产生错误的原因有太多可能,一般都是一些细节的问题,只能靠自己检查解决

cyq6567916
cyqhaha 多谢
3 年多之前 回复

应该是你部署web时没有把Oracle数据库的jar包部署到,检查下

cyq6567916
cyqhaha 谢谢
3 年多之前 回复

我检查两天了 而且直接把老师的代码复制过来也不行
jar包? 我测试是可以链接数据库的 但是用Sevlet就不行 我就是在Servlet工程包下测试的 jar包应该没有问题

细节我一步一步检查两天了 大神 你一句细节就给我打发走了。。。。
而且最后我直接复制老师的代码都没有用

应该是服务器端的问题

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
访问MySQL数据库报错?
eclipse下创建Java项目可以用c3p0获取数据库连接。 创建web项目登陆访问到数据库就报错,c3p0配置文件都一样的。两个项目报一样的错,请大神指点。非常感谢。 警告: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@aa811c5 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:812) at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3269) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1182) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2670) at com.mysql.jdbc.Connection.<init>(Connection.java:1531) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) java.sql.SQLException: Connections could not be acquired from the underlying database! at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:529) at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128) at org.apache.commons.dbutils.AbstractQueryRunner.prepareConnection(AbstractQueryRunner.java:156) at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:285) at cn.itcast.dao.UserDaoImple.login(UserDaoImple.java:18) at cn.itcast.service.UserService.login(UserService.java:11) at cn.itcast.action.UserServlet.login(UserServlet.java:127) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at cn.itcast.utils.BaseServlet.service(BaseServlet.java:33) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source. at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1319) at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557) at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525) ... 28 more java.lang.RuntimeException: 鐢ㄦ埛鐧诲綍澶辫触! at cn.itcast.dao.UserDaoImple.login(UserDaoImple.java:21) at cn.itcast.service.UserService.login(UserService.java:11) at cn.itcast.action.UserServlet.login(UserServlet.java:127) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at cn.itcast.utils.BaseServlet.service(BaseServlet.java:33) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) 十一月 14, 2018 6:23:21 下午 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run 警告: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@39f301dc -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:812) at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3269) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1182) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2670) at com.mysql.jdbc.Connection.<init>(Connection.java:1531) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 十一月 14, 2018 6:23:21 下午 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run 警告: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@62ae4cb6 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:812) at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3269) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1182) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2670) at com.mysql.jdbc.Connection.<init>(Connection.java:1531) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547)
创建WEB项目访问数据库报错?
借用别人的源代码,数据库自己按相同要求建的,调试的时候访问登录时访问数据库总是报错,求大神帮忙看一下是哪里出的问题?该怎么改?拜托。 警告: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@672870be -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:885) at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3421) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1247) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775) at com.mysql.jdbc.Connection.<init>(Connection.java:1555) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) 3月 26, 2019 3:57:37 下午 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run 警告: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@c3ea91a -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:885) at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3421) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1247) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775) at com.mysql.jdbc.Connection.<init>(Connection.java:1555) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) 3月 26, 2019 3:57:37 下午 com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask run 警告: com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask@67a370c4 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception: com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:921) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:885) at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3421) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1247) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775) at com.mysql.jdbc.Connection.<init>(Connection.java:1555) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:134) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:182) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:171) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:137) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1014) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:32) at com.mchange.v2.resourcepool.BasicResourcePool$AcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:547) java.sql.SQLException: Connections could not be acquired from the underlying database! at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:529) at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128) at org.apache.commons.dbutils.AbstractQueryRunner.prepareConnection(AbstractQueryRunner.java:156) at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:285) at cn.sy.dao.UserDao.login(UserDao.java:22) at cn.sy.service.UserService.login(UserService.java:13) at cn.sy.servlet.Login.doPost(Login.java:32) at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at cn.sy.filter.Vote_Filter.doFilter(Vote_Filter.java:84) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1156) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1539) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1495) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:835) Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source. at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1319) at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557) at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525) ... 32 more
servlet的dopost中写了控制台输出,测试到不执行数据库工具类后的代码,也不报错,会输出数据访问成功,连接到这个servlet成功的。
``` request.setCharacterEncoding("UTF-8"); System.out.println("数据访问成功"); String sql="select * from employee"; DBUtil dbUtil = new DBUtil(); List<Employee> employeeList=new ArrayList<Employee>(); System.out.println("开始执行查询"); ```
关于使用ConvertUtils.register控制台出现异常,导致向数据库中插入数据失败
我在idea里面在servlet里面使用 ConvertUtils.register(new DateLocaleConverter(), Date.class); BeanUtils.populate(user, request.getParameterMap()); 这俩个方法的时候(就是从表单里面获取数据封装到user里面,因为里面有Date型数据,所以使用ConvertUtils注册)一开始访问,直接浏览器500说是服务器的问题,然后发现只导入了beanutils的jar包没有导入logging的jar包,导入之后浏览器不报错但控制台就出现异常,导致后面将user的数据插入到数据库的 us.register(user)语句也执行失败,而且就是ConvertUtils.register(new DateLocaleConverter(), Date.class);这句的问题,删掉之后,就是下一句的问题异常如图:![图片说明](https://img-ask.csdn.net/upload/201912/25/1577205165_555562.png) ![图片说明](https://img-ask.csdn.net/upload/201912/25/1577205866_560947.png) 其中蓝色的错误就是上面俩句,希望有人解答一番,被这个错误给弄的烦死?
gwt连接数据库总是报错
下面的代码只不过是将eclipse或用webAppCreator产生的service类的方法体变了一下,然后错误就开始了, mysql与sqlserver都报错,说是没有权限访问.请问如何解决啊(不要说什么让我换个驱动,不通过gwt是可以正常取到数据的). public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { public String greetServer(String input) { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=zg", "sa", "sa"); List<String> userList = new ArrayList<String>(); Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(); rs = stmt.executeQuery("select * from user"); while (rs.next()) { userList.add(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3)); System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3)); } } catch (SQLException e) { e.printStackTrace(); } return userList.get(0); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } 异常: SEVERE: [1262763541078000] javax.servlet.ServletContext log: Exception while dispatching incoming RPC call com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String org.zengge.gwt.demo.client.GreetingService.greetServer(java.lang.String)' threw an unexpected exception: java.security.AccessControlException: access denied (java.net.SocketPermission localhost:1433 connect,resolve) at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:378) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:581) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:188) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:224) at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62) at javax.servlet.http.HttpServlet.service(HttpServlet.java:713) at javax.servlet.http.HttpServlet.service(HttpServlet.java:806) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1093) at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:51) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084) at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084) at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:121) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:712) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at com.google.apphosting.utils.jetty.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:70) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:139) at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:352) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:139) at org.mortbay.jetty.Server.handle(Server.java:313) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:506) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:844) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:644) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:381) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:396) at org.mortbay.thread.BoundedThreadPool$PoolThread.run(BoundedThreadPool.java:442) Caused by: java.security.AccessControlException: access denied (java.net.SocketPermission localhost:1433 connect,resolve) at java.security.AccessControlContext.checkPermission(Unknown Source) at java.security.AccessController.checkPermission(Unknown Source) at java.lang.SecurityManager.checkPermission(Unknown Source) at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:151) at java.lang.SecurityManager.checkConnect(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerConnectionSecurityManager.checkConnect(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.zengge.gwt.demo.server.GreetingServiceImpl.greetServer(GreetingServiceImpl.java:25) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:100) at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:562) ... 30 more
接手别人的JavaEE项目之前运行正确,添加访问数据库后报tomcat异常
我重装了tomcat,重新导入了项目又再将我修改的添加进去,运行时报tomcat异常,所以应当不是环境问题 报错截图:![图片说明](https://img-ask.csdn.net/upload/201507/18/1437188120_508314.png) 访问数据库按照MVC形式,数据显示在getData.jsp中,servlet为GetDServlet.java, 实现从数据库中取数据的类为getD.java,数据表对应的类为inemo_bean, 下面贴代码: package Servlet; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; //import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.Bean.inemo_bean; /** * Servlet implementation class GetDataServlet */ @WebServlet("/GetDataServlet") public class GetDServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public GetDServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().append("Served at: ").append(request.getContextPath()); GetD gd = new GetD(); ArrayList<inemo_bean> al = gd.getArrayList(); request.setAttribute("al", al); System.out.println("GetDataServlet.doGet()"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); System.out.println("GetDataServlet.doPost()"); } } package Servlet; import java.sql.SQLException; import java.util.ArrayList; import com.Bean.inemo_bean; import com.mysql.jdbc.Connection; import com.mysql.jdbc.ResultSet; import com.mysql.jdbc.Statement; import com.scut.older.db.DB; /** * Servlet implementation class getData * */ public class GetD { private Statement st = null; private ResultSet rs = null; private Connection ct = null; public ArrayList<inemo_bean> getArrayList() { ArrayList<inemo_bean> al = new ArrayList<inemo_bean>(); String sql = "select * from sensor_data_inemo"; ct = (Connection) new DB().getConn(); st = (Statement) new DB().getStatement(ct); rs = (ResultSet) new DB().getResultSet(st, sql); try { while (rs.next()) { inemo_bean ib = new inemo_bean(); ib.setId_sensor_data_iNEMO(rs.getInt("id_sensor_data_iNEMO")); ib.setDatetime(rs.getInt("datetime")); ib.setAccx(rs.getInt("accx")); ib.setAccy(rs.getInt("accy")); ib.setAccz(rs.getInt("accz")); ib.setGyrox(rs.getInt("gyrox")); ib.setGyroy(rs.getInt("gyroy")); ib.setGyroz(rs.getInt("gyroz")); ib.setMagx(rs.getInt("magx")); ib.setMagy(rs.getInt("magy")); ib.setMagz(rs.getInt("magz")); ib.setPress(rs.getInt("press")); ib.setTemp(rs.getInt("press")); ib.setAltitude(rs.getInt("altitude")); ib.setLongitude(rs.getInt("longitude")); ib.setLatitude(rs.getInt("latitude")); al.add(ib); } } catch (SQLException e) { e.printStackTrace(); System.out.println("getData.getArrayList()"); System.err.println("getdata()出错"); } finally { closeSource(); } return al; } private void closeSource() { try { if (rs != null) rs.close(); if (st != null) st.close(); if (ct != null) ct.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public GetD() { super(); } } <%@page import="com.Bean.inemo_bean"%> <%@page import="java.util.ArrayList"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Data from inemo</title> </head> <body> <h1>Get Data From DataBase -sensor_inemo_data</h1> <br> <a href="homepage.jsp"></a> <% ArrayList<inemo_bean> al = (ArrayList)request.getAttribute("al"); %> <table border="1" align="center"> <tr> <td>id_sensor_data_iNEMO</td> <td>datetime</td> <td>accx</td> <td>accy</td> <td>accz</td> <td>gyrox</td> <td>gyroy</td> <td>gyroz</td> <td>magx</td> <td>magy</td> <td>magz</td> <td>press</td> <td>temp</td> <td>altitude</td> <td>longitude</td> <td>latitude</td> </tr> <% for (int i = 1; i <= al.size(); i++) { inemo_bean inemo = al.get(i); %> <tr> <td><%=inemo.getId_sensor_data_iNEMO()%></td> <td><%=inemo.getDatetime()%></td> <td><%=inemo.getAccx()%></td> <td><%=inemo.getAccy()%></td> <td><%=inemo.getAccz()%></td> <td><%=inemo.getGyrox()%></td> <td><%=inemo.getGyroy()%></td> <td><%=inemo.getGyroz()%></td> <td><%=inemo.getMagx()%></td> <td><%=inemo.getMagy()%></td> <td><%=inemo.getMagz()%></td> <td><%=inemo.getPress()%></td> <td><%=inemo.getTemp()%></td> <td><%=inemo.getAltitude()%></td> <td><%=inemo.getLongitude()%></td> <td><%=inemo.getLatitude()%></td> </tr> <% } %> </table> </body> </html>
spring boot 项目访问controller报错
搭建最基本的spring boot项目,版本是2.0.4.RELEASE。 整合mybatis, 从数据库中查询数据。 我想 通过浏览器,直接访问controller,看到json格式的数据; 但是,控制台中能看到查询的数据,接下来就报错。 Controller ``` @Controller public class UserController { @Autowired private UserService userService; @GetMapping("/findAll") @ResponseBody public List<User> findAll(){ List<User> list = userService.findAll(); System.out.println(Arrays.toString(list.toArray())); return userService.findAll(); } } ``` 访问 http://localhost:1111/findAll ![浏览器端没有显示json格式数据](https://img-ask.csdn.net/upload/201808/21/1534843529_294415.png) 控制台先显示查询出来的数据,然后报错; ``` [User{id='122221', status='1', roleId='03bd3cc782b242bbab08c464ac35b0fa', remark='监控大盘', UpdateTime=2018-08-16 15:10:27.0}, User{id='12222221', status='1', roleId='03bd3cc782b242bbab08c464ac35b0fa', remark='监控大盘', UpdateTime=2018-08-16 15:10:27.0}, User{id='yyx', status='1', roleId='yyx0101', remark='监控大盘', UpdateTime=2018-08-16 15:10:27.0}] 2018-08-21 17:03:55.089 INFO 17728 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry : Running the evict task with compensationTime 410ms 2018-08-21 17:03:55.132 ERROR 17728 --- [nio-1111-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/module/jaxb/JaxbAnnotationIntrospector] with root cause java.lang.ClassNotFoundException: com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector ``` 按照之前的想法,加上了@ResponseBody 注解后,方法返回的数据应该被springboot内置的jackson,转换成了json格式的数据, 然后浏览器端直接显示的。 不知道问题出在哪里?
ssm框架,无法访问数据库Could not get JDBC Connection
用的德鲁伊连接池,先看applicationContext-dao.xml里的配置 ``` <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> <context:property-placeholder location="classpath:properties/*.properties" /> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="driverClassName" value="${jdbc.driver}" /> <property name="maxActive" value="10" /> <property name="minIdle" value="5" /> <!-- <property name="maxWait" value="5000" /> --> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.demo.mapper" /> </bean> </beans> ``` 这样的话,控制台输出: 2017-12-28 12:43:58,209DEBUG[org.springframework.web.servlet.DispatcherServlet] - <DispatcherServlet with name 'case' processing GET request for [/case/test]> 2017-12-28 12:43:58,214DEBUG[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - <Looking up handler method for path /test> 2017-12-28 12:43:58,221DEBUG[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - <Returning handler method [public com.demo.pojo.TbItem com.demo.controller.TestController.getItem(java.lang.Long)]> 2017-12-28 12:43:58,221DEBUG[org.springframework.beans.factory.support.DefaultListableBeanFactory] - <Returning cached instance of singleton bean 'testController'> 2017-12-28 12:43:58,222DEBUG[org.springframework.web.servlet.DispatcherServlet] - <Last-Modified value for [/case/test] is: -1> 2017-12-28 12:43:58,317DEBUG[org.mybatis.spring.SqlSessionUtils] - <Creating a new SqlSession> 2017-12-28 12:43:58,335DEBUG[org.mybatis.spring.SqlSessionUtils] - <Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@727efb8d]> 2017-12-28 12:43:58,366DEBUG[org.springframework.jdbc.datasource.DataSourceUtils] - <Fetching JDBC Connection from DataSource> 2017-12-28 12:43:58,447INFO[com.alibaba.druid.pool.DruidDataSource] - <{dataSource-1} inited> 一直显示等待,后来加了个maxWait属性,时间是5秒,然后才开始报错,如下: 2017-12-28 12:47:41,261DEBUG[org.springframework.web.servlet.DispatcherServlet] - <DispatcherServlet with name 'case' processing GET request for [/case/test]> 2017-12-28 12:47:41,264DEBUG[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - <Looking up handler method for path /test> 2017-12-28 12:47:41,269DEBUG[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - <Returning handler method [public com.demo.pojo.TbItem com.demo.controller.TestController.getItem(java.lang.Long)]> 2017-12-28 12:47:41,269DEBUG[org.springframework.beans.factory.support.DefaultListableBeanFactory] - <Returning cached instance of singleton bean 'testController'> 2017-12-28 12:47:41,270DEBUG[org.springframework.web.servlet.DispatcherServlet] - <Last-Modified value for [/case/test] is: -1> 2017-12-28 12:47:41,338DEBUG[org.mybatis.spring.SqlSessionUtils] - <Creating a new SqlSession> 2017-12-28 12:47:41,348DEBUG[org.mybatis.spring.SqlSessionUtils] - <Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3a67d807]> 2017-12-28 12:47:41,378DEBUG[org.springframework.jdbc.datasource.DataSourceUtils] - <Fetching JDBC Connection from DataSource> 2017-12-28 12:47:41,472INFO[com.alibaba.druid.pool.DruidDataSource] - <{dataSource-1} inited> 2017-12-28 12:47:46,473WARN[com.alibaba.druid.pool.DruidDataSource] - <not full timeout retry : 1> 2017-12-28 12:47:51,476DEBUG[org.mybatis.spring.SqlSessionUtils] - <Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3a67d807]> 2017-12-28 12:47:51,476DEBUG[org.mybatis.spring.SqlSessionUtils] - <Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3a67d807]> 2017-12-28 12:47:51,476DEBUG[org.mybatis.spring.SqlSessionUtils] - <Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3a67d807]> 2017-12-28 12:47:51,476DEBUG[org.springframework.jdbc.datasource.DataSourceTransactionManager] - <Should roll back transaction but cannot - no transaction available> 2017-12-28 12:47:51,478DEBUG[org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver] - <Resolving exception from handler [public com.demo.pojo.TbItem com.demo.controller.TestController.getItem(java.lang.Long)]: org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 5000, active 0 ### The error may exist in com/demo/mapper/TbItemMapper.xml ### The error may involve com.demo.mapper.TbItemMapper.selectByPrimaryKey ### The error occurred while executing a query 无法连接到数据库。。。。错误显示可能在/TbItemMapper.xml,这是mybatis逆向生成的,在其他项目中测试可用,所以问题应该不在这,其他配置文件啥的也感觉没问题,但就是连接不到数据库,问题出在哪??? TbItemMapper.xml: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.demo.mapper.TbItemMapper"> <resultMap id="BaseResultMap" type="com.demo.pojo.TbItem"> <id column="id" jdbcType="BIGINT" property="id" /> <result column="title" jdbcType="VARCHAR" property="title" /> <result column="sell_point" jdbcType="VARCHAR" property="sellPoint" /> <result column="price" jdbcType="BIGINT" property="price" /> <result column="num" jdbcType="INTEGER" property="num" /> <result column="barcode" jdbcType="VARCHAR" property="barcode" /> <result column="image" jdbcType="VARCHAR" property="image" /> <result column="cid" jdbcType="BIGINT" property="cid" /> <result column="status" jdbcType="TINYINT" property="status" /> <result column="created" jdbcType="TIMESTAMP" property="created" /> <result column="updated" jdbcType="TIMESTAMP" property="updated" /> </resultMap> <sql id="Example_Where_Clause"> <where> <foreach collection="oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Update_By_Example_Where_Clause"> <where> <foreach collection="example.oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List"> id, title, sell_point, price, num, barcode, image, cid, status, created, updated </sql> <select id="selectByExample" parameterType="com.demo.pojo.TbItemExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from tb_item <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tb_item where id = #{id,jdbcType=BIGINT} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long"> delete from tb_item where id = #{id,jdbcType=BIGINT} </delete> <delete id="deleteByExample" parameterType="com.demo.pojo.TbItemExample"> delete from tb_item <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.demo.pojo.TbItem"> insert into tb_item (id, title, sell_point, price, num, barcode, image, cid, status, created, updated) values (#{id,jdbcType=BIGINT}, #{title,jdbcType=VARCHAR}, #{sellPoint,jdbcType=VARCHAR}, #{price,jdbcType=BIGINT}, #{num,jdbcType=INTEGER}, #{barcode,jdbcType=VARCHAR}, #{image,jdbcType=VARCHAR}, #{cid,jdbcType=BIGINT}, #{status,jdbcType=TINYINT}, #{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP}) </insert> <insert id="insertSelective" parameterType="com.demo.pojo.TbItem"> insert into tb_item <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="title != null"> title, </if> <if test="sellPoint != null"> sell_point, </if> <if test="price != null"> price, </if> <if test="num != null"> num, </if> <if test="barcode != null"> barcode, </if> <if test="image != null"> image, </if> <if test="cid != null"> cid, </if> <if test="status != null"> status, </if> <if test="created != null"> created, </if> <if test="updated != null"> updated, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=BIGINT}, </if> <if test="title != null"> #{title,jdbcType=VARCHAR}, </if> <if test="sellPoint != null"> #{sellPoint,jdbcType=VARCHAR}, </if> <if test="price != null"> #{price,jdbcType=BIGINT}, </if> <if test="num != null"> #{num,jdbcType=INTEGER}, </if> <if test="barcode != null"> #{barcode,jdbcType=VARCHAR}, </if> <if test="image != null"> #{image,jdbcType=VARCHAR}, </if> <if test="cid != null"> #{cid,jdbcType=BIGINT}, </if> <if test="status != null"> #{status,jdbcType=TINYINT}, </if> <if test="created != null"> #{created,jdbcType=TIMESTAMP}, </if> <if test="updated != null"> #{updated,jdbcType=TIMESTAMP}, </if> </trim> </insert> <select id="countByExample" parameterType="com.demo.pojo.TbItemExample" resultType="java.lang.Long"> select count(*) from tb_item <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map"> update tb_item <set> <if test="record.id != null"> id = #{record.id,jdbcType=BIGINT}, </if> <if test="record.title != null"> title = #{record.title,jdbcType=VARCHAR}, </if> <if test="record.sellPoint != null"> sell_point = #{record.sellPoint,jdbcType=VARCHAR}, </if> <if test="record.price != null"> price = #{record.price,jdbcType=BIGINT}, </if> <if test="record.num != null"> num = #{record.num,jdbcType=INTEGER}, </if> <if test="record.barcode != null"> barcode = #{record.barcode,jdbcType=VARCHAR}, </if> <if test="record.image != null"> image = #{record.image,jdbcType=VARCHAR}, </if> <if test="record.cid != null"> cid = #{record.cid,jdbcType=BIGINT}, </if> <if test="record.status != null"> status = #{record.status,jdbcType=TINYINT}, </if> <if test="record.created != null"> created = #{record.created,jdbcType=TIMESTAMP}, </if> <if test="record.updated != null"> updated = #{record.updated,jdbcType=TIMESTAMP}, </if> </set> <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map"> update tb_item set id = #{record.id,jdbcType=BIGINT}, title = #{record.title,jdbcType=VARCHAR}, sell_point = #{record.sellPoint,jdbcType=VARCHAR}, price = #{record.price,jdbcType=BIGINT}, num = #{record.num,jdbcType=INTEGER}, barcode = #{record.barcode,jdbcType=VARCHAR}, image = #{record.image,jdbcType=VARCHAR}, cid = #{record.cid,jdbcType=BIGINT}, status = #{record.status,jdbcType=TINYINT}, created = #{record.created,jdbcType=TIMESTAMP}, updated = #{record.updated,jdbcType=TIMESTAMP} <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.demo.pojo.TbItem"> update tb_item <set> <if test="title != null"> title = #{title,jdbcType=VARCHAR}, </if> <if test="sellPoint != null"> sell_point = #{sellPoint,jdbcType=VARCHAR}, </if> <if test="price != null"> price = #{price,jdbcType=BIGINT}, </if> <if test="num != null"> num = #{num,jdbcType=INTEGER}, </if> <if test="barcode != null"> barcode = #{barcode,jdbcType=VARCHAR}, </if> <if test="image != null"> image = #{image,jdbcType=VARCHAR}, </if> <if test="cid != null"> cid = #{cid,jdbcType=BIGINT}, </if> <if test="status != null"> status = #{status,jdbcType=TINYINT}, </if> <if test="created != null"> created = #{created,jdbcType=TIMESTAMP}, </if> <if test="updated != null"> updated = #{updated,jdbcType=TIMESTAMP}, </if> </set> where id = #{id,jdbcType=BIGINT} </update> <update id="updateByPrimaryKey" parameterType="com.demo.pojo.TbItem"> update tb_item set title = #{title,jdbcType=VARCHAR}, sell_point = #{sellPoint,jdbcType=VARCHAR}, price = #{price,jdbcType=BIGINT}, num = #{num,jdbcType=INTEGER}, barcode = #{barcode,jdbcType=VARCHAR}, image = #{image,jdbcType=VARCHAR}, cid = #{cid,jdbcType=BIGINT}, status = #{status,jdbcType=TINYINT}, created = #{created,jdbcType=TIMESTAMP}, updated = #{updated,jdbcType=TIMESTAMP} where id = #{id,jdbcType=BIGINT} </update> </mapper> ``` 上面是逆向工程的mapper,后来我自己写了个TestMapper,还是出现同样的问题: ![图片说明](https://img-ask.csdn.net/upload/201712/28/1514454719_724728.png) 另外navicat访问数据库没问题。我想会不会是连接池配置的问题,也许那些配置可能导致这种情况??
Web项目部署在tomcat上,当执行到访问数据库操作时会报JDBCUtil初始化失败!
本人在是刚入门的小白。。在学习中,一直在陆续的写这个练手的项目-ebook,前几天的时候运行的都很正常,突然今天一运行就报错。。这是在MyEclipse中将项目部署在tomcat上的不过不是自带的tomcat,自己加的插件。 异常如下: ``` HTTP Status 500 - type Exception report message description The server encountered an internal error () that prevented it from fulfilling this request. exception javax.servlet.ServletException: java.lang.NoClassDefFoundError: Could not initialize class com.itany.jdbc.util.JDBCUtil org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:294) org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) root cause java.lang.NoClassDefFoundError: Could not initialize class com.itany.jdbc.util.JDBCUtil com.itany.jdbc.util.JDBCTemplate.query(JDBCTemplate.java:103) com.itany.ebook.dao.impl.ManagerDaoImpl.queryManagerById(ManagerDaoImpl.java:62) com.itany.ebook.service.impl.ManagerServiceImpl.queryManagerById(ManagerServiceImpl.java:44) com.itany.ebook.action.LoginAction.login(LoginAction.java:31) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270) org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) ``` 我的datasource.properties配置文件如下: driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/ebook?useUnicode=true&characterEncoding=utf8 username=root password= maxActive=10 initialSize=10 maxWait=5000 这是我的jar包以及刚刚异常的截图: ![图片说明](https://img-ask.csdn.net/upload/201610/01/1475332054_242487.png) ![图片说明](https://img-ask.csdn.net/upload/201610/01/1475332143_619533.png) 求大神。。膜拜膜拜!~~~~~~~~
web项目可以正常启动,但是打成war包放到tomcat中启动就报错???
用servlet写了一个小型项目,简单的实现了几个功能,没有使用任何框架,但是在maven中引入了spring依赖,因为用JDBCTemplate访问的数据库。 问题:项目写完后正常启动,但是打成war包放到Tomcat中启动就报错。错误信息显示:Cound not open ServletContext resource[\]; 个人见解:我没有使用框架,不需要配置web.xml,但是它启动就要访问web.xml,所以现在比较尴尬,不知道这个web.xml该怎么配。 求解:
使用jdbc链接sqlserver 2008出现Could not get JDBC Connection,项目可以启动,但不能访问数据库
JDBC:![图片说明](https://img-ask.csdn.net/upload/201909/03/1567504614_704721.png) mybatis:![图片说明](https://img-ask.csdn.net/upload/201909/03/1567504645_758618.png) jar包没问题,可以正常连接2005的数据库,链接这个2008的就不行了,求助各位大神啊 报错代码:### The error occurred while executing a query ### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (I/O Error: Connection reset)] with root cause java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:209) at java.net.SocketInputStream.read(SocketInputStream.java:141) at java.io.DataInputStream.readFully(DataInputStream.java:195) at java.io.DataInputStream.readFully(DataInputStream.java:169) at net.sourceforge.jtds.jdbc.SharedSocket.readPacket(SharedSocket.java:842) at net.sourceforge.jtds.jdbc.SharedSocket.getNetPacket(SharedSocket.java:723) at net.sourceforge.jtds.jdbc.ResponseStream.getPacket(ResponseStream.java:466) at net.sourceforge.jtds.jdbc.ResponseStream.read(ResponseStream.java:103) at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2206) at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:603) at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:357) at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50) at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184) at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38) at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582) at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556) at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545) at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388) at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) at org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:84) at org.mybatis.spring.transaction.SpringManagedTransaction.getConnection(SpringManagedTransaction.java:70) at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:336) at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:84) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:62) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:83) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:434) at com.sun.proxy.$Proxy17.selectList(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:231) at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59) at com.sun.proxy.$Proxy21.getproList(Unknown Source) at com.ytxd.service.DuplicateCheck.DuplicateCheckServiceImpl.getproList(DuplicateCheckServiceImpl.java:333) at com.ytxd.controller.DuplicateCheck.DuplicateCheck_Controller.GetList(DuplicateCheck_Controller.java:44) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349) at org.apache.coyote.http11.Http11Proce ssor.service(Http11Processor.java:783) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)
关于数据库连接(c3p0连接mysql)出现的问题
本来是想通过jsp页面添加一个数据,跳转到访问serlvlet页面通过jbutils连接mqsql保存数据,但是我检查了c3p0的配置文件和datasource对象,queryrunner对象都可以正常新建,具体问题找不到,谢谢大家了这是访问页面的报错代码 HTTP Status 500 - java.lang.RuntimeException: java.sql.SQLException: QueryRunner requires a DataSource to be invoked in this way, or a Connection should be passed in type Exception report message java.lang.RuntimeException: java.sql.SQLException: QueryRunner requires a DataSource to be invoked in this way, or a Connection should be passed in description The server encountered an internal error that prevented it from fulfilling this request. exception java.lang.RuntimeException: java.lang.RuntimeException: java.sql.SQLException: QueryRunner requires a DataSource to be invoked in this way, or a Connection should be passed in serviceimp.FoodTypeService.save(FoodTypeService.java:62) servlet.FoodTypeServlet.addFoodType(FoodTypeServlet.java:65) servlet.FoodTypeServlet.doGet(FoodTypeServlet.java:44) servlet.FoodTypeServlet.doPost(FoodTypeServlet.java:105) javax.servlet.http.HttpServlet.service(HttpServlet.java:643) javax.servlet.http.HttpServlet.service(HttpServlet.java:723) root cause java.lang.RuntimeException: java.sql.SQLException: QueryRunner requires a DataSource to be invoked in this way, or a Connection should be passed in daoimp.FoodTypeDao.save(FoodTypeDao.java:36) serviceimp.FoodTypeService.save(FoodTypeService.java:59) servlet.FoodTypeServlet.addFoodType(FoodTypeServlet.java:65) servlet.FoodTypeServlet.doGet(FoodTypeServlet.java:44) servlet.FoodTypeServlet.doPost(FoodTypeServlet.java:105) javax.servlet.http.HttpServlet.service(HttpServlet.java:643) javax.servlet.http.HttpServlet.service(HttpServlet.java:723) root cause java.sql.SQLException: QueryRunner requires a DataSource to be invoked in this way, or a Connection should be passed in org.apache.commons.dbutils.AbstractQueryRunner.prepareConnection(AbstractQueryRunner.java:200) org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:437) daoimp.FoodTypeDao.save(FoodTypeDao.java:34) serviceimp.FoodTypeService.save(FoodTypeService.java:59) servlet.FoodTypeServlet.addFoodType(FoodTypeServlet.java:65) servlet.FoodTypeServlet.doGet(FoodTypeServlet.java:44) servlet.FoodTypeServlet.doPost(FoodTypeServlet.java:105) javax.servlet.http.HttpServlet.service(HttpServlet.java:643) javax.servlet.http.HttpServlet.service(HttpServlet.java:723) note The full stack trace of the root cause is available in the Apache Tomcat/6.0.39 logs.
过一段时间,会报错GetConnectionTimeoutException
开始访问的时候一起正常,但是如果打开一个页面放置一段时间,再继续访问的时候高概率出现GetConnectionTimeoutException: wait millis 10, active 0, maxActive 800 连接数据库报错,但是刷新之后又一起正常。困扰好几个星期了,以下是报错 org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 10, active 0, maxActive 800 ### The error may exist in file [/usr/devops/tomcat-7.0.47/apache-tomcat-7.0.47/webapps/orderdish/WEB-INF/classes/isv/mapper/ShopIsvInfoMapper.xml] ### The error may involve com.eagle.isv.ShopIsvInfoMapper.selectShopidByKouBeiId ### The error occurred while executing a query ### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 10, active 0, maxActive 800 at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75) ~[mybatis-spring-1.2.2.jar:1.2.2] at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:371) ~[mybatis-spring-1.2.2.jar:1.2.2] at com.sun.proxy.$Proxy32.selectOne(Unknown Source) ~[?:?] at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:163) ~[mybatis-spring-1.2.2.jar:1.2.2] at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:68) ~[mybatis-3.2.8.jar:3.2.8] at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52) ~[mybatis-3.2.8.jar:3.2.8] at com.sun.proxy.$Proxy47.selectShopidByKouBeiId(Unknown Source) ~[?:?] at com.eagle.bussiness.ShopBussiness.getISVShopId(ShopBussiness.java:98) [ShopBussiness.class:?] at com.eagle.controller.PageController.scan(PageController.java:428) [PageController.class:?] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_102] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_102] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_102] at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_102] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) [spring-web-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) [servlet-api.jar:?] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.3.RELEASE.jar:4.3.3.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) [servlet-api.jar:?] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) [catalina.jar:7.0.47] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.47] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) [tomcat7-websocket.jar:7.0.47] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) [catalina.jar:7.0.47] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.47] at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71) [log4j-web-2.7.jar:2.7] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) [catalina.jar:7.0.47] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.47] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) [catalina.jar:7.0.47] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) [catalina.jar:7.0.47] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [catalina.jar:7.0.47] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) [catalina.jar:7.0.47] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) [catalina.jar:7.0.47] at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) [catalina.jar:7.0.47] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) [catalina.jar:7.0.47] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) [catalina.jar:7.0.47] at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) [tomcat-coyote.jar:7.0.47] at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603) [tomcat-coyote.jar:7.0.47] at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) [tomcat-coyote.jar:7.0.47] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [?:1.8.0_102] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [?:1.8.0_102] at java.lang.Thread.run(Thread.java:745) [?:1.8.0_102] Caused by: org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 10, active 0, maxActive 800 ### The error may exist in file [/usr/devops/tomcat-7.0.47/apache-tomcat-7.0.47/webapps/orderdish/WEB-INF/classes/isv/mapper/ShopIsvInfoMapper.xml] ### The error may involve com.eagle.isv.ShopIsvInfoMapper.selectShopidByKouBeiId ### The error occurred while executing a query ### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 10, active 0, maxActive 800
java项目连接mongoDB报错
在本地搭了环境,启动mongoDB数据库服务并进行了连接验证,如下: ![图片说明](https://img-ask.csdn.net/upload/201708/14/1502695838_396993.png) ![图片说明](https://img-ask.csdn.net/upload/201708/14/1502695905_168178.png) 启动eclipse,登录页面时会访问mongoDB,但总是连接超时,报错信息如下: org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}] at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:73) at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2002) at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1885) at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1696) at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1679) at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:598) at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:589) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByCondition(ManageUserServiceImpl.java:301) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByCondition(ManageUserServiceImpl.java:273) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByUserName(ManageUserServiceImpl.java:664) at com.jftt.wifi.action.LoginAction.login(LoginAction.java:369) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) 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) at java.lang.Thread.run(Unknown Source) Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}] at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:370) at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101) at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75) at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71) at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63) at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:166) at com.mongodb.operation.FindOperation.execute(FindOperation.java:394) at com.mongodb.operation.FindOperation.execute(FindOperation.java:57) at com.mongodb.Mongo.execute(Mongo.java:738) at com.mongodb.Mongo$2.execute(Mongo.java:725) at com.mongodb.DBCursor.initializeCursor(DBCursor.java:815) at com.mongodb.DBCursor.hasNext(DBCursor.java:149) at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1871) ... 49 more 请问各位大侠,有碰到这样的问题么?如何解决呢?
怎么maven项目部署之后不能访问servlet?
1.我用的myeclipse,servlet中的是ShowTable.java 在浏览器中能访问src/main/webapp中的index.jsp, 访问路径是http://localhost:8080/magSystem/index.jsp,能够显示出内容; 但是想要用servlet:http://localhost:8080/magSystem/ShowTable却404,还不会报错。。 http://localhost:8080/magSystem/servlet/ShowTable 会显示404并且有错误信息: ``` Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary. java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76) at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835) at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455) at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240) at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207) at java.sql.DriverManager.getConnection(DriverManager.java:664) at java.sql.DriverManager.getConnection(DriverManager.java:247) at com.zkz.magSystem.dao.BaseDAO.getConnection(BaseDAO.java:16) at com.zkz.magSystem.dao.BaseDAO.runSelect(BaseDAO.java:20) at com.zkz.magSystem.servlet.ShowTable.service(ShowTable.java:43) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61) at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85) at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132) at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2234) at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2258) at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319) at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966) at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825) ... 31 more ``` 我的其他配置以及目录如下: ## web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>ShowTable</servlet-name> <display-name>This is the display name of my J2EE component</display-name> <description>This is the description of my J2EE component</description> <servlet-class>com.zkz.magSystem.servlet.ShowTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShowTable</servlet-name> <url-pattern>/servlet/ShowTable</url-pattern> </servlet-mapping> </web-app> ``` ## ShowTable.java ``` package com.zkz.magSystem.servlet; import java.io.IOException; 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.servlet.jsp.jstl.sql.Result; import com.zkz.magSystem.dao.BaseDAO; @WebServlet("/uploadsevlet") public class ShowTable extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /** * Constructor of the object. */ public ShowTable() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub try { Result result = BaseDAO.runSelect("select * from ex1"); request.setAttribute("rows", result.getRows()); request.getRequestDispatcher("index.jsp").forward(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); response.sendRedirect("error.jsp"); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } } ``` ## BaseDAO.java ``` package com.zkz.magSystem.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.jsp.jstl.sql.Result; import javax.servlet.jsp.jstl.sql.ResultSupport; public class BaseDAO { public static Connection getConnection() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection("jdbc:mysql://localhost:3306/exam","root","qianmoZONGHENG"); } public static Result runSelect(String sql) throws Exception{ Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); //将在线结果集转化为离线结果集 Result result = ResultSupport.toResult(rs); close(conn,ps,rs); return result; } //数据库关闭语句 public static void close(Connection conn, PreparedStatement ps, ResultSet rs) { try { if (rs != null) { rs.close(); rs = null; } if (ps != null) { ps.close(); ps = null; } if (conn != null) { conn.close(); conn = null; } } catch (SQLException se) { se.printStackTrace(); } } } ``` ## index.jsp ``` <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ taglib prefix = "c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <table> <tr> <th>编号</th> <th>姓名</th> <th>电话</th> <th>状态</th> </tr> <c:forEach var="row" items="${rows }"> <tr> <td>${row.id }</td> <td>${row.name }/td> <td>${row.phone }</td> <td>${row.state }</td> </tr> </c:forEach> </table> </body> </html> ``` ![图片说明](https://img-ask.csdn.net/upload/201905/07/1557239537_160797.png) ![图片说明](https://img-ask.csdn.net/upload/201905/07/1557239544_525903.png)
数据库连接断开后还有操作的异常
用的springmvc+c3p0连接池,服务器tomcat,内存不是很大。 在其中某个模块的一些功能访问时,间歇性的会出现以下这种错误,基本都是:数据库链接断开后还有动作执行。随后就是OOM,服务器崩溃。 ERROR - 2015-10-08 09:07:24.187; org.hibernate.transaction.JDBCTransaction; JDBC rollback failed com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed. ​Caused by: java.lang.OutOfMemoryError: Java heap space ERROR - 2015-10-08 09:07:24.187; org.hibernate.transaction.JDBCTransaction; Could not toggle autocommit com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed. ​ 下面是刚刚报错的异常栈 ERROR - 2015-10-08 14:11:43.203; org.springframework.transaction.interceptor.TransactionAspectSupport; Application exception overridden by rollback exception org.hibernate.exception.JDBCConnectionException: could not load an entity: [net.shopxx.goodsmanagement.entity.GoodsShelve#12] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:99) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.loader.Loader.loadEntity(Loader.java:2041) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76) at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3294) at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496) at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477) at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227) at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:147) at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090) at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:1026) at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215) at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190) at net.shopxx.goodsmanagement.entity.GoodsShelve_$$_javassist_19.getShopManagerInfo(GoodsShelve_$$_javassist_19.java) at net.shopxx.service.impl.OrderServiceImpl.build(OrderServiceImpl.java:562) at net.shopxx.service.impl.OrderServiceImpl.create(OrderServiceImpl.java:825) at net.shopxx.service.impl.OrderServiceImpl.updateOrder(OrderServiceImpl.java:2117) at net.shopxx.service.impl.OrderServiceImpl$$FastClassByCGLIB$$42b70035.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631) at net.shopxx.service.impl.OrderServiceImpl$$EnhancerByCGLIB$$ed32199c.updateOrder(<generated>) at net.shopxx.zdlengineer.controller.ClientOrderController.updateOrder(ClientOrderController.java:342) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838) at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.planetj.servlet.filter.compression.CompressingFilter.doFilter(CompressingFilter.java:270) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at net.shopxx.filter.SiteStatusFilter.doFilterInternal(SiteStatusFilter.java:50) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) 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) at java.lang.Thread.run(Unknown Source) Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 0 milliseconds ago. The last packet sent successfully to the server was 271,625 milliseconds ago. ... 77 more Caused by: java.io.EOFException: Can not read response from server. Expected to read 5,349 bytes, read 1,362 bytes before connection was unexpectedly lost. at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3119) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3626) ... 95 more
ssm项目Tomcat启动报错
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'LoginDao': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'LoginMapper' is defined at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5017) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5531) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1574) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1564) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:748) Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'LoginMapper' is defined at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:641) at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1159) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:282) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:446) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:420) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:545) at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:305) ... 22 more 这是dao实现类 ``` @Repository("LoginDao") public class LoginDaoImpl implements LoginDao { @Resource(name = "LoginMapper") private LoginMapper LoginMapper; public LoginMapper getLoginMapper() { return LoginMapper; } public void setLoginMapper(LoginMapper loginMapper) { LoginMapper = loginMapper; } ``` 这是service实现类 ``` @Service("LoginService") public class LoginServiceImpl implements LoginService { @Resource private LoginDao LoginDao; ``` 配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 引入我们的database.properties,hibernate.properties文件 --> <bean id="property" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:database.properties</value><!-- classpath代表类路径,如src下面的文件 --> </list> </property> </bean> <!-- 定义使用C3P0连接池的数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <!-- 指定连接数据库的JDBC驱动 --> <property name="driverClass"> <value>${mysql.driver_class}</value> </property> <!-- 连接数据库所用的URL --> <property name="jdbcUrl"> <value>${mysql.connection.url}</value> </property> <!-- 连接数据库的用户名 --> <property name="user"> <value>${mysql.connection.username}</value> </property> <!-- 连接数据库的密码 --> <property name="password"> <value>${mysql.connection.password}</value> </property> <!-- 设置数据库连接池的最大连接数 --> <property name="maxPoolSize"> <value>30</value> </property> <!-- 设置数据库连接池的最小连接数 --> <property name="minPoolSize"> <value>2</value> </property> <!-- 设置数据库连接池的初始化连接数 --> <property name="initialPoolSize"> <value>2</value> </property> <!-- 设置数据库连接池的连接的最大空闲时间,单位为秒 --> <property name="maxIdleTime"> <value>10</value> </property> </bean> <!-- 启用自动扫描 --> <context:component-scan base-package="com.kachi.*"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /><!-- 排除注解为controller的类型 --> </context:component-scan> <!-- 配置SqlSessionFactoryBean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis.xml"/> <!-- mapper和resultmap配置路径 --> <property name="mapperLocations"> <list> <value>classpath:entity/config/*.xml</value> </list> </property> </bean> <!-- 自动扫描mapper接口,注入sqlsessionfactory --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.kachi.mapper"/> </bean> <!-- 开启 mybatis事务--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> </beans> springmvc配置文件 <?xml version="1.0" encoding="UTF-8"?> <!-- <mvc:annotation-driven/>该注解可以代替下面的两个注解 --> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" > <property name="messageConverters"> <list> <bean class = "org.springframework.http.converter.StringHttpMessageConverter"> <property name = "supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!-- 注解探测器 --> <context:component-scan base-package="com.kachi.controller"/> <!-- 静态资源访问 --> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <mvc:resources location="/font/" mapping="/font/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <!-- annotation默认的方法映射适配器 ,视图解析器,类似于action--> <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /><!-- 寻找类 --> <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /><!-- 根据url找方法 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
Spring MVC访问不了Controller
web.xml配置 ``` <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:DispatcherServlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置DispatcherServlet所需要拦截的url类型 --> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> ``` DispatcherServlet.xml配置 ``` <!-- 启用spring mvc 注解 --> <context:annotation-config /> <!-- 引入数据库配置文件 --> <import resource="classpath:jdbc.xml" /> <!-- 使Spring支持自动检测组件,如注解的Controller --> <context:component-scan base-package="com.user.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 启动spring MVC注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 自定义拦截器 --> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"> <property name="interceptors"> <list> <bean class="com.inteceptor.SelfInteceptor" /> </list> </property> </bean> <bean class="org.springframework.http.converter.StringHttpMessageConverter" > <constructor-arg value="UTF-8" index="0" /> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- JSP视图处理器(对模型视图名称的解析) --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> <!-- order数值越大优先级越低 --> <property name="order" value="2" /> </bean> ``` index.jsp配置 ``` $(function(){ $.ajax({ type:'post', url:'userController/getAllUsers.htm', data:{}, dataType:'html', success:function(){ alert(1111); }, error:function(XMLHttpRequest, textStatus, errorThrown){ alert(XMLHttpRequest.status); } }); }); ``` UserController配置 ``` @Controller @RequestMapping("/userController") public class UserController { @RequestMapping("/getAllUsers") @ResponseBody public String getAllUsers(){ System.out.println("lalallalalalalalallala"); return ""; } } ``` 最后访问:http://localhost:8080/zheng/index.jsp 可是后台没报错,浏览器打印了“1111”,就是没进controller层。。
SpringMVC3.2+hibernate4.2.5 多数据库注解 找不到实体问题
下面我只粘主要的配置文件和实体 applicationContext.xml <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:hsm-db-dchsqlserver.properties</value> <value>classpath:hsm-db-drhsqlserver.properties</value> </list> </property> </bean> <import resource="db-dch.xml" /> <import resource="db-drh.xml" /> 资源文件就不贴了,资源文件主要配置数据库驱动连接等相关配置 db-dch.xml ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683458_426800.png) ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683433_468361.png) ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683482_414961.png) db-drh.xml ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683619_647886.png) ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683631_436180.png) ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683683_883648.png) 两个数据库都有一个Employee的表,所以这里我分开两个实体 DCHEmployeeEntity ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683700_464099.png) DRHEmployeeEntity ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683710_847204.png) DAO也分两个 DCHEmployeeDAO ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683694_848628.png) DRHEmployeeDAO ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683747_220630.png) 目录结构 ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683756_255356.png) 控制类,项目访问 import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.dch.projects.dch.employee.entity.DCHEmployeeEntity; import com.dch.projects.dch.employee.service.IDCHEmployeeService; import com.dch.projects.drh.employee.entity.DRHEmployeeEntity; import com.dch.projects.drh.employee.service.IDRHEmployeeService; import com.dch.projects.oms.user.entity.UserEntity; import com.dch.projects.oms.user.service.IUserService; @Controller @RequestMapping("/") public class IndexController { @Autowired private IUserService userService; @Autowired private IDCHEmployeeService dchEmployeeService; @Autowired private IDRHEmployeeService drhEmployeeService; @RequestMapping("/main") public ModelAndView main(HttpServletRequest request) { List<UserEntity> listUsers=this.userService.getAllUsersByHql("from UserEntity"); for(UserEntity user:listUsers){ System.out.println(user.getName()); } List<DCHEmployeeEntity> listDCHEmployees=this.dchEmployeeService.getAllDCHEmployeesByHql("from DCHEmployeeEntity"); for(DCHEmployeeEntity employee:listDCHEmployees){ System.out.println("德诚行:"+employee.getEmpNo()+" "+employee.getEmpName()); } List<DRHEmployeeEntity> listDRHEmployees=this.drhEmployeeService.getAllDRHEmployeesByHql("from DRHEmployeeEntity"); for(DRHEmployeeEntity employee:listDRHEmployees){ System.out.println("德瑞行:"+employee.getEmpNo()+" "+employee.getEmpName()); } return new ModelAndView("index/main"); } } 后台错误 ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683806_403295.png) ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683774_999026.png) 页面错误,都一样 ![图片说明](https://img-ask.csdn.net/upload/201501/08/1420683824_221980.png) DCHEmployee这个能查出数据,就是DRHEmployee报错,配置那里看来看去都没什么问题,除了table的名字是一样,但如果我使用hibernate配置文件配置实体而不用注解的话是没问题,使用注解就出现这问题。 哪位大神帮看下问题出在哪里,谢谢了。
推荐 130 个令你眼前一亮的网站,总有一个用得着
总结了大学生活两年来,发现的 130 余个黑科技网站,总有一个会让你眼前一亮,赶紧收藏!
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
我在支付宝花了1分钟,查到了女朋友的开房记录!
在大数据时代下,不管你做什么都会留下蛛丝马迹,只要学会把各种软件运用到极致,捉奸简直轻而易举。今天就来给大家分享一下,什么叫大数据抓出轨。据史料证明,马爸爸年轻时曾被...
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
20道你必须要背会的微服务面试题,面试一定会被问到
写在前面: 在学习springcloud之前大家一定要先了解下,常见的面试题有那块,然后我们带着问题去学习这个微服务技术,那么就会更加理解springcloud技术。如果你已经学了springcloud,那么在准备面试的时候,一定要看看看这些面试题。 文章目录1、什么是微服务?2、微服务之间是如何通讯的?3、springcloud 与dubbo有哪些区别?4、请谈谈对SpringBoot 和S...
讲真,这两个IDE插件,可以让你写出质量杠杠的代码
周末躺在床上看《拯救大兵瑞恩》 周末在闲逛的时候,发现了两个优秀的 IDE 插件,据说可以提高代码的质量,我就安装了一下,试了试以后发现,确实很不错,就推荐给大家。 01、Alibaba Java 代码规范插件 《阿里巴巴 Java 开发手册》,相信大家都不会感到陌生,其 IDEA 插件的下载次数据说达到了 80 万次,我今天又贡献了一次。嘿嘿。 该项目的插件地址: https://github....
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
2020 年,大火的 Python 和 JavaScript 是否会被取而代之?
Python 和 JavaScript 是目前最火的两大编程语言,但是2020 年,什么编程语言将会取而代之呢? 作者 |Richard Kenneth Eng 译者 |明明如月,责编 | 郭芮 出品 | CSDN(ID:CSDNnews) 以下为译文: Python 和 JavaScript 是目前最火的两大编程语言。然而,他们不可能永远屹立不倒。最终,必将像其他编程语言一...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
Flutter 会不会被苹果限制其发展?
这个可能性是存在的,而且不止是 flutter、react-native 、weex 、uni-app 、taro 、Hippy等都存在这个风险,虽然有些框架对比起 flutter 其他框架存在时间稍长,但是这不可否认它们一直都存在这个风向。 只要不是平台自己的亲儿子,那么肯定存在被限制发展的风险,所以这件事上是风险和收益之间的博弈,这是一个“后妈和前任之间的太极。” 先说现状 如今各大平台,如:...
Idea 中最常用的10款插件(提高开发效率),一定要学会使用!
学习使用一些插件,可以提高开发效率。对于我们开发人员很有帮助。这篇博客介绍了开发中使用的插件。
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
最全最强!世界大学计算机专业排名总结!
我正在参与CSDN200进20,希望得到您的支持,扫码续投票5次。感谢您! (为表示感谢,您投票后私信我,我把我总结的人工智能手推笔记和思维导图发送给您,感谢!) 目录 泰晤士高等教育世界大学排名 QS 世界大学排名 US News 世界大学排名 世界大学学术排名(Academic Ranking of World Universities) 泰晤士高等教育世界大学排名 中国共...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
一个程序在计算机中是如何运行的?超级干货!!!
强烈声明:本文很干,请自备茶水!???? 开门见山,咱不说废话! 你有没有想过,你写的程序,是如何在计算机中运行的吗?比如我们搞Java的,肯定写过这段代码 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } ...
【蘑菇街技术部年会】程序员与女神共舞,鼻血再次没止住。(文末内推)
蘑菇街技术部的年会,别开生面,一样全是美女。
Linux必懂知识大总结(补)
关机 1. 数据同步写入磁盘 sync 为了加快对磁盘上文件的读写速度,位于内存中的文件数据不会立即同步到磁盘上,因此关机之前需要先进行 sync 同步操作。 2. shutdown # /sbin/shutdown [-krhc] [时间] [警告讯息] -k : 不会关机,只是发送警告讯息,通知所有在线的用户 -r : 将系统的服务停掉后就重新启动 -h : 将系统的服务停掉后就...
立即提问