mysql8.0 数据库中表的行数不显示,大小也不显示

请教下各位专家,目前数据库新安装了8.0版本,新建个表后往数据库的表中导入数据,或者将之前5.7的表恢复过来,都会出现个别表不显示行数,也不显示大小,打开表也能看到里面的数据,增减数据后也没有变化,是什么原因导致的呢?
图片说明

1个回答

Navicat上的信息没有同步,但是实际数据库是没有问题

weixin_42056745
从未完美过 感谢,去mysql 里看也是没有的,第二天就自动又显示了,很奇怪,感觉有缓存似的,而且没显示行数的情况下,索引也是用不了的
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
SSM链接mysql数据库问题Cannot create JDBC driver of class
八月 23, 2017 4:01:37 下午 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet [SpringMVC] in context with path [/liuyg] threw exception [Request processing failed; nested exception is 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 org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:127.0.0.1:3306/tjfx' ### The error may exist in file [D:\tomcat - liuyg\tomcat-7.0.81\webapps\liuyg\WEB-INF\classes\com\Mapping\xt_userMapper.xml] ### The error may involve com.Dao.xt_userMapper.selectByPrimaryKey ### 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 JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:127.0.0.1:3306/tjfx'] with root cause java.sql.SQLException: No suitable driver 配置文件如下 jdbc.properties --------- jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:127.0.0.1:3306/tjfx jdbc.username=root jdbc.password=root #定义初始连接数 jdbc.initialSize=0 #定义最大连接数 jdbc.maxActive=20 #定义最大空闲 jdbc.maxIdle=20 #定义最小空闲 jdbc.minIdle=1 #定义最长等待时间 jdbc.maxWait=600000 ---------- spring-mvc.xml ------------ <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com" /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置 --> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> --> <!-- <property name="prefix" value="/WEB-INF/welcome/" /> --> <!-- <property name="suffix" value=".htm" /> --> <!-- </bean> --> <!-- 静态资源处理--> <mvc:default-servlet-handler/> <!-- 注解驱动--> <mvc:annotation-driven></mvc:annotation-driven> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <!-- 视图模式配置,velocity配置文件--> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <property name="resourceLoaderPath" value="/welcome/" /> <property name="configLocation" value="classpath:velocity.properties" /> <property name="velocityProperties"> <props> <prop key="input.encoding">utf-8</prop> <prop key="output.encoding">utf-8</prop> </props> </property> </bean> <!-- 配置后缀 --> <bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="suffix" value=".htm" /> <property name="contentType" value="text/html;charset=UTF-8"></property> </bean> <import resource="spring-mybatis.xml"/> </beans> --------------- spring-mybatis.xml ------------------ <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com" /> <!-- 引入配置文件 --> <!-- 1.读取数据库配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="NEVER"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${jdbc.initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${jdbc.maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${jdbc.maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${jdbc.minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${jdbc.maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/Mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com/Dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> ----------------
springnvc+mybatis+C3P0连接池,一段时间数据库就崩溃了,求援~
云服务上有三个tomcat服务器,都启动一段时间后报异常,mysql数据库崩溃,求帮助,怎么配置都配置不行 applicationcontext中连接池配置 ``` <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!--连接池中保留的最小连接数。 --> <property name="minPoolSize" value="${minPoolSize}" /> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize" value="${maxPoolSize}" /> <!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime" value="${maxIdleTime}" /> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement" value="${acquireIncrement}" /> <!--c3p0全局的PreparedStatements缓存的大小。如果maxStatements与maxStatementsPerConnection均为0,则缓存不生效,只要有一个不为0,则语句的缓存就能生效。如果默认值:0 --> <property name="maxStatements" value="${maxStatements}" /> <property name="initialPoolSize" value="${initialPoolSize}" /> <!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,如设为0则无限期等待。单位毫秒。Default: 0 --> <property name="checkoutTimeout" value="${checkoutTimeout}" /> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}" /> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts" value="${acquireRetryAttempts}" /> <property name="breakAfterAcquireFailure" value="${breakAfterAcquireFailure}" /> <property name="testConnectionOnCheckout" value="${testConnectionOnCheckout}" /> <property name="connectionCustomizerClassName" value="com.tanwuapp.util.handler.UTF8MB4ConnectionCustomizer" /> </bean> ``` ``` minPoolSize=10 <!--连接池中保留的最大连接数。Default: 15 --> maxPoolSize=40 <!--最大空闲时间,30秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> maxIdleTime=30 <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> acquireIncrement=3 <!--c3p0全局的PreparedStatements缓存的大小。如果maxStatements与maxStatementsPerConnection均为0,则缓存不生效,只要有一个不为0,则语句的缓存就能生效。如果默认值: 0--> maxStatements=50 <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。默认值: 0 --> maxStatementsPerConnection=0 initialPoolSize=10 <!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,如设为0则无限期等待。单位毫秒。Default: 0 --> checkoutTimeout=10000 <!--每30秒检查所有连接池中的空闲连接。Default: 0 --> idleConnectionTestPeriod=30 <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> acquireRetryAttempts=30 breakAfterAcquireFailure=true testConnectionOnCheckout=false ``` 异常信息: ``` 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 org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.) ### The error may exist in file [/home/webapps/tomcat-1.2.1/tanwuapps/TanWuAppAPI_v1.2.1/WEB-INF/classes/com/tanwuapp/dao/mapper/BasBannerMapper.xml] ### The error may involve com.tanwuapp.dao.BasBannerDao.findAllInfo ### 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 (Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.) at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:371) at com.sun.proxy.$Proxy9.selectList(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:198) at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:119) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:63) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52) at com.sun.proxy.$Proxy42.findAllInfo(Unknown Source) at com.tanwuapp.service.impl.HomePageServiceImpl.getBannerList(HomePageServiceImpl.java:55) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198) at com.sun.proxy.$Proxy46.getBannerList(Unknown Source) at com.tanwuapp.controller.ProductSearchController.searchHomeBannerData(ProductSearchController.java:78) at com.tanwuapp.controller.ProductSearchController$$FastClassBySpringCGLIB$$1b828f00.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:700) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.cache.interceptor.CacheInterceptor$1.invoke(CacheInterceptor.java:58) at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:211) at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:66) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:633) at com.tanwuapp.controller.ProductSearchController$$EnhancerBySpringCGLIB$$f6dc0725.searchHomeBannerData(<generated>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.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:953) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829) 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:169) 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:436) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: org.apache.ibatis.exceptions.PersistenceException: ```
启动tomcat后,只要有数据操作mysql服务就自动关闭?
今天把项目部署到服务器上时,报了一个error。 后来检查发现,mysql服务停止了,但是之前服务已经启动了。经过几次测试发现,没启动tomcat时,使用Navicat对数据库操作不会有问题,只要启动项目,一有数据操作就会自动停止mysql服务,这是什么情况? 错误信息如下: 2017-11-01 08:49:35,007 ERROR [com.alibaba.druid.pool.DruidDataSource] - create connection error, url: jdbc:mysql://192.168.251.229:3306/creditteaching?useUnico de=true&characterEncoding=utf-8, errorCode 0, state 08S01 com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link fai lure The last packet sent successfully to the server was 0 milliseconds ago. The driv er has not received any packets from the server. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct orAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC onstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1 127) at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:356) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2502) at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2 539) at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2321) at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832) at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct orAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC onstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java :344) at com.alibaba.druid.filter.FilterChainImpl.connection_connect(FilterCha inImpl.java:148) at com.alibaba.druid.filter.stat.StatFilter.connection_connect(StatFilte r.java:211) at com.alibaba.druid.filter.FilterChainImpl.connection_connect(FilterCha inImpl.java:142) at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnecti on(DruidAbstractDataSource.java:1410) at com.alibaba.druid.pool.DruidAbstractDataSource.createPhysicalConnecti on(DruidAbstractDataSource.java:1464) at com.alibaba.druid.pool.DruidDataSource$CreateConnectionThread.run(Dru idDataSource.java:1969) Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketI mpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.ja va:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocket Impl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java :182) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at java.net.Socket.<init>(Socket.java:425) at java.net.Socket.<init>(Socket.java:241) at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.ja va:258) at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:306) ... 18 more 数据源使用的时druid,配置信息如下: <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass --> <property name="driverClassName" value="${jdbc.driver}" /> <!-- 基本属性 url、user、password --> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="1" /> <property name="minIdle" value="3" /> <property name="maxActive" value="20" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="validationQuery" value="${jdbc.testSql}" /> <property name="testWhileIdle" value="true" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用) <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="20" /> --> <!-- 配置监控统计拦截的filters --> <property name="filters" value="stat" /> </bean>
c3p0+mysql session资源不释放
程序正常启动后获得正常的连接数,在设定的时间内也正常释放了,但是一旦用户登录后数据库的连接sleep就超过设置的时间不再释放,程序中opensession的地方也已经手动关闭了,请问各位是属于什么问题? hibernate.cfg.xml配置文件如下: [code="java"] <session-factory> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.default_schema">demo_new</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/demo_new</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 连接池 --> <property name="hibernate.connection.provider_class"> org.hibernate.connection.C3P0ConnectionProvider</property> <property name="hibernate.current_session_context_class">thread</property> <!-- 间隔多少秒检查空闲的连接,这里为了测试设置为30秒--> <property name="hibernate.c3p0.idle_test_period">30</property> <!-- hibernate.c3p0.timeout是设置c3p0.maxIdleTime,单位是秒 ,这里为了测试设置为30秒--> <property name="hibernate.c3p0.timeout">30</property> <!-- 最大连接数--> <property name="hibernate.c3p0.max_size">300</property> <!-- 保持最小的连接数--> <property name="hibernate.c3p0.min_size">15</property> <!-- 每次获取连接的数量 --> <property name="hibernate.c3p0.acquire_increment">5</property> <property name="hibernate.bytecode.use_reflection_optimizer"> false </property> <!-- JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 --> <property name="hibernate.c3p0.max_statements">50</property> <!--Fetch Size 是设定JDBC的Statement读取数据的时候每次从数据库中取出的记录条数--> <property name="hibernate.jdbc.fetch_size">100</property> <!--Batch Size是设定对数据库进行批量删除,批量更新和批量插入的时候的批次大小,有点相当于设置Buffer缓冲区大小的意思--> <property name="hibernate.jdbc.batch_size">50</property> <!-- + | 在数据插入数据库之后,允许使用JDBC3 PreparedStatement.getGeneratedKeys() | 来获取数据库生成的key(键)。需要JDBC3+驱动和JRE1.4+, | 如果你的数据库驱动在使用Hibernate的标 识生成器时遇到问题,请将此值设为false. | 默认情况下将使用连接的元数据来判定驱动的能力. + --> <property name="hibernate.jdbc.use_get_generated_keys">true</property> <!-- 强制Hibernate按照被更新数据的主键,为SQL更新排序。这么做将减少在高并发系统中事务的死锁。 --> <property name="hibernate.order_updates">true</property> <property name="hibernate.connection.charSet">utf8</property> <property name="hibernate.connection.characterEncoding">utf8</property> <property name="hibernate.connection.useUnicode">true</property> <property name="hibernate.show_sql">false</property> <property name="hibernate.format_sql">false</property> <property name="hibernate.use_sql_comments">false</property> <mapping package="com.pjgw.assetsys.entity" /> ........ [/code]
请教:spring配置mysql/access多数据源的动态切换问题,急用,十分感谢!
请教:spring配置mysql/access多数据源在切换到access数据源时抛No Session found for current thread错误是怎么回事?请大侠详加指导,十分感谢,急用!我的配置文件如下: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" 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 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd" default-autowire="byName" default-lazy-init="false"> <!-- 自动扫描dao和service包(自动注入) --> <context:component-scan base-package="org.framework.core.common.dao.*" /> <context:component-scan base-package="org.framework.core.common.service.*" /> <!-- 加载service,此时要排除要controller,因为controller已经spring-mvc中加载过了 --> <context:component-scan base-package="test.*,framework.*"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:dbconfig.properties" /> <!-- 配置数据源1 --> <bean name="mysqlDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url.mysql}" /> <property name="username" value="${jdbc.username.jeecg}" /> <property name="password" value="${jdbc.password.jeecg}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> <property name="validationQuery" value="${validationQuery.sqlserver}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> </bean> <!-- 数据源2 : access数据源 --> <bean id="accessDataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="sun.jdbc.odbc.JdbcOdbcDriver" /> <property name="url" value="jdbc:odbc:users" /> <property name="username" value="" /> <property name="password" value="" /> </bean> <!-- access sessionFactory --> <bean id="aceessSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="accessDataSource" /> <property name="hibernateProperties"> <props> <!-- access 语法和MSSQL相似 所以用的MSSQL方言,或者可以使用第三方方言 --> <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> <prop key="hibernate.jdbc.batch_size">30</prop> <prop key="hibernate.jdbc.fetch_size">50</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">false</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- 数据源集合 --> <bean id="dataSource" class="org.jeecgframework.core.extend.datasource.DynamicDataSource"> <property name="targetDataSources"> <map key-type="org.jeecgframework.core.extend.datasource.DataSourceType"> <entry key="mysqlDataSource" value-ref="mysqlDataSource" /> </map> </property> <property name="defaultTargetDataSource" ref="mysqlDataSource" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="entityInterceptor" ref="hiberAspect"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop> </props> </property> <!-- 注解方式配置 --> <property name="packagesToScan"> <list> <value>system.pojo.*</value> <value>demo.entity.*</value> <value>test.entity.*</value> <value>test.bussiness.db.UserInfo</value> </list> </property> </bean> <bean id="accessJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="accessDataSource"/> </property> </bean> <bean id="accessTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="aceessSessionFactory"></property> </bean> <tx:advice id="txAdvice" transaction-manager="accessTransactionManager"> <tx:attributes> <tx:method name="exists" read-only="true" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config proxy-target-class="true"> <aop:advisor advice-ref="txAdvice" pointcut="execution(* cors.bussiness.db..*.*(..))" /> </aop:config> <!-- JDBC配置 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <!-- JDBC配置 --> <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource" /> </bean> <!-- 配置事物管理器,在*ServiceImpl里写@Transactional就可以启用事物管理 --> <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
SSM框架下,数据库放置在docker下 拒绝访问的问题
一个简单的评价系统,使用的SSM框架。 最近将项目迁移到liunx系统上(deepin 15.4) IDE是idea 数据库是 mysql 因为想测试docker的功能,将数据库迁移到了docker镜像上, **使用jdbc驱动的方式访问docker的数据库,一切正常。** 使用mybatis的数据连接池,访问失败,提示拒绝访问。一直得不到Connection。 非常疑惑 docker开放端口如下: ![docker开放端口](https://img-ask.csdn.net/upload/201706/15/1497497259_204023.png) jdbc.properties 文件内容如下: ``` jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3303/teachercommentdb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC jdbc.username=root jdbc.password=794613 ``` spring-mybatis配置整合文件内容如下: ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="zyp"/> <!-- 第一种方式:加载一个properties文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!-- 第二种方式:加载多个properties文件 <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:common.properties</value> </list> </property> <property name="fileEncoding" value="UTF-8"/> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configProperties"/> </bean> --> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"/> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"/> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"/> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"/> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"/> </bean> <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:zyp/mapping/*.xml"/> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="zyp.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` 提示如下错误,但跟网上说明的原因不太一样,不是超时连接,也不是用户名错误等。 ``` Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)] with root cause java.net.ConnectException: 拒绝连接 (Connection refused) ```
org.hibernate.HibernateException: No Session found for current thread
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p><span style="font-size: 12px; line-height: 1.5;">hibernate:4.1.6</span><br style="line-height: 24px; background-color: #f2f8ef;"><span style="font-size: 12px; line-height: 1.5;">spring:4.0.1<br></span></p> <p> </p> <p><span style="font-size: 12px; line-height: 1.5;">工程启动没错,进入getAllUser页面获得数据库用户信息时报如下错误: </span></p> <p> </p> <p>严重: Servlet.service() for servlet springMVC threw exception</p> <p>org.hibernate.HibernateException: No Session found for current thread</p> <p>at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:106)</p> <p>at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941)</p> <p>at com.mlf.web.controller.dao.UserDAO.getAllUser(UserDAO.java:27)</p> <p>at com.mlf.web.controller.service.UserManager.getAllUser(UserManager.java:28)</p> <p>at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)</p> <p>at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)</p> <p>at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)</p> <p>at java.lang.reflect.Method.invoke(Method.java:597)</p> <p>at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)</p> <p>at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)</p> <p>at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)</p> <p>at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)</p> <p>at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)</p> <p>at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)</p> <p>at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)</p> <p>at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)</p> <p>at $Proxy19.getAllUser(Unknown Source)</p> <p>at com.mlf.web.controller.UserController.getAllUser(UserController.java:36)</p> <p>at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)</p> <p>at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)</p> <p>at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)</p> <p>at java.lang.reflect.Method.invoke(Method.java:597)</p> <p>at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)</p> <p>at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)</p> <p>at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)</p> <p>at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)</p> <p>at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)</p> <p>at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)</p> <p>at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)</p> <p>at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)</p> <p>at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)</p> <p>at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)</p> <p>at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)</p> <p>at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)</p> <p>at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)</p> <p>at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149)</p> <p>at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)</p> <p>at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)</p> <p>at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)</p> <p>at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)</p> <p>at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)</p> <p>at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)</p> <p>at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)</p> <p>at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)</p> <p>at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)</p> <p>at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)</p> <p>at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617)</p> <p>at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1760)</p> <p>at java.lang.Thread.run(Thread.java:619)</p> <p>-----------------------------------------------------------------------------------------------------------------------------------------</p> <p>hibernate.cfg.test.xml(com.mlf.web.controller.hibernate)</p> <p> </p> <pre name="code" class="xml">&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"&gt; &lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;mapping class="com.mlf.web.controller.entity.User"/&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt;</pre> <p> <span style="font-size: 12px; line-height: 1.5;">-----------------------------------------------------------------------------------------------------------------------------------------</span></p> <p> </p> <p><span style="font-size: 12px; line-height: 1.5;">applicationContext.xml(com.mlf.web.controller.spring)</span></p> <p> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [ &lt;!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml"&gt; ]&gt; &lt;beans&gt; &lt;bean id="userDao" class="com.mlf.web.controller.dao.UserDAO"&gt; &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="userManagerBase" class="com.mlf.web.controller.service.UserManager"&gt; &lt;property name="userDao" ref="userDao"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="userManager" parent="transactionBese"&gt; &lt;property name="target" ref="userManagerBase"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </pre> <p> <span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;">-----------------------------------------------------------------------------------------------------------------------------------------</span></p> <p> </p> <p><span style="font-size: 12px; line-height: 1.5;">spring-annotation.xml(包:config)</span></p> <p> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"&gt; &lt;!-- 扫描包 --&gt; &lt;context:component-scan base-package="com.mlf.web.controller"&gt;&lt;/context:component-scan&gt; &lt;!-- 开启注解 --&gt; &lt;mvc:annotation-driven/&gt; &lt;!-- &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt;&lt;/bean&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&gt;&lt;/bean&gt; --&gt; &lt;!-- 静态资源访问 --&gt; &lt;mvc:resources location="/img/" mapping="/img/**"/&gt; &lt;mvc:resources location="/js/" mapping="/js/**"/&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/"&gt;&lt;/property&gt; &lt;property name="suffix" value=".jsp"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;!-- 配置文件上传解析器 --&gt; &lt;bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"&gt; &lt;property name="defaultEncoding" value="utf-8"/&gt; &lt;!-- 文件最大值 --&gt; &lt;property name="maxUploadSize" value="10485760000"/&gt; &lt;!-- 缓存大小 --&gt; &lt;property name="maxInMemorySize" value="40960"/&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> <span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;">-----------------------------------------------------------------------------------------------------------------------------------------</span></p> <p> </p> <p><span style="font-size: 12px; line-height: 1.5;">spring-core.xml(</span><span style="font-size: 12px; line-height: 1.5;">包:config</span><span style="font-size: 12px; line-height: 1.5;">)</span></p> <p> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [ &lt;!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml"&gt; ]&gt; &lt;beans&gt; &lt;import resource="classpath:com/mlf/web/controller/spring/applicationContext.xml"/&gt; &lt;/beans&gt; </pre> <p> <span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;">-----------------------------------------------------------------------------------------------------------------------------------------</span></p> <p> </p> <p><span style="font-size: 12px; line-height: 1.5;">spring-hibernate.xml(</span><span style="font-size: 12px; line-height: 1.5;">包:config</span><span style="font-size: 12px; line-height: 1.5;">)</span></p> <p> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [ &lt;!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml"&gt; ]&gt; &lt;beans&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="com.mysql.jdbc.Driver"&gt;&lt;/property&gt; &lt;property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;amp;characterEncodeing=utf-8"&gt;&lt;/property&gt; &lt;property name="username" value="root"&gt;&lt;/property&gt; &lt;property name="password" value="donny2014"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLInnoDBDialect&lt;/prop&gt; &lt;!-- 自动更新 --&gt; &lt;prop key="hibernate.hbm2ddl.auto"&gt;update&lt;/prop&gt; &lt;!-- 在控制台打印SQL语句 --&gt; &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt; &lt;!-- 将SQL脚本进行格式化后再输出 --&gt; &lt;prop key="hibernate.format_sql"&gt;true&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="configLocations"&gt; &lt;list&gt; &lt;value&gt; classpath:com/mlf/web/controller/hibernate/hibernate.cfg.test.xml &lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;!-- 配置事务 --&gt; &lt;bean id="transactionBese" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true"&gt; &lt;property name="transactionManager" ref="transactionManager"&gt;&lt;/property&gt; &lt;property name="transactionAttributes"&gt; &lt;props&gt; &lt;prop key="add*"&gt;PROPAGATION_REQUIRED,-Exception&lt;/prop&gt; &lt;prop key="update*"&gt;PROPAGATION_REQUIRED,-Exception&lt;/prop&gt; &lt;prop key="insert*"&gt;PROPAGATION_REQUIRED,-Exception&lt;/prop&gt; &lt;prop key="modify*"&gt;PROPAGATION_REQUIRED,-Exception&lt;/prop&gt; &lt;prop key="delete*"&gt;PROPAGATION_REQUIRED,-Exception&lt;/prop&gt; &lt;prop key="get*"&gt;PROPAGATION_NEVER&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </pre> <p> <span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;"> </span><span style="font-size: 12px; line-height: 1.5;">-----------------------------------------------------------------------------------------------------------------------------------------</span></p> <p> </p> <p><span style="font-size: 12px; line-height: 1.5;">UserController.java(包:</span><span style="font-size: 12px; line-height: 1.5;">com.mlf.web.controller</span><span style="font-size: 12px; line-height: 1.5;">)</span></p> <p> </p> <pre name="code" class="java">package com.mlf.web.controller; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.mlf.web.controller.entity.User; import com.mlf.web.controller.service.IUserManager; @Controller @RequestMapping("/user") public class UserController { @Resource(name="userManager") private IUserManager userManager; @RequestMapping("/toAddUser") public String toAddUser(){ return "/addUser"; } @RequestMapping("/addUser") public String addUser(User user){ userManager.addUser(user); return "/success"; } @RequestMapping("/getAllUser") public String getAllUser(HttpServletRequest request){ List&lt;User&gt; user = userManager.getAllUser(); request.setAttribute("user", user); return "/userManager"; } } </pre> <p> </p> </div>
有没有大神能指点一下哪里错了。。。。
package Frame; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.*; import javax.swing.*; import db.DButil; public class login extends JFrame implements ActionListener{ private JPanel jp=new JPanel(); //创建标签数组 private JLabel[] jlArray={new JLabel("用户名"), new JLabel("密 码"),new JLabel("")}; private JButton jb1; private JButton jb2; private JButton jb3; private JTextField jtf=new JTextField(); private JPasswordField jpf=new JPasswordField(); //布局构造实现方法 public login(){ Icon icon1=new ImageIcon("login.jpg"); Icon icon2=new ImageIcon("reset.jpg"); Icon icon3=new ImageIcon("zhuce.jpg"); JPanel jp=new JPanel(){ protected void paintComponent(Graphics g) { ImageIcon icon = new ImageIcon("bg.jpg"); Image img = icon.getImage(); g.drawImage(img, 0, 0, icon.getIconWidth(), icon.getIconHeight(), icon.getImageObserver()); }}; jp.setLayout(null); jb1=new JButton(icon1); jb2=new JButton(icon3); jb3=new JButton(icon2); jlArray[0].setBounds(70,120,90,32); jb1.setBounds(365,110,130,60); jb2.setBounds(365,170,130,60); jlArray[1].setBounds(70,170,90,32); //将标签与按钮添加到JPanel容器中 jp.add(jlArray[0]); jp.add(jlArray[1]); jp.add(jb1); jp.add(jb2); jb1.addActionListener(this); jb2.addActionListener(this);//为按钮注册动作事件监听器 //添加修改密码的按钮 jb3.setBounds(365,230,130,60); jp.add(jb3); jp.add(jtf); jtf.setBounds(140,120,180,30);//设置文本框位置 jp.add(jpf); jpf.setBounds(140,170,180,30);//设置密码框位置 jpf.setEchoChar('*'); //密码显示字符形式 jpf.addActionListener(this); //为密码框注册动作事件监听器 this.setVisible(true);//设置窗体的可见性 jpf.addActionListener(this); //为密码框注册动作事件监听器 //设置用于显示登陆状态的标签大小位置,并将其添加进JPanel容器 jlArray[2].setBounds(70,220,300,30); jp.add(jlArray[2]); this.setTitle("登陆");//设置窗体标题 this.setBounds(450,200,500,318);//设置窗体的大小 this.setResizable(false);//设置窗体不让用户调整大小 this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setVisible(true);//设置窗体的可见性 this.add(jp);//将窗体添加到面板中 jp.setBackground(Color.blue); } public static void main(String[] args) { new login();//创建登陆窗体 } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub //得到用户名与密码 String user=jtf.getText().trim(); String pwd=String.valueOf(jpf.getPassword());//返回密码的字符串表示方式 String sql=""; if(e.getSource()==jtf){//事件源为文本框,切换焦点到密码框 jpf.requestFocus(); } else if(e.getSource()==jb1||e.getSource()==jpf){ //判断用户名和密码是否匹配 查询数据库 if(DButil.check(user, pwd)){ //登陆成功 MainFrame mf=new MainFrame(jtf.getText());//主窗体 this.dispose(); } else{ //登陆失败 jlArray[2].setText("对不起,非法的用户名和密码"); this.clear(); } } else if(e.getSource()==jb2) {//事件源为注册按钮 if(user.equals("")||pwd.equals("")) {//如果注册的用户名为空或者密码为空 jlArray[2].setText("用户名和密码都不得为空!!!"); this.clear();//清空输入文本框 } else { sql="select uid from user where uid='"+user+"'"; if(DButil.isExist(sql)) {//用户名已经存在 jlArray[2].setText("对不起,用户名已存在!!!"); this.clear();//清空输入文本框 } else { sql="insert into user values('"+user+"','"+pwd+"')"; if(DButil.update(sql)>0) {//注册成功 jlArray[2].setText("恭喜您!!!注册成功,请登陆"); } } } } else if(e.getSource()==jb3)//修改密码的监听 { //判断是否已经输入用户名和密码 if(user.equals("")||pwd.equals("")) { jlArray[2].setText("修改密码先输入正确的用户名和密码!!!"); this.clear();//清空输入文本框 } //判断是否输入了正确的用户名和密码 else if(DButil.check(user,pwd)) { //正确的用户名和密码 String password=JOptionPane.showInputDialog(this,"修改密码:","请输入新密码", JOptionPane.PLAIN_MESSAGE); //得到新的密码为空 if(password==null||password.equals("")) { JOptionPane.showMessageDialog(this,"密码不得为空!!!","错误", JOptionPane.WARNING_MESSAGE); } else {//密码不为空 sql="update user set pwd='"+password+"' where uid='"+user+"'";//更新密码的SQL if(DButil.update(sql)>0) {//密码修改成功 this.clear();//清空输入文本框 jlArray[2].setText("恭喜您!!!密码修改成功,请用新密码登陆"); } } } else { JOptionPane.showMessageDialog(this,"用户名或者密码错误!!!","错误", JOptionPane.WARNING_MESSAGE); this.clear();//清空输入文本框 } } } package Frame; import javax.swing.*; import javax.swing.table.DefaultTableModel; import db.DButil; import java.awt.*; import java.awt.event.*; import java.sql.*; import java.io.*; import java.util.*; public class MainFrame extends JFrame implements ActionListener,ItemListener { private String uname=null;//当前用户的名字 private boolean isInsert=false;//是否为添加默认为否 private JPanel topjp=new JPanel();//界面上半部分的JPanel容器 private JButton jba=new JButton("模糊查询"); private JButton jbs=new JButton("查找"); private JTextField jtfs=new JTextField();//按给出信息查找联系人信息 private JRadioButton jrbxm=new JRadioButton("按姓名查找",true); private JRadioButton jrbbh=new JRadioButton("按学号查找",false); private ButtonGroup bg=new ButtonGroup();//单选按钮组 private JPanel jpbr=new JPanel();//单选按钮面板 private JPanel jpyInfo=new JPanel();//右侧显示个人信息的面板 private JTextArea jta=new JTextArea(); // 模糊查询得到的信息文本区 private JLabel[] jlInfo={new JLabel("学号:"),new JLabel("姓名:"), new JLabel("性别:"),new JLabel("出生日期:"), new JLabel("电话号码:"),new JLabel("QQ:"), new JLabel("Email:"),new JLabel("地址:"), new JLabel("添加相片")}; private JButton[] jbInfo={new JButton("编辑"),new JButton("保存"), new JButton("浏览"), new JButton("上传"),}; private JLabel jlPhoto=new JLabel();//显示图像的JLabel控件 private JTextField[] jtfInfo=new JTextField[10]; private JTextField jtfPhoto=new JTextField();//添加照片到相册的路径 private JFileChooser jfcPic=new JFileChooser();//上传图像的文件选择器 private DefaultTableModel tableModel; private JTable table; //性别部分 private JRadioButton jrbMale=new JRadioButton("男",true); private JRadioButton jrbFemale=new JRadioButton("女"); private ButtonGroup bgGender=new ButtonGroup(); private JPanel jpGender=new JPanel();//单选按钮面板 private JLabel jlDetail=new JLabel();//右侧显示一幅图片的标签 private JSplitPane jspOuter=//上下分割的JSplitPane new JSplitPane(JSplitPane.VERTICAL_SPLIT,true); //系统托盘部分 private PopupMenu popup=new PopupMenu(); private SystemTray tray;//定义SystemTray成员变量 private TrayIcon trayIcon;//定义TrayIcon成员变量 private MenuItem exit=new MenuItem("退出程序");//定义菜单 public void initJps() {//界面上半部分的初始化 topjp.setLayout(null);//设置topjp布局管理器为null //设置按钮大小并添加到JPanel面板里 jba.setBounds(5,10,120,26); jba.addActionListener(this);//为模糊查询按钮注册事件监听器 topjp.add(jba); jbs.setBounds(130,10,80,26); jbs.addActionListener(this);//为查找按钮注册事件监听器 topjp.add(jbs);//添加按钮到topjp面板里 //设置jtfs文本框大小并添加到jps面板里 jtfs.setBounds(215,10,120,26); jtfs.addActionListener(this);//为文本框注册事件监听器 topjp.add(jtfs); //设置单选按钮大小和位置并添加到jpbr面板里同时添加到bg单选按钮组里 jrbxm.setBounds(5,3,50,26); jrbxm.addItemListener(this);//为单选按钮注册ItemEvent事件监听器 bg.add(jrbxm); jpbr.add(jrbxm); jrbbh.setBounds(60,3,50,26); jrbbh.addItemListener(this); bg.add(jrbbh); jpbr.add(jrbbh); jpbr.setBounds(360,10,200,26); topjp.add(jpbr); } public void initInfo() {//初始化信息界面 jpyInfo.setLayout(null);//设置布局管理器为空 jpyInfo.setBounds(50,50,380,360);//设置信息面板的大小和位置 jlPhoto.setBounds(220,10,150,170);//设置联系人图像JLabel的大小和位置 jlPhoto.setBorder(BorderFactory.createLineBorder(Color.BLACK));//将JLbel的边框线显现出来 jpyInfo.add(jlPhoto);//将显示联系人照片的JLabel添加到信息面板 tableModel=new DefaultTableModel(); Vector vector1 = new Vector(); DButil db = new DButil(); vector1.add("学号"); vector1.add("姓名"); vector1.add("性别"); vector1.add("出生日期"); vector1.add("电话号码"); vector1.add("QQ"); vector1.add("Email"); vector1.add("地址"); vector1.add("照片路径"); tableModel.setDataVector(null, vector1); System.out.print(123); table=new JTable(tableModel); //table.addMouseListener((MouseListener) this); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); JScrollPane js=new JScrollPane(table); //添加相片部分的控件 jtfPhoto.setBounds(80,250,200,26);//设置得到照片路径的文本框的大小和位置 jpyInfo.add(jtfPhoto);//将得到照片路径的文本框添加到信息面板 jbInfo[2].setBounds(285,250,80,26); jbInfo[2].addActionListener(this);//为添加照片的浏览按钮注册事件监听器 jpyInfo.add(jbInfo[2]); //上传按钮 jbInfo[3].setBounds(380,250,80,26); jbInfo[3].addActionListener(this);//为添加照片的浏览按钮注册事件监听器 jpyInfo.add(jbInfo[3]); for(int i=0;i<9;i++)//添加JLabel,并设置大小和位置 { jlInfo[i].setBounds(20,10+i*30,60,26); jpyInfo.add(jlInfo[i]); } for(int i=0;i<10;i++) {//初始化一些文本框 jtfInfo[i]=new JTextField(); } //学号 jtfInfo[0].setBounds(80,10,135,26); jpyInfo.add(jtfInfo[0]); //姓名 jtfInfo[1].setBounds(80,40,135,26); jpyInfo.add(jtfInfo[1]); //出生日期 jtfInfo[3].setBounds(80,100,135,26); jpyInfo.add(jtfInfo[3]); //电话号码 jtfInfo[4].setBounds(80,130,135,26); jpyInfo.add(jtfInfo[4]); //QQ jtfInfo[5].setBounds(80,160,135,26); jpyInfo.add(jtfInfo[5]); //Email jtfInfo[6].setBounds(80,190,135,26); jpyInfo.add(jtfInfo[6]); //地址文本框的添加 jtfInfo[7].setBounds(80,220,285,26); jpyInfo.add(jtfInfo[7]); //模糊查询信息文本区的添加 js.setBounds(0,350,600,100); jpyInfo.add(js); //编辑、保存按钮 jbInfo[0].setBounds(160,300,80,26); jbInfo[0].addActionListener(this); jpyInfo.add(jbInfo[0]); jbInfo[1].setBounds(260,300,80,26); jbInfo[1].addActionListener(this); jpyInfo.add(jbInfo[1]); //性别部分 jrbMale.setBounds(5,3,50,26); jrbMale.addItemListener(this); //为单选按钮注册ItemEvent事件监听器 bgGender.add(jrbMale); jpGender.add(jrbMale); jrbFemale.setBounds(60,3,50,26); jrbFemale.addItemListener(this); //为单选按钮注册ItemEvent事件监听器 bgGender.add(jrbFemale); jpGender.add(jrbFemale); jpGender.setBounds(60,70,125,26); jpyInfo.add(jpGender); } public void clearInfo()//清空信息面板 { for(int i=0;i<10;i++) { jtfInfo[i].setText("");//清空文本框 } jlPhoto.setIcon(null);//清空图像 } public void setjtaArea(String information){ if(information.isEmpty()){ JOptionPane.showMessageDialog(this,"所查用户不存在!!!","错误", JOptionPane.WARNING_MESSAGE); } else { jta.setText(information); } } public void setInfo(Vector<String> pInfo)//将信息向量设置到信息面板中 {//将信息向量按规则填到信息面板里 this.clearInfo(); if(pInfo.size()==0) { JOptionPane.showMessageDialog(this,"所查用户不存在!!!","错误", JOptionPane.WARNING_MESSAGE); } else { for(int i=0;i<2;i++) {//显示联系人编号和姓名 jtfInfo[i].setText(pInfo.get(i)); } if(pInfo.get(2).equals("男")) {//显示性别 jrbMale.setSelected(true); } else {//显示性别 jrbFemale.setSelected(true); } for(int i=3;i<9;i++) {//显示出生日期、电话号码和QQ jtfInfo[i].setText(pInfo.get(i)); } } } public Vector<String> getInfo()//从信息面板得到用户输入的信息 { Vector<String> pInfo=new Vector<String>(); pInfo.add(jtfInfo[0].getText().trim());//添加pid pInfo.add(jtfInfo[1].getText().trim());//添加pname String gender=jrbMale.isSelected()?"男":"女"; pInfo.add(gender);//添加性别 pInfo.add(jtfInfo[3].getText().trim());//出生日期 pInfo.add(jtfInfo[4].getText().trim());//电话号码 pInfo.add(jtfInfo[5].getText().trim());//QQ pInfo.add(jtfInfo[6].getText().trim());//Email pInfo.add(jtfInfo[7].getText().trim());//地址 String photoPath=jtfPhoto.getText().trim();//得到照片路径 pInfo.add(photoPath);//照片路径 return pInfo; } public void monitorSaveButton() //监听保存按钮的方法 { String sql=""; String pid=jtfInfo[0].getText().trim();//得到联系人的编号 String pname=jtfInfo[1].getText().trim();//得到联系人的姓名 String gender=jrbMale.isSelected()?"男":"女"; String s1=jtfInfo[3].getText().trim(); String s2=jtfInfo[4].getText().trim(); String s3=jtfInfo[5].getText().trim(); String s4=jtfInfo[6].getText().trim(); String s5=jtfInfo[7].getText().trim(); String s6=jtfPhoto.getText().trim(); String sqla="select * from contacts where pid='"+pid+"'";//判断此编号是否存在的SQL String sqlb="select * from contacts where pname='"+pname+"'";//判断此姓名是否存在的SQL boolean isIdExist=DButil.isExist(sqla);//得到编号是否存在 boolean isNameExist=DButil.isExist(sqlb);//得到姓名是否存在 if(!(pid.equals(" ")||pname.equals(" "))) { if(isIdExist||isNameExist){ JOptionPane.showMessageDialog(this,"联系人已存在"+ " , 添加联系人失败","错误",JOptionPane.WARNING_MESSAGE); } else { sql="insert into contacts values (?,?,?,?,?,?,?,?,?,?)"; String[] paras={pid,pname,gender,s1,s2,s3,s4,s5,s6,null}; if(DButil.update(sql,paras)>0){ JOptionPane.showMessageDialog(this,"联系人保存成功","提示", JOptionPane.INFORMATION_MESSAGE); } } } } public void setEditable(boolean Editable)//设置信息窗口是否可编辑 { jrbFemale.setEnabled(Editable);//设置性别是否可编辑 jrbMale.setEnabled(Editable);//设置性别是否可编辑 for(int i=0;i<8;i++) { jtfInfo[i].setEditable(Editable);//设置文本框是否可编辑 } } public void monitorSearchButton()//监听查找按钮的方法 { String name=jtfs.getText().trim(); String sql="";//声明查找字符串 if(name.equals("")) { JOptionPane.showMessageDialog(this,"查找条件不能为空!!!", "错误", JOptionPane.WARNING_MESSAGE); } else { if(jrbxm.isSelected()==true) {//按姓名查找 sql="select pid,pname,pgender,pbirthday,pnumber,pQQ,pemail,padress,pphoto from contacts where pname='"+name+"'"; this.setInfo(DButil.getPerInfo(sql));//设置信息面板为该联系人的信息 } else {//按编号查找 sql="select pid,pname,pgender,pbirthday,pnumber,pQQ,pemail,padress,pphoto from contacts where pid='"+name+"'"; this.setInfo(DButil.getPerInfo(sql));//设置信息面板为该联系人的信息 } } this.setEditable(false);//设置面板不可编辑 } public void monitorRandomSearchButton(String information){ //监听模糊查询按钮 String adress=jba.getText().trim(); String sql="";//声明查找字符串 if(adress.equals("")) { JOptionPane.showMessageDialog(this,"查找条件不能为空!!!", "错误", JOptionPane.WARNING_MESSAGE); } else{ sql="select pid,pname,pgender,pbirthday,pnumber,pQQ,pemail,padress,pphoto from contacts where padress like '%天河区%'"; } } public MainFrame(String uname) { //主窗体构造器 this.uname=uname;//设置用户名 this.initJps();//界面上半部分的搭建 this.initInfo(); jspOuter.setDividerLocation(46);//设置分割窗体JSplitPane的位置 jspOuter.setTopComponent(topjp);//设置窗体上半部分的控件 jspOuter.setBottomComponent(jpyInfo);//设置下半部分的控件 //设置窗体关闭按钮执行的动作 this.add(jspOuter); this.addWindowListener( new WindowAdapter() { @SuppressWarnings("deprecation") public void WindowClosing(WindowEvent e) { //将窗体隐藏 MainFrame.this.hide(); } } ); //设置主窗体的图标、标题、大小以及可见性 this.setResizable(false);//设置窗体不让调整大小 this.setTitle(uname+"的通讯录"); this.setBounds(420,80,618,550); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource()==jbInfo[1]) {//保存按钮的监听 this.monitorSaveButton(); } else if(e.getSource()==jba) {//模糊查询按钮的监听 DButil db = new DButil(); Vector vector1 = new Vector(); vector1.add("学号"); vector1.add("姓名"); vector1.add("性别"); vector1.add("出生日期"); vector1.add("电话号码"); vector1.add("QQ"); vector1.add("Email"); vector1.add("地址"); vector1.add("照片路径"); String ad = jtfs.getText().trim(); tableModel.setDataVector(db.getData(ad),vector1); } else if(e.getSource()==jbInfo[2]) {//打开图像文件路径 jfcPic.showOpenDialog(this); if(jfcPic.getSelectedFile()!=null) { jtfPhoto.setText(""+jfcPic.getSelectedFile()); } } else if(e.getSource()==jbInfo[0]) {//编辑按钮的监听 this.setEditable(true);//设置信息面板可编辑 } else if(e.getSource()==jbs||e.getSource()==jtfs) {//查找,按按钮或者在文本框里敲回车 this.monitorSearchButton(); } } public void itemStateChanged(ItemEvent e) { } public static void main(String[] args){ } } package db; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.Vector; public class DButil { private static String jdbcName="org.gjt.mm.mysql.Driver";//声明驱动类字符串 //声明数据库连接字符串 private static String dbUrl="jdbc:mysql://127.0.0.1:3306/maillist"; private static String dbUserName="root"; private static String dbPassword="admin"; private static Connection con=null;//声明数据库连接对象引用 private static Statement stat=null;//声明语句对象引用 private static PreparedStatement pstmt=null; private static ResultSet rs=null;//声明结果集对象引用 private static PreparedStatement psInsert=null;//声明预编译语句对象引用 public static Connection getConnection()//得到数据库连接的方法 { System.out.println("连接中.."); try { Class.forName(jdbcName);//加载驱动类 con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);//得到连接 System.out.println("成功连接"); } catch(Exception e){e.printStackTrace();} return con;//返回连接 } public static boolean check(String user,String pwd)//登陆验证 { boolean flag=false; try { con=DButil.getConnection();//得到数据库连接 stat=con.createStatement();//创建语句对象 rs=stat.executeQuery("select pwd from user where uid='"+user+"'"); rs.next(); String spwd=rs.getString(1);//得到密码 if(spwd.equals(pwd)) { flag=true;//密码匹配,登陆成功 } } catch(Exception e) { flag=false;//有任何异常发生,登陆失败 } finally{DButil.closeCon();}//关闭数据库连接 return flag; } //某条记录是否存在 public static boolean isExist(String sql) { boolean flag=false;//设置返回值 try { con=DButil.getConnection();//得到数据库连接 stat=con.createStatement();//创建语句对象 rs=stat.executeQuery(sql);//执行查询 if(rs.next()) { flag=true;//存在,设置返回值为true } } catch(Exception e) { e.printStackTrace(); flag=false;//发生任何异常,置返回结果为false } finally{DButil.closeCon();}//关闭数据库连接 return flag;//返回结果 } public static int update(String sql,String[] paras)//更新数据库 { int count=0;//声明返回值 try { con=DButil.getConnection(); pstmt=con.prepareStatement(sql); for(int i=0; i<paras.length;i++){ pstmt.setString(i+1, paras[i]); } count=pstmt.executeUpdate(); } catch(Exception e) { e.printStackTrace(); count=-1;//更新失败返回值为-1 } finally{DButil.closeCon();}//关闭数据库连接 return count;//返回结果 } public static int update(String sql)//更新数据库 { int count=0;//声明返回值 try { con=DButil.getConnection(); stat=con.createStatement(); count=stat.executeUpdate(sql);//执行更新 } catch(Exception e) { e.printStackTrace(); count=-1;//更新失败返回值为-1 } finally{DButil.closeCon();}//关闭数据库连接 return count;//返回结果 } //====================添加联系人================================= public static String insertPerson(String uid,Vector<String> pInfo) { String isPathNull="isNotNull";//传过来的图像是不是合法,默认不为空 try{ con=getConnection();//得到数据库连接 if(pInfo.get(8).equals("")||pInfo.get(8)==null) {//照片路径为空,则不插入图像 psInsert=con.prepareStatement("insert into contacts(pid,pname,pgender,pbirthday,pnumber,"+ "pQQ,pemail,padress,uid)"+ "values(?,?,?,?,?,?,?,?,?)"); } else {//照片路径不为空,则插入图像 psInsert=con.prepareStatement("insert into contacts(pid,pname,pgender,pbirthday,pnumber,"+ "pQQ,pemail,padress,pphoto,uid)"+ "values(?,?,?,?,?,?,?,?,?,?,?)" ); File f=new File(pInfo.get(8));//获取选取的图片文件 byte[] b=new byte[(int)f.length()];//创建存储图片数据的数组 FileInputStream fin=new FileInputStream(f); fin.read(b);fin.close();//读取文件存于byte数组中并关闭输入流 psInsert.setBytes(11,b);//设置pphoto参数的数据 } for(int i=0;i<8;i++) {//设置公共信息 psInsert.setString(i+1,pInfo.get(i)); } psInsert.setString(10,uid);//所属用户 psInsert.execute();psInsert.close();//执行更新并关闭语句 } catch(FileNotFoundException fnfe){isPathNull="isNull";}//图片路径不对 catch(Exception e){e.printStackTrace();} finally{DButil.closeCon();}//关闭数据库连接 return isPathNull; } public static String updatePerson(String uid,Vector<String> pInfo){ String isPathNull="isNotNull";//传过来的path是不是合法 try{ con=getConnection(); if(pInfo.get(9).equals("")||pInfo.get(9)==null) {//更新时候,如果照片路径为空,则不更新图像 psInsert=con.prepareStatement("update contacts set pname=?,pgender=?,birthday=?,pnumber=?,"+ "pQQ=?,pemail=?,padress=?,pphoto=?,uid=? where pid='"+pInfo.get(0).trim()+"'"); } else {//如果照片路径不为空,则更新图像 psInsert=con.prepareStatement("update contacts set pname=?,pgender=?,page=?,pnumber=?,"+ "pemail=?,pgroup=?,ppostalcode=?,padress=?,uid=?,pphoto=? where pid='"+pInfo.get(0).trim()+"'"); File f=new File(pInfo.get(9));//获取选取的图片文件 byte[] b=new byte[(int)f.length()];//创建存储图片数据的数组 FileInputStream fin=new FileInputStream(f); fin.read(b);fin.close();//读取文件存于byte数组中并关闭输入流 psInsert.setBytes(10,b); } for(int i=1;i<8;i++){//设置公共的信息部分 psInsert.setString(i,pInfo.get(i)); } psInsert.setString(9,uid);//所属用户 psInsert.execute();psInsert.close();//执行更新并关闭语句 } catch(FileNotFoundException fnfe){isPathNull="isNull";}//路径不合法 catch(Exception e){e.printStackTrace();} finally{DButil.closeCon();}//关闭连接 return isPathNull; } public Vector getData(String ad){ Vector vector=new Vector(); try { //陈述对象 con=getConnection();//得到数据库连接 stat=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);//创建语句对象 rs=stat.executeQuery("select * from contacts where padress LIKE '%"+ad+"%'"); ResultSetMetaData rm=rs.getMetaData(); //循环打印出数据库表中数据 int n=rm.getColumnCount(); while(rs.next()){ Vector ve=new Vector(); for(int i=1;i<n+1;i++){ String s=rs.getString(i); ve.add(s); } vector.add(ve);//Vector对象接收表中数据 } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{if(rs!=null){ try { rs.close();//关闭结果集 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(stat!=null){ try { stat.close();//关闭陈述对象 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(con!=null){ try { con.close();//关闭连接 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return vector; } public static Vector<String> getPerInfo(String sql)//得到联系人信息 { Vector<String> pInfo=new Vector<String>(); try { con=getConnection();//得到数据库连接 stat=con.createStatement();//创建语句对象 rs=stat.executeQuery(sql);//执行查询 while(rs.next()) { for(int i=1;i<10;i++) { System.out.println(rs.getString(i)); pInfo.add(rs.getString(i));//将联系人信息添加到返回向量 } } } catch(Exception e) { e.printStackTrace(); } finally{DButil.closeCon();}//关闭数据库连接 return pInfo;//返回信息集合 } public static void closeCon()//关闭数据库连接的方法 { try { if(rs!=null){rs.close(); rs=null;}//如果结果集不为空关闭结果集并赋值null if(stat!=null){stat.close(); stat=null;}//如果语句对象不为空关闭语句对象并赋值null if(con!=null){con.close(); con=null;}//如果连接不为空关闭连接并赋值null } catch(Exception e){e.printStackTrace();} } public static void main(String[] args){ DButil DB=new DButil(); System.out.println(DB.getConnection()); } } }
NoSuchMethodError的问题
![图片说明](https://img-ask.csdn.net/upload/201706/09/1496995432_549285.png)# 刚刚搭建好maven的ssm框架访问index的时候就出现这个问题了 java.lang.NoSuchMethodError: javax.el.ExpressionFactory.newInstance()Ljavax/el/ExpressionFactory; at org.apache.jasper.compiler.PageInfo.<init>(PageInfo.java:79) at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:111) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:374) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:341) at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:657) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339) at javax.servlet.http.HttpServlet.service(HttpServlet.java:770) 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:85) 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:314) 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) --------------------------------------------------------------------------------------- C:\Users\Administrator\.m2\repository\junit\junit\4.11\junit-4.11.jar C:\Users\Administrator\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar C:\Users\Administrator\.m2\repository\javax\servlet\javax.servlet-api\3.0.1\javax.servlet-api-3.0.1.jar C:\Users\Administrator\.m2\repository\javax\servlet\jsp\jsp-api\2.1\jsp-api-2.1.jar C:\Users\Administrator\.m2\repository\javax\servlet\jstl\1.2\jstl-1.2.jar C:\Users\Administrator\.m2\repository\org\aspectj\aspectjweaver\1.8.6\aspectjweaver-1.8.6.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-core\4.1.7.RELEASE\spring-core-4.1.7.RELEASE.jar C:\Users\Administrator\.m2\repository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-beans\4.1.7.RELEASE\spring-beans-4.1.7.RELEASE.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-aop\4.1.7.RELEASE\spring-aop-4.1.7.RELEASE.jar C:\Users\Administrator\.m2\repository\aopalliance\aopalliance\1.0\aopalliance-1.0.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-context\4.1.7.RELEASE\spring-context-4.1.7.RELEASE.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-expression\4.1.7.RELEASE\spring-expression-4.1.7.RELEASE.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-jdbc\4.1.7.RELEASE\spring-jdbc-4.1.7.RELEASE.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-tx\4.1.7.RELEASE\spring-tx-4.1.7.RELEASE.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-web\4.1.7.RELEASE\spring-web-4.1.7.RELEASE.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-webmvc\4.1.7.RELEASE\spring-webmvc-4.1.7.RELEASE.jar C:\Users\Administrator\.m2\repository\org\springframework\spring-test\4.0.6.RELEASE\spring-test-4.0.6.RELEASE.jar C:\Users\Administrator\.m2\repository\org\mybatis\mybatis\3.2.7\mybatis-3.2.7.jar C:\Users\Administrator\.m2\repository\org\mybatis\mybatis-spring\1.2.3\mybatis-spring-1.2.3.jar C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.37\mysql-connector-java-5.1.37.jar C:\Users\Administrator\.m2\repository\com\alibaba\druid\1.0.16\druid-1.0.16.jar C:\Users\Administrator\.m2\repository\com\mchange\c3p0\0.9.5-pre8\c3p0-0.9.5-pre8.jar C:\Users\Administrator\.m2\repository\com\mchange\mchange-commons-java\0.2.7\mchange-commons-java-0.2.7.jar C:\Users\Administrator\.m2\repository\org\slf4j\slf4j-log4j12\1.7.12\slf4j-log4j12-1.7.12.jar C:\Users\Administrator\.m2\repository\org\slf4j\slf4j-api\1.7.12\slf4j-api-1.7.12.jar C:\Users\Administrator\.m2\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar C:\Users\Administrator\.m2\repository\commons-fileupload\commons-fileupload\1.3.1\commons-fileupload-1.3.1.jar C:\Users\Administrator\.m2\repository\commons-io\commons-io\2.2\commons-io-2.2.jar C:\Users\Administrator\.m2\repository\org\apache\poi\poi\3.16-beta2\poi-3.16-beta2.jar C:\Users\Administrator\.m2\repository\commons-codec\commons-codec\1.10\commons-codec-1.10.jar C:\Users\Administrator\.m2\repository\org\apache\commons\commons-collections4\4.1\commons-collections4-4.1.jar C:\Users\Administrator\.m2\repository\com\alibaba\fastjson\1.2.24\fastjson-1.2.24.jar C:\Users\Administrator\.m2\repository\org\glassfish\web\el-impl\2.2\el-impl-2.2.jar C:\Users\Administrator\.m2\repository\javax\el\el-api\2.2\el-api-2.2.jar 这些是我的包 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 这个是我的applicationContext.xml文件的内容 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 该包下的类支持注解,表示会被当作{@code mybatis mapper}处理 配置了之后表示可以自动引入mapper类 <mybatis:scan base-package="com.crm.dao" /> --> <!--引入属性文件 --> <context:property-placeholder location="classpath:dataSource.properties" /> <!-- 排除controller扫描 --> <context:component-scan base-package="com.zefu"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!--数据库连接 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${jdbc.maxWait}" /> <!-- 配置监控统计拦截的filters --> <property name="filters" value="${jdbc.filters}" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> </bean> <!-- sqlSessionFactory配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mybatis的配置文件和映射文件 --> <property name="mapperLocations" value="classpath:com/zefu/domain/*.xml"></property> <!-- <property name="configLocation" value="classpath:mybatis.xml"></property> --> <property name="typeAliasesPackage" value="com.zefu.domain,com.zefu.query" /> </bean> <!-- spring扫描dao接口所在的包 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zefu.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 事务管理 --> <bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务通知 --> <tx:advice id="txAdvice" transaction-manager="tx"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置事务切面 --> <aop:config> <aop:pointcut expression="bean(*Service)" id="pt" /> <!-- expression="execution(*com.zefu.service.*.*(..))" --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt" /> </aop:config> </beans> ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 这个是applicationContext-mvc里面的内容 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <!-- 启用spring mvc 注解--> <mvc:annotation-driven> <!-- 启动JSON格式的配置 --> <mvc:message-converters> <!-- 这里也可以自己定制class --> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <!-- 避免IE出现下载JSON文件的情况 --> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 自动扫描的包名 ,使Spring支持自动检测组件,只扫描Controller,排除service--> <context:component-scan base-package="com.zefu"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <!-- 视图解析器:定义跳转的文件的前后缀--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
springboot 配置多库之后,mybatis在控制台不打印sql语句了
springboot项目 单库下,mybatis只需要添加如下配置,就可以打印sql语句 ```xml <!-- 打印查询语句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> ``` 但是多库环境下,mybatis不论怎么设置,都无法打印sql语句..... ---- ---- 项目中的相关配置: mybatis配置: ```xml <!-- 设置运行参数 --> <settings> <!-- 全局映射器启用缓存 --> <setting name="cacheEnabled" value="true" /> <!-- 查询时,关闭关联对象及时加载以提高性能 --> <setting name="lazyLoadingEnabled" value="false" /> <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 --> <setting name="aggressiveLazyLoading" value="false" /> <!-- 对于位置的SQL查询,允许返回不同的结果集以达到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 允许使用列标签代替列明 --> <setting name="useColumnLabel" value="true" /> <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值), 数据表的pk生成策略将被覆盖 --> <setting name="useGeneratedKeys" value="true" /> <!-- 给予被嵌套的resultMap以字段-属性的映射支持 --> <setting name="autoMappingBehavior" value="PARTIAL" /> <!-- 对于批量更新操作缓存SQL以提高性能 --> <setting name="defaultExecutorType" value="REUSE" /> <!-- 数据库超过25000秒仍未响应则超时 --> <!--<setting name="defaultStatementTimeout" value="25000" />--> <!-- 打印查询语句 --> <setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 开启驼峰--> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> ``` logback配置: ```xml <?xml version="1.0" encoding="UTF-8"?> <configuration scan="true"> <!-- 属性1:每个logger都关联到logger上下文,默认上下文名称为“default”。 但可以使用设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改,可以通过%contextName来打印日志上下文名称。 --> <contextName>logback</contextName> <!--属性2:定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径--> <!-- <springProfile name="dev"> <property name="LOG_PATH" value="D://care-management-statisticserver-logs"/> </springProfile> <springProfile name="test"> <property name="LOG_PATH" value="/data/tomcat_jar/taixin_care/care-management-statisticserver/logs"/> </springProfile> <springProfile name="prod"> <property name="LOG_PATH" value="/data1/logs/care-management-statisticserver"/> </springProfile> --> <property name="LOG_PATH" value="${LOG_FILE}"/> <!--appender用来格式化日志输出节点,有俩个属性name和class,class用来指定哪种输出策略,常用就是控制台输出策略和文件输出策略。--> <!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,,,, --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>info</level> </filter> <encoder> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n</pattern> </encoder> </appender> <!--<include resource="org/springframework/boot/logging/logback/base.xml"/>--> <!-- 说明: 1、日志级别及文件 日志记录采用分级记录,级别与日志文件名相对应,不同级别的日志信息记录到不同的日志文件中 例如:error级别记录到log_error_xxx.log或log_error.log(该文件为当前记录的日志文件),而log_error_xxx.log为归档日志, 日志文件按日期记录,同一天内,若日志文件大小等于或大于2M,则按0、1、2...顺序分别命名 例如log-level-2013-12-21.0.log 其它级别的日志也是如此。 2、文件路径 若开发、测试用,在Eclipse中运行项目,则到Eclipse的安装路径查找logs文件夹,以相对路径../logs。 若部署到Tomcat下,则在Tomcat下的logs文件中 3、Appender FILEERROR对应error级别,文件名以log-error-xxx.log形式命名 FILEWARN对应warn级别,文件名以log-warn-xxx.log形式命名 FILEINFO对应info级别,文件名以log-info-xxx.log形式命名 FILEDEBUG对应debug级别,文件名以log-debug-xxx.log形式命名 CONSOLE将日志信息输出到控制上,为方便开发测试使用 --> <!-- 日志记录器,日期滚动记录 --> <appender name="FILEERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 正在记录的日志文件的路径及文件名 --> <file>${LOG_PATH}/error_statisticserver.log</file> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 归档的日志文件的路径,例如今天是2013-12-21日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。 而2013-12-21的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 --> <fileNamePattern>${LOG_PATH}/error-statisticserver-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <!-- 表示只保留最近30天的日志,以防止日志填满整个磁盘空间。--> <maxHistory>30</maxHistory> <!--用来指定日志文件的上限大小,例如设置为1GB的话,那么到了这个值,就会删除旧的日志。--> <totalSizeCap>1GB</totalSizeCap> <!-- 除按日志记录之外,还配置了日志文件不能超过2M,若超过2M,日志文件会以索引0开始, 命名日志文件,例如log-error-2013-12-21.0.log --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <!-- 追加方式记录日志 --> <append>true</append> <!-- 日志文件的格式 --> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n</pattern> <charset>utf-8</charset> </encoder> <!-- 此日志文件只记录error级别的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- 日志记录器,日期滚动记录 --> <appender name="FILEINFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 正在记录的日志文件的路径及文件名 --> <file>${LOG_PATH}/info_statisticserver.log</file> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 归档的日志文件的路径,例如今天是2013-12-21日志,当前写的日志文件路径为file节点指定,可以将此文件与file指定文件路径设置为不同路径,从而将当前日志文件或归档日志文件置不同的目录。 而2013-12-21的日志文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 --> <fileNamePattern>${LOG_PATH}/info-statisticserver-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <!-- 表示只保留最近30天的日志,以防止日志填满整个磁盘空间。--> <maxHistory>30</maxHistory> <!--用来指定日志文件的上限大小,例如设置为1GB的话,那么到了这个值,就会删除旧的日志。--> <totalSizeCap>1GB</totalSizeCap> <!-- 除按日志记录之外,还配置了日志文件不能超过2M,若超过2M,日志文件会以索引0开始,命名日志文件,例如log-error-2013-12-21.0.log --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <!-- 追加方式记录日志 --> <append>true</append> <!-- 日志文件的格式 --> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n</pattern> <charset>utf-8</charset> </encoder> <!-- 此日志文件只记录info级别的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- <logger>用来设置某一个包或者具体的某一个类的日志打印级别、以及指定<appender>。<logger>仅有一个name属性,一个可选的level和一个可选的addtivity属性。 --> <logger name="org.springframework" level="INFO"/> <logger name="org.apache" level="ERROR"/> <logger name="org.hibernate.validator" level="ERROR"/> <!--<logger name="org.thymeleaf" level="ERROR"/>--> <logger name="org.springframework.context.annotation" level="ERROR"/> <!-- springProfile多环境日志输出,据不同环境(prod:生产环境,test:测试环境,dev:开发环境)来定义不同的日志输出--> <springProfile name="dev" /> <root level="INFO"> <appender-ref ref="FILEERROR"/> <appender-ref ref="FILEINFO"/> <appender-ref ref="STDOUT"/> </root> <!-- 可以启动服务的时候指定 profile (如不指定使用默认),如指定prod 的方式为: java -jar xxx.jar –spring.profiles.active=prod--> </configuration> ``` application.properties部分配置: ```properties #配置文件 logging.level.tk.mybatis=TRACE spring.freemarker.cache=false spring.freemarker.request-context-attribute=request mybatis.type-aliases-package=com.mtpf.domain mybatis.mapper-locations=classpath:mapper/*.xml mapper.mappers=com.mtpf.util.MyMapper mapper.not-empty=false mapper.identity=MYSQL pagehelper.helperDialect=mysql #true 是超出最大页码返回数据 false超出最大页码不返回数据 pagehelper.reasonable=${PAGEHELPER_REASONABLE} pagehelper.supportMethodsArguments=true pagehelper.params=count=countSql ```
springboot+logback每日生成日志文件
用springboot+logback配置了每日生成日志文件,以前用log4j没有问题,现在用logback每日生成日志文件,刚启动应用服务器时可以生成,以后每天并没有生成新的文件,而是继续写入原来的文件,有哪位兄弟知道原因了。 logback配置如下 <?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2010-2011 The myBatis Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <configuration debug="false"> <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径--> <property name="LOG_HOME" value="@logback.log.file.path@"/> <!-- 控制台输出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> </encoder> </appender> <!-- 按照每天生成INFO日志文件 --> <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--日志文件输出的文件名--> <FileNamePattern>${LOG_HOME}/platform_logger_warn_%d{yyyy-MM-dd}.log</FileNamePattern> <!--日志文件保留天数--> <MaxHistory>10</MaxHistory> </rollingPolicy> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> </encoder> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>DENY</onMatch> <onMismatch>ACCEPT</onMismatch> </filter> <!--日志文件最大的大小--> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> <!-- 按照每天生成ERROR日志文件 --> <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--日志文件输出的文件名--> <FileNamePattern>${LOG_HOME}/platform_logger_error_%d{yyyy-MM-dd}.log</FileNamePattern> <!--日志文件保留天数--> <MaxHistory>10</MaxHistory> </rollingPolicy> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> </encoder> <filter class="ch.qos.logback.classic.filter.LevelFilter"><!-- 只打印错误日志 --> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <!--日志文件最大的大小--> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> <!-- show parameters for hibernate sql 专为 Hibernate 定制 --> <!-- <logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE" /> <logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG" /> <logger name="org.hibernate.SQL" level="DEBUG" /> <logger name="org.hibernate.engine.QueryParameters" level="DEBUG" /> <logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" /> --> <!-- 日志输出级别 --> <root level="@logback.log.root.level@"> <appender-ref ref="STDOUT"/> <appender-ref ref="WARN_FILE"/> <appender-ref ref="ERROR_FILE"/> </root> <!--日志异步到数据库 --> <!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://127.0.0.1:3306/databaseName</url> <user>root</user> <password>root</password> </dataSource> </connectionSource> </appender>--> </configuration>
javaweb项目部署到tomcat下,可以修改配置文件吗?
我创建了一个war包到tomcat的webapps下,自动解压后,我去修改项目的jdbc.properties文件,但是修改过后访问就会报错,(不能加载jdbc的驱动程序类${jdbc.driver}),这是怎么回事?是打了war包就不能修改 ``` <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> <property name="ignoreUnresolvablePlaceholders" value="true" /> </bean> <!--配置连接池...连接数据库 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> ``` ``` jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/gykj_tksp?useUnicode=true&amp;characterEncoding=UTF-8 jdbc.username=**** #password=**** jdbc.password=**** #定义初始连接数 initialSize=0 #定义最大连接数 maxActive=20 #定义最大连接空间 maxIdle=20 #定义最小连接空间 minIdle=1 #定义最长等待时间 maxWait=60000 idleConnectionTestPeriod=1800 maxIdleTime=14400 ``` 只要修改就报这个错 ``` nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class '${jdbc.driver}' ```
spring-mybatis.xml而配置druid连接池错误
package gg; public class hj { <?xml version=\"1.0\" encoding=\"UTF-8\"?> <beans xmlns=\"http://www.springframework.org/schema/beans\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:context=\"http://www.springframework.org/schema/context\" xmlns:tx=\"http://www.springframework.org/schema/tx\" xmlns:aop=\"http://www.springframework.org/schema/aop\" xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd \"> <!--自动扫描--> <context:component-scan base-package=\"com.books\"> <context:exclude-filter type=\"annotation\" expression=\"org.springframework.stereotype.Controller\"/> </context:component-scan> <context:property-placeholder ignore-unresolvable=\"true\" location=\"classpath:jdbc.properties\"/> <!--============================配置数据源=================================--> <bean id=\"dataSource\" class=\"com.alibaba.druid.pool.DruidDataSource\" init-method=\"init\" destroy-method=\"close\"> <property name=\"driverClassName\" value=\"${driverClass}\"/> <property name=\"url\" value=\"${jdbcurl}\"/> <property name=\"username\" value=\"${jdbcusername}\"/> <property name=\"password\" value=\"${jdbcpassword}\"/> <!-- 初始化连接大小 --> <property name=\"initialSize\" value=\"2\"/> <!-- 连接池最大使用连接数量 --> <property name=\"maxActive\" value=\"${maxActive}\"/> <!-- 连接池最大空闲 --> <!-- <property name=\"maxIdle\" value=\"20\" /> --> <!-- 连接池最小空闲 --> <property name=\"minIdle\" value=\"${minIdle}\"/> <!-- 获取连接最大等待时间 --> <property name=\"maxWait\" value=\"${maxWait}\"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name=\"timeBetweenEvictionRunsMillis\" value=\"60000\"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name=\"minEvictableIdleTimeMillis\" value=\"25200000\"/> <!-- 打开removeAbandoned功能 --> <property name=\"removeAbandoned\" value=\"true\"/> <!-- 1800秒,也就是30分钟 --> <property name=\"removeAbandonedTimeout\" value=\"1800\"/> <!-- 关闭abanded连接时输出错误日志 --> <property name=\"logAbandoned\" value=\"true\"/> <!-- 监控数据库 --> <!-- <property name=\"filters\" value=\"stat\" /> --> <property name=\"filters\" value=\"mergeStat\"/> </bean> <!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 --> <bean id=\"sqlSessionFactory\" class=\"org.mybatis.spring.SqlSessionFactoryBean\"> <property name=\"dataSource\" ref=\"dataSource\"/> <!-- 自动扫描mapping.xml文件 --> <property name=\"mapperLocations\" value=\"classpath:/mapper/*.xml\"/> <!-- 分页查询(mybatis 3.2.8以上版本)-张晗 --> <property name=\"plugins\"> <array> <bean class=\"com.github.pagehelper.PageInterceptor\"> <property name=\"properties\"> <value> helperDialect=mysql </value> </property> </bean> </array> </property> </bean> <!--DAO接口所在包名,Spring会自动查找其下的类--> <bean class=\"org.mybatis.spring.mapper.MapperScannerConfigurer\"> <!--制定扫描的包名扫描dao层下的类--> <property name=\"basePackage\" value=\"com.books.dao\"/> <property name=\"sqlSessionFactoryBeanName\" value=\"sqlSessionFactory\"/> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id=\"transactionManager\" class=\"org.springframework.jdbc.datasource.DataSourceTransactionManager\"> <property name=\"dataSource\" ref=\"dataSource\"/> </bean> <!--使用注释事务 --> <tx:annotation-driven transaction-manager=\"transactionManager\"/> <!-- <import resource=\"spring-schedule.xml\"/> --> </beans> 15-Mar-2018 16:01:27.914 严重 [RMI TCP Connection(5)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [spring-mybatis.xml]: Invocation of init method failed; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
一开始自己配置的activiti的运行web时报错以为是环境的问题,后面到网上借鉴改了一些还是没用。
ssm框架整合activiti流程,在控制器中使用注入有关activities的一些Service如:RepositoryService、ProcessEngine、TaskService、RuntimeService、HistoryService,运行web项目后报错,后面网上借鉴了一些activitie的一些配置还是没用,o依.springframework.beans.factory.BeanCreationException: Error creating bean with name 'processEngineConfiguration' defined in file [F:\宏图软件学院办公软件项目\SchoolSystem\target\SSMTest\WEB-INF\classes\spring-activiti.xml]: Cannot resolve reference to bean 'dataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359) org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1469) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629) org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677) org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548) org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489) org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) javax.servlet.GenericServlet.init(GenericServlet.java:158) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748) ``` 这个是activiti.cfg.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置数据源 --> <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration"> <property name="jdbcDriver" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/schoolsystem?characterEncoding=utf8"></property> <property name="jdbcUsername" value="root"></property> <property name="jdbcPassword" value="1234"></property> <property name="databaseSchemaUpdate" value="true"></property> </bean> <!-- 配置流程引擎工厂 --> <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean"> <property name="processEngineConfiguration" ref="processEngineConfiguration"></property> </bean> </beans> ``` 这个是spring-activiti.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 用于创建流程引擎的对象 --> <bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration"> <property name="transactionManager" ref="transactionManager"></property> <property name="dataSource" ref="druidDataSource"></property> <property name="databaseSchemaUpdate" value="true"></property> </bean> <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean"> <property name="processEngineConfiguration" ref="processEngineConfiguration"></property> </bean> </beans> ``` spring-dao.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" 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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置整合mybatis过程 --> <!-- 1.配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 2.数据库连接池 --> <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc_driverClassName}" /> <property name="url" value="${jdbc_url}"/> <property name="username" value="${jdbc_username}"/> <property name="password" value="${jdbc_password}"/> <!-- 初始化连接大小 --> <property name="initialSize" value="5"/> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="50"/> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20"/> <!-- 连接池最小空闲 --> <property name="minIdle" value="5"/> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000"/> <property name="validationQuery" value="${validationQuery}"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="testWhileIdle" value="true"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000"/> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true"/> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800"/> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true"/> <!-- 监控数据库 --> <property name="filters" value="mergeStat"/> </bean> <!-- 3.配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="druidDataSource" /> <!-- 配置MyBaties全局配置文件:mybatis-config.xml --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 扫描vo包 使用别名 --> <property name="typeAliasesPackage" value="Vo" /> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:Mapper/*.xml" /> </bean> <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="Mapper"/> </bean> </beans> ``` 这个是spring-service.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描service包下所有使用注解的类型 --> <context:component-scan base-package="Service" /> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="druidDataSource" /> </bean> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans> ``` 这个是spring-web.xml ``` <?xml version="1.0" encoding="UTF-8"?> <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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置spring mvc--> <!--1,开启springmvc注解模式 a.自动注册 DefaultAnnotationHandlerMapping, AnnotationMethodHandlerAdapter b.默认提供一系列的功能:数据绑定,数字和日期的format@NumberFormat,@DateTimeFormat c:xml,json的默认读写支持--> <mvc:annotation-driven conversion-service="dateUtil"></mvc:annotation-driven> <!--2.静态资源默认servlet配置--> <!-- 1).加入对静态资源处理:排除后缀 js,gif,png, 等静态资源的请求不会进入控制器 2).允许使用 "/" 做整体映射 --> <mvc:default-servlet-handler/> <!--3:配置JSP 显示ViewResolver--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!--4:扫描web所有的 controller--> <context:component-scan base-package="Control"/> <!-- FastJson注入 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!-- 避免IE执行AJAX时,返回JSON出现下载文件 --> <!-- FastJson --> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 --> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <property name="features"> <array value-type="com.alibaba.fastjson.serializer.SerializerFeature"> <!-- 避免循环引用 --> <value>DisableCircularReferenceDetect</value> <!-- 是否输出值为null的字段 --> <value>WriteMapNullValue</value> <!-- 数值字段如果为null,输出为0,而非null --> <value>WriteNullNumberAsZero</value> <!-- 字符类型字段如果为null,输出为"",而非null --> <value>WriteNullStringAsEmpty</value> <!-- List字段如果为null,输出为[],而非null --> <value>WriteNullListAsEmpty</value> <!-- Boolean字段如果为null,输出为false,而非null --> <value>WriteNullBooleanAsFalse</value> </array> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 拦截器配置 --> <mvc:interceptors> <mvc:interceptor> <!-- 拦截URL,拦截 admin 开头的所有请求 --> <mvc:mapping path="/**" /> <!-- 添加不会被拦截的url --> <mvc:exclude-mapping path="/login/**" /> <!-- 拦截请求交给,哪个拦截器 --> <bean class="Interceptor.MyInterceptor"/> </mvc:interceptor> <!-- 国际化拦截器 --> <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"> <property name="paramName" value="lang"/> </bean> </mvc:interceptors> <bean id="dateUtil" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" > <property name="converters" > <list> <bean class="Base.DateUtil"></bean> </list> </property> </bean> <!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 配置文件上传最大大小(字节)这里是1M --> <property name="maxUploadSize" value="1048576"/> </bean> <!-- 国际化资源文件 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <!-- 表示多语言配置文件在根路径下,以i18n开头的文件--> <property name="basename" value="i18n"/> <property name="useCodeAsDefaultMessage" value="true"/> </bean> <!-- 配置SessionLocaleResolver用于将Locale对象存储于Session中供后续使用 --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean> </beans> ``` ```
js 上传图片显示上传失败
希望有大神能帮我看一下以下代码哪里有错误导致上传图片后显示上传失败,拜托了.我基础很差 ``` upload.jsp <%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <%@ page import="com.jspsmart.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>推荐书籍上传界面</title> <script type="text/javascript"> function check(){ var txtName = document.getElementById("nfile").value.length; if(txtName==0){ alert("请先选择一张图片"); return false; } } </script> </head> <body style="background: url(images/changepassword.JPG)"> <div align="center"> <form action="uploadservlet" enctype="multipart/form-data" onsubmit="return check()" method="post"> <h1>推荐书籍上传界面</h1> 选择书籍封面:<input type="file" name="nfile" id="nfile"> <br><br> 请输入推荐书籍名:<input type="text" name="gName"> <br><br> 请输入推荐理由:<textarea name="gInfo" cols="20" rows="8"> </textarea> <br><br> <input type="submit" value="添加书籍"> </form> </div> </body> </html> ``` uploadservlet.java ```import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import bean.DBClass; import com.jspsmart.upload.SmartUpload; public class uploadservlet extends HttpServlet { public uploadservlet() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=gbk"); PrintWriter out = response.getWriter(); String path; //进行smartupload操作 SmartUpload su = new SmartUpload(); com.jspsmart.upload.File file = null; //初始化smartupload对象 su.initialize(getServletConfig(), request, response); //设置允许上传的文件格式 String allowed = "jpg,gif,png,bmp"; //设置不允许上传的文件格式 String baned = "txt,doc,xls,docx,pdf"; //设置允许上传文件的大小 int file_size = 1024*1024*10; String exMsg = null; try{ //上传文件的设置 su.setAllowedFilesList(allowed); su.setDeniedFilesList(baned); su.setMaxFileSize(file_size); //执行上传 su.setCharset("gbk"); su.upload(); String gName = su.getRequest().getParameter("bName"); String gInfo = su.getRequest().getParameter("bInfo"); file = su.getFiles().getFile(0); String filepath = null; if(!file.isMissing()){ //设置文件存放在服务器的位置 filepath = "upload\\"; filepath += file.getFileName(); //将文件另存为 file.setCharset("gbk"); //DBClass db=new DBClass(); //db.addGoods(gName, gInfo, file.getFileName()); file.saveAs(filepath,SmartUpload.SAVE_VIRTUAL); //System.out.print(filepath); out.print("<script type='text/javascript'>"); out.print("alert('上传成功!');"); out.print("document.location='index.jsp';"); out.print("</script>"); } }catch(Exception e){ e.printStackTrace(); out.print("<script type='text/javascript'>"); out.print("alert('上传失败!');"); out.print("document.location='index.jsp';"); out.print("</script>"); } out.flush(); out.close(); } public void init() throws ServletException { // Put your code here } } ``` ``` /** * 该类为网上书店操作数据库的公用类 * 用于数据库连接、查询和更新等操作 */ package bean; import java.io.*; import java.util.*; import java.sql.*; public class DBClass { private String driver; private String url; private String username; private String password; private Connection connection; private Statement statement; private String message=""; PreparedStatement pst = null; public DBClass(){ driver="com.mysql.jdbc.Driver"; url="jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=UTF-8"; username="root"; password="123"; connection=null; statement=null; message=""; } /* 连接数据库 */ public void connect(){ try{ Class.forName(driver); connection=DriverManager.getConnection(url,username,password); statement=connection.createStatement(); }catch(ClassNotFoundException cnfe){ message="connection:"+cnfe; }catch(SQLException sqle){ message="executeQuery:"+sqle; } } /* 执行SQL查询并返回结果 */ public ResultSet executeQuery(String query){ ResultSet resultset=null; try{ resultset=statement.executeQuery(query); }catch(SQLException sqle){ message="executeQuery:"+sqle; } return resultset; } /* 执行数据库更新操作 */ public void executeUpdate(String command){ try{ statement.executeUpdate(command); }catch(SQLException sqle){ message="executeUpdate:"+sqle; } } public void addGoods(String gName,String gInfo,String path){ connect(); try{ String sql = "insert into add (gName,gInfo,gPic) " + "values (?,?,?)"; pst = connection.prepareStatement(sql); pst.setString(1, gName); pst.setString(2, gInfo); pst.setString(3, path); pst.executeUpdate(); pst.close(); connection.close(); }catch(Exception e){ e.printStackTrace(); } } /* 关闭数据库连接 */ public void closeConnection(){ try{ connection.close(); }catch(SQLException sqle){ message="closeConnection:"+sqle; } } } ```
spring-data-jpa事务不起作用
spring-data-jpa中的repository事务没有问题,但是在Service中添加Transactional注解事务就不起作用, 中间有异常不能回滚,spring的配置如下 ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <!-- 指定数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 指定Jpa持久化实现厂商类,这里以Hibernate为例 --> <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/> <property name="packagesToScan" value="com.test.domain"/> <property name="jpaProperties"> <props> <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="javax.persistence.validation.mode">none</prop> <prop key="hibernate.use_sql_comments">false</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.max_fetch_depth">1</prop> <!-- 二级缓存设置 --> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> <prop key="hibernate.cache.use_query_cache">true</prop> </props> </property> <property name="sharedCacheMode" value="ENABLE_SELECTIVE"/> </bean> <!-- Hibernate对Jpa的实现 --> <bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/> <!-- 数据源配置,使用应用内的DBCP数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${db.driverClass}"/> <property name="url" value="${db.jdbcUrl}"/> <property name="username" value="${db.user}"/> <property name="password" value="${db.password}"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="${db.initialSize}"/> <property name="minIdle" value="${db.minIdle}"/> <property name="maxActive" value="${db.maxActive}"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${db.maxWait}"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${db.timeBetweenEvictionRunsMillis}"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${db.minEvictableIdleTimeMillis}"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="${db.poolPreparedStatements}"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="${db.maxPoolPreparedStatementPerConnectionSize}"/> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <jpa:repositories base-package="com.test.dao.reposities.db" entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" /> </beans> ``` ``` <!-- 组件自动扫描 (注解) --> <context:component-scan base-package="com.test"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.RestController"/> </context:component-scan> <!-- 开启注解事务 --> <!-- 使用 JDK 动态代理: proxy-target-class="false" @Transactional可以标注在接口或者父类上 使用CGLIB动态代理: proxy-target-class="true" @Transactional不能标注在接口或者父类上,需要标注在业务实现类或是其方法上,否则事务不生效 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> ``` 请大神们给解答一些为什么在Service中配置事务不起作用?
看别人的项目,就是数据库的表看不懂,帮忙解释下
-- MySQL dump 10.11 -- -- Host: localhost Database: zxdy -- ------------------------------------------------------ -- Server version 5.0.41-community-nt /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES latin1 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `dy_apply` -- DROP TABLE IF EXISTS `dy_apply`; CREATE TABLE `dy_apply` ( `AID` int(11) NOT NULL auto_increment, `UID` int(11) default NULL, `TGID` int(11) default NULL, `AReason` varchar(200) NOT NULL, `AFlag` int(11) default '0', `AStatus` char(10) default '申请中', PRIMARY KEY (`AID`), KEY `UID` (`UID`), KEY `TGID` (`TGID`), [color=red] CONSTRAINT `dy_apply_ibfk_1` FOREIGN KEY (`UID`) REFERENCES `dy_user` (`UID`) ON DELETE CASCADE, CONSTRAINT `dy_apply_ibfk_2` FOREIGN KEY (`TGID`) REFERENCES `dy_topic_group` (`TGID`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1;[/color]-- -- Dumping data for table `dy_apply` -- [color=red]LOCK TABLES `dy_apply` WRITE;[/color]/*!40000 ALTER TABLE `dy_apply` DISABLE KEYS */; INSERT INTO `dy_apply` VALUES (2,1,10002,'范德萨发大萨菲',1,'拒绝申请'),(3,1,10004,'范德萨发大',0,'申请中'),(4,1,10000,'fsfaf',1,'拒绝申请'),(5,1,10002,'dsf',1,'拒绝申请'),(7,3,10002,'范德萨发大是',1,'同意申请'),(8,1,10002,'feafdsafdsafdas',1,'同意申请'),(9,1,10000,'fefewfewa',1,'同意申请'),(10,1,10003,'21',0,'申请中'),(11,1,10008,'fdsa',0,'申请中'),(12,1,10006,'想学习',0,'申请中'); /*!40000 ALTER TABLE `dy_apply` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `dy_revert` -- DROP TABLE IF EXISTS `dy_revert`; CREATE TABLE `dy_revert` ( `RID` int(11) NOT NULL auto_increment, `TID` int(11) default NULL, `UID` int(11) default NULL, `RTitle` varchar(200) default NULL, `RContent` text NOT NULL, `RDate` datetime NOT NULL, PRIMARY KEY (`RID`), KEY `TID` (`TID`), KEY `UID` (`UID`), [color=red] CONSTRAINT `dy_revert_ibfk_1` FOREIGN KEY (`TID`) REFERENCES `dy_topic` (`TID`) ON DELETE CASCADE, CONSTRAINT `dy_revert_ibfk_2` FOREIGN KEY (`UID`) REFERENCES `dy_user` (`UID`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1;[/color] -- -- Dumping data for table `dy_revert` -- [color=red]LOCK TABLES `dy_revert` WRITE;[/color]/*!40000 ALTER TABLE `dy_revert` DISABLE KEYS */; INSERT INTO `dy_revert` VALUES (1,2,3,'','看书,上网问问题','2008-12-08 11:08:31'),(2,1,3,'','传说新版本的JAVA 会自动缓存BYTE范围内的值.','2008-12-08 11:08:31'),(3,1,3,'','楼主懂了吗?可以参考Java里的源代码','2008-12-08 11:08:31'),(4,1,3,'','谢谢大家指教','2008-12-08 11:08:31'),(5,3,3,'','认真学习,专心研究的话就好学','2008-12-08 11:08:31'),(6,10,1,'','\r\n测试测试测试测试测试测试测试测试测试10\r\n测试测试测试测试测试测试测试测试测试10\r\n测试测试测试测试测试测试测试测试测试10','2008-12-08 20:13:07'),(7,10,1,'回答 xyz 的问题','\r\n测试测试测试测试测试测试测试测试测试10\r\n测试测试测试测试测试测试测试测试测试10\r\n测试测试测试测试测试测试测试测试测试10','2008-12-08 20:13:15'),(8,1,2,'','都是一个人????','2008-12-10 23:01:33'),(9,6,2,'','新版本会缓存的 呵呵','2008-12-11 23:24:32'),(10,8,1,'','再次测试啊啊啊 啊','2008-12-12 01:16:36'),(11,10,1,'','学生\r\n\r\n注册时间 2008-12-08\r\n\r\n最后登陆 2008-12-12\r\n 2楼 发表于 2008-12-08 20:13:15 回答 xyz 的问题\r\n测试测试测试测试测试测试测试测试测试10 测试测试测试测试测试测试测试测试测试10 测试测试测试测试测试测试测试测试测试10 ','2008-12-12 01:16:56'),(12,4,2,'','回答过的问题嘛算法','2008-12-12 10:58:57'),(13,10,2,'','回答过了,是不是没有了么','2008-12-12 13:08:35'),(14,3,2,'','回答了 谢谢 呵呵。。。','2008-12-12 13:27:24'),(15,15,1,'','bbbbbbbbbbbbbbbbb','2009-03-16 20:45:19'),(16,15,1,'','ccccccccccccccc','2009-03-16 20:59:07'),(17,17,1,'','ssssssssssssssssss','2009-03-16 21:00:10'); /*!40000 ALTER TABLE `dy_revert` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `dy_topic` -- DROP TABLE IF EXISTS `dy_topic`; CREATE TABLE `dy_topic` ( `TID` int(11) NOT NULL auto_increment, `UID` int(11) default NULL, `TGID` int(11) default NULL, `TTitle` varchar(200) NOT NULL, `TContent` text NOT NULL, `TDate` datetime NOT NULL, `TReadCount` int(11) default '0', PRIMARY KEY (`TID`), KEY `UID` (`UID`), KEY `TGID` (`TGID`), CONSTRAINT `dy_topic_ibfk_1` FOREIGN KEY (`UID`) REFERENCES `dy_user` (`UID`) ON DELETE CASCADE, CONSTRAINT `dy_topic_ibfk_2` FOREIGN KEY (`TGID`) REFERENCES `dy_topic_group` (`TGID`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `dy_topic` -- LOCK TABLES `dy_topic` WRITE; /*!40000 ALTER TABLE `dy_topic` DISABLE KEYS */; INSERT INTO `dy_topic` VALUES (1,1,10001,'怎样学习框架ssh','学习struts spring hibernate 的顺序是ssh吗 顺便根据我的情况推荐几本书','2008-12-08 11:07:16',31),(2,2,10003,'C++很难吗?应该怎么样学习呢','请给我推荐几本C++的书,给我讲些学习方法谢谢','2008-12-08 11:07:16',19),(3,2,10001,'测试','测试测试测试测试测试测试测试测试测试','2008-12-08 11:07:16',19),(4,1,10001,'JAVA很难吗?应该怎么样学习呢','请给我推荐几本JAVA的书,给我讲些学习方法谢谢','2008-12-08 11:07:16',14),(5,1,10002,'请教一句SQL这么写。。','这个SQL好难啊,应该怎么学呢','2008-12-08 11:07:16',12),(6,1,10001,'Integer类的一个小问题 ==比较','Integer内的值的大小在Byte范围内时,==比较返回true 在那范围之外返回false \n这是为什么呢,为什么会这样》? ','2008-12-08 11:07:34',32),(7,1,10002,'测试71','测试测试测试测试测试测试测试测试测试7','2008-12-08 11:08:09',13),(8,1,10001,'测试81','测试测试测试测试测试测试测试测试测试8','2008-12-08 11:08:09',21),(9,1,10002,'测试91','测试测试测试测试测试测试测试测试测试9','2008-12-08 11:08:09',16),(10,1,10001,'测试101','测试测试测试测试测试测试测试测试测试10','2008-12-08 11:08:09',29),(11,1,10002,'测试111','测试测试测试测试测试测试测试测试测试11','2008-12-08 11:08:09',12),(12,1,10001,'测试121','测试测试测试测试测试测试测试测试测试12','2008-12-08 11:08:09',13),(13,1,10005,'自动控制的课本是哪个?','自动控制的课本是哪个?自动控制的课本是哪个?自动控制的课本是哪个?','2008-12-12 01:18:07',2),(14,1,10000,'我是第一个来到这里的','第一个提问的哦 呵呵','2008-12-12 14:01:29',1),(15,1,10000,'aaaaaaaaaa','aabbbbbbbbbbbbbbbbbbbb','2009-03-16 20:44:05',6),(16,1,10000,'bbccccccccccccc','aaaaaaaaaaaaaa','2009-03-16 20:58:57',0),(17,1,10000,'11111111111111111','22222222222222222222','2009-03-16 21:00:00',2); /*!40000 ALTER TABLE `dy_topic` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `dy_topic_group` -- DROP TABLE IF EXISTS `dy_topic_group`; CREATE TABLE `dy_topic_group` ( `TGID` int(11) NOT NULL auto_increment, `TGName` varchar(50) NOT NULL, `TDetail` varchar(200) NOT NULL, PRIMARY KEY (`TGID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `dy_topic_group` -- LOCK TABLES `dy_topic_group` WRITE; /*!40000 ALTER TABLE `dy_topic_group` DISABLE KEYS */; INSERT INTO `dy_topic_group` VALUES (10000,'Java网络编程','计算机与自动控制学院'),(10001,'数据库系统概论','计算机与自动控制学院'),(10002,'C语言程序设计','计算机与自动控制学院'),(10003,'高等数学','理学院'),(10004,'线性代数','理学院'),(10005,'自动控制原理','机械学院'),(10006,'大学英语1','外国语学院'),(10007,'运筹学','经济管理学院'),(10008,'运筹学','经济管理学院'),(10009,'大学物理','基础课程'),(10010,'高等数学','基础课程'); /*!40000 ALTER TABLE `dy_topic_group` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `dy_tu` -- DROP TABLE IF EXISTS `dy_tu`; CREATE TABLE `dy_tu` ( `TUID` int(11) NOT NULL auto_increment, `UID` int(11) default NULL, `TGID` int(11) default NULL, PRIMARY KEY (`TUID`), KEY `UID` (`UID`), KEY `TGID` (`TGID`), CONSTRAINT `dy_tu_ibfk_1` FOREIGN KEY (`UID`) REFERENCES `dy_user` (`UID`) ON DELETE CASCADE, CONSTRAINT `dy_tu_ibfk_2` FOREIGN KEY (`TGID`) REFERENCES `dy_topic_group` (`TGID`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `dy_tu` -- LOCK TABLES `dy_tu` WRITE; /*!40000 ALTER TABLE `dy_tu` DISABLE KEYS */; INSERT INTO `dy_tu` VALUES (1,2,10000),(2,2,10001),(3,2,10002),(4,1,10001),(6,1,10005),(10,3,10002),(12,1,10000),(13,1,10002),(14,3,10001),(15,4,10001),(17,7,10001); /*!40000 ALTER TABLE `dy_tu` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `dy_user` -- DROP TABLE IF EXISTS `dy_user`; CREATE TABLE `dy_user` ( `UID` int(11) NOT NULL auto_increment, `UName` varchar(20) NOT NULL, `UPwd` varchar(20) NOT NULL, `UGender` char(2) default '男', `UEmail` varchar(40) default NULL, `URole` int(11) default '0', `UHead` varchar(50) default 'UserHead/no_head.jpg', `URegDate` date default NULL, `ULastLogin` datetime default NULL, `ULastEmit` datetime default NULL, `UPermit` int(11) default '1', PRIMARY KEY (`UID`), UNIQUE KEY `UName` (`UName`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `dy_user` -- LOCK TABLES `dy_user` WRITE; /*!40000 ALTER TABLE `dy_user` DISABLE KEYS */; INSERT INTO `dy_user` VALUES (1,'xyz','123456','男','fgdsa@163.com',0,'UserHead/1.jpg','2008-12-08','2009-03-16 22:16:20','2009-03-16 21:00:10',1),(2,'zrk','123456','男','sfdsaga@163.com',1,'UserHead/2.JPG','2008-12-08','2009-03-16 23:12:04','2008-12-12 13:27:24',1),(3,'胡再芬','123456','女','wereq@163.com',0,'UserHead/3.jpg','2008-12-08','2008-12-12 09:26:47',NULL,1),(4,'wyf','123456','男','gr4eg@163.com',3,'UserHead/1.jpg','2008-12-08','2009-03-17 15:11:32','2008-12-12 14:01:29',1),(5,'fdsa','123123','男','rfews@3421.com',0,'UserHead/no_head.jpg','2009-03-16','2009-03-16 17:41:24','2009-03-16 17:41:24',1),(7,'wfa','123123','男','fdsa@123.com',0,'UserHead/no_head.jpg','2009-03-16','2009-03-16 17:44:32','2009-03-16 17:44:32',1),(8,'few','123123','男','fdsa@123.com',0,'UserHead/no_head.jpg','2009-03-16','2009-03-16 17:45:11','2009-03-16 17:45:11',1); /*!40000 ALTER TABLE `dy_user` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2009-03-17 7:23:17 红色部分不知道什么意思,如果能解释下这几个表的关系,就更好了
Hibernate+SpringMvc+spring 事务不起效果(求大神帮忙看下)
appliactionContent.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 默认扫描的包路径 --> <context:component-scan base-package="zjl.website.*" /> <!-- 开启注解 --> <mvc:annotation-driven/> <!-- 属性文件读入 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:*.properties</value> </list> </property> </bean> <!-- 数据源定义,使用dbcp数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClassName}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 配置hibernate的SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 扫描hibernate注解配置的entity --> <property name="packagesToScan" value="zjl.website.entity" /> <!-- hibernate配置信息 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> </props> </property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="find*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="interceptorPointCuts" expression="execution(* zjl.website.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" /> </aop:config> </beans> hibernate.cxg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <!-- 连接数据库的操作 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/microblog?useUnicode=true</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- SQL dialect --> <!-- 数据库方言hql是hibernate官方的语言 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 控制台打印sql语句 --> <property name="show_sql">true</property> <mapping class="zjl.website.entity.User"></mapping> </session-factory> </hibernate-configuration> spring-servlet.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <import resource="classpath*:applicationContext.xml" /> <mvc:default-servlet-handler/> <!-- 默认扫描的包路径 --> <context:component-scan base-package="zjl.website.*" /> <!-- 定义跳转的文件的前后缀 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 添加注解驱动 --> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="utf-8" /> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=utf-8</value> <value>text/json;charset=utf-8</value> <value>application/json;charset=utf-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760" /> </bean> </beans> web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 默认跳转到根目录下的页面,在这里为index.jsp --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> ``` ![junit测试插入成功,但是可能事务没有提交在数据库中美有插入数据](https://img-ask.csdn.net/upload/201612/08/1481177671_274141.png) 第一次接触这东西,求大神帮忙看下,在线等
PHP网站语句如何优化,希望和高手一起探讨下
我的网站是PHP网站,使用的数据库是MySQL 的目前直接用网上的采集插件出现了很多慢查询和扫全表的动作,自己也在对应的表里建立了普通索引,但还是无法得到解决,一直报错在SQL语句里,对于这块本人学习尚浅。 MySQL引擎是InnoDB,下面是索引截图: ![图片说明](https://img-ask.csdn.net/upload/201906/16/1560632068_941383.jpg) 报错语句: select url from ve123_links_temp where url like 'jmw.com.cn%' UPDATE `ve123_links_temp` SET `no_id`='1' WHERE url='http://app.hiapk.com/hiapk/about/agreement' 还请各位高手指点迷津,到底如何优化 语句: <?php //抓全站--- 多线程 function all_links_duo($site_id,$ceng,$include_word,$not_include_word) { global $db; $new_url=array(); $fenge=array(); $nei=1;//1代表只收内链 2代表外链 空代表所有 $numm=2;//开启多少线程 echo "<br><b>开始抓取第".$ceng."层</b><br>"; $ceng++; $row=$db->get_one("select * from ve123_links_temp where site_id='".$site_id."' and no_id='0'"); if(empty($row)){echo " ---------- 没有新链接了<br>";return;}//如果找不到新增加url,则结束 $query=$db->query("select * from ve123_links_temp where site_id='".$site_id."' and no_id='0'"); while($row=$db->fetch_array($query)) { $new_url[]=$row[url]; } $he_num = ceil(count($new_url)/$numm);//计算需要循环多少次 $fenge=array_chunk($new_url,$numm);//把数组分割成多少块数组 每块大小$numm /* echo "一共多少个"; echo count($new_url); echo "需要循环"; echo $he_num; echo "次<br>"; */ for($i=0;$i<=$he_num;$i++) { /*echo "开始循环第 ".$i." 次<br>"; print_r($fenge[$i]); echo "<br>";*/ $fen_url = array(); $fen_url = cmi($fenge[$i]); //需要把得到的数组 (数组只包括 网址和源码) 分析 写入数据库 , /*echo "<b>本次抓完的网址为</b>"; print_r($fen_url[url]); echo "<br>";*/ foreach ((array)$fen_url as $url => $file) { $links = array(); $temp_links = array(); $cha_temp = array(); $loy = array(); $new_links = array(); $cha_links = array(); $cha_links_num = array(); $links = _striplinks($file); //从htmlcode中提取网址 $links = _expandlinks($links, $url); //补全网址 $links=check_wai($links,$nei,$url); $links=array_values(array_unique($links)); $bianma = bianma($file); //获取得到htmlcode的编码 $file = Convert_File($file,$bianma); //转换所有编码为gb2312 $loy = clean_lry($file,$url,"html"); $title=$loy["title"]; //从数组中得到标题,赋值给title $pagesize=number_format(strlen($file)/1024, 0, ".", ""); $fulltxt=Html2Text($loy["fulltext"]); $description=$loy["description"]; //从数组中得到标题,赋值给description $keywords=$loy["keywords"]; //从数组中得到标题,赋值给keywords $lrymd5=md5($fulltxt); $updatetime=time(); if($title==""){$title=str_cut($fulltxt,65); } //根据url,更新内容 $array=array('lrymd5'=>$lrymd5,'title'=>$title,'fulltxt'=>$fulltxt,'description'=>$description,'keywords'=>$keywords,'pagesize'=>$pagesize,'updatetime'=>$updatetime); $db->update("ve123_links",$array,"url='".$url."'"); $all_num = count($links); //开始读取 ve123_links_temp 中所有site_id 为$site_id 的url 然后和抓取的 $links 数组比较,将得到的差集创建到 ve123_links_temp 中 $query=$db->query("select url from ve123_links_temp where url like '%".getdomain($url)."%'"); while($row=$db->fetch_array($query)) { $temp_links[]=rtrim($row[url],"/"); } $cha_temp=array_diff($links,$temp_links); foreach((array)$cha_temp as $value) { if(check_include($value, $include_word, $not_include_word )) { $arral=array('url'=>$value,'site_id'=>$site_id); $db->insert("ve123_links_temp",$arral); } } //开始读取 ve123_links 中所有site_id 为 $site_id 的url 然后和抓取的 $links 数组比较,将得到的差集创建到 ve123_links 中 合集则输出 已存在了 $query=$db->query("select url from ve123_links where url like '%".getdomain($url)."%'"); while($row=$db->fetch_array($query)) { $new_links[]=rtrim($row[url],"/"); } $cha_links=array_diff($links,$new_links); foreach((array)$cha_links as $value) { if(check_include($value, $include_word, $not_include_word )) { $array=array('url'=>$value,'site_id'=>$site_id,'level'=>'1'); $db->insert("ve123_links",$array); $cha_links_num[]=$value; } } $cha_num = count($cha_links_num); printLinksReport($cha_num, $all_num, $cl=0); echo "<a href=".$url." target=_blank>".$url. "</a><br>"; $arral=array('no_id'=>1); $db->update("ve123_links_temp",$arral,"url='$url'"); ob_flush(); flush(); } } all_links_duo($site_id,$ceng,$include_word,$not_include_word);//再次调用本函数开始循环 } //一键找站 function find_sites($site_id,$ceng) { global $db; $new_url=array(); $fenge=array(); $numm=20;//开启多少线程 echo "<br><b>开始抓取第".$ceng."层</b><br>"; $ceng++; $row=$db->get_one("select * from ve123_sites_temp where site_id='".$site_id."' and no_id='0'"); if(empty($row)){echo " ---------- 没有新链接了<br>";return;}//如果找不到新增加url,则结束 $query=$db->query("select * from ve123_sites_temp where site_id='".$site_id."' and no_id='0'"); while($row=$db->fetch_array($query)) { $new_url[]=$row[url]; } $he_num = ceil(count($new_url)/$numm);//计算需要循环多少次 $fenge=array_chunk($new_url,$numm);//把数组分割成多少块数组 每块大小$numm for($i=0;$i<=$he_num;$i++) { $fen_url = array(); $fen_url = cmi($fenge[$i]); //需要把得到的数组 (数组只包括 网址和源码) 分析 写入数据库 , foreach ((array)$fen_url as $url => $file) { $links = array(); $fen_link = array(); $nei_link = array(); $wai_link = array(); $new_temp = array(); $cha_temp = array(); $new_site = array(); $cha_site = array(); $new_lik = array(); $cha_lik = array(); $links = _striplinks($file); //从htmlcode中提取网址 $links = _expandlinks($links, $url); //补全网址 $fen_link=fen_link($links,$url); //把内链和外链分开 $nei_link=array_values(array_unique($fen_link[nei])); //过滤内链 重复的网址 $wai_link=GetSiteUrl($fen_link[wai]); //把外链都转换成首页 $wai_link=array_values(array_unique($wai_link)); //过滤外链 重复的网址 //读出 ve123_sites_temp 中所有 site_id=-1 and no_id=0 $query=$db->query("select url from ve123_sites_temp where site_id='".$site_id."'"); while($row=$db->fetch_array($query)) { $new_temp[]=$row[url]; } $cha_temp=array_diff($nei_link,$new_temp);//与内链进行比较 得出差集 //将差集创建到 ve123_sites_temp 中 foreach((array)$cha_temp as $value) { $arral=array('url'=>$value,'site_id'=>$site_id,'no_id'=>0); $db->insert("ve123_sites_temp",$arral); } //读出 ve123_sites 中所有 site_id=-1 global $db; $query=$db->query("select url from ve123_sites where site_no='".$site_id."'"); while($row=$db->fetch_array($query)) { $new_site[]=$row[url]; } $cha_site=array_diff($wai_link,$new_site);//与外链进行比较 得出差集 //将差集创建到 ve123_sites 中 foreach((array)$cha_site as $value) { $arral=array('url'=>$value,'site_no'=>$site_id); $db->insert("ve123_sites",$arral); } //读出 ve123_links 中所有 site_id=-1 global $db; global $db; $query=$db->query("select url from ve123_links where site_id='".$site_id."'"); while($row=$db->fetch_array($query)) { $new_lik[]=$row[url]; } $cha_lik=array_diff($wai_link,$new_lik);//与外链进行比较 得出差集 //将得到的差集 创建到 ve123_links foreach ((array)$cha_lik as $value) { $array=array('url'=>$value,'site_id'=>$site_id); $db->insert("ve123_links",$array); echo "<font color=#C60A00><b>抓取到:</b></font>"; echo "<a href=".$value." target=_blank>".$value."</a><br>"; } $arral=array('no_id'=>1); $db->update("ve123_sites_temp",$arral,"url='$url'"); ob_flush(); flush(); } } find_sites($site_id,$ceng);//再次调用本函数开始循环 } //一键更新 已抓站 function Update_sites($site_id) { global $db; $numm=20;//开启多少线程 $new_url = array(); $fenge = array(); $query=$db->query("select url from ve123_links where site_id='".$site_id."' and length(lrymd5)!=32"); while($row=$db->fetch_array($query)) { $new_url[]=$row[url]; } $he_num = ceil(count($new_url)/$numm);//计算需要循环多少次 $fenge=array_chunk($new_url,$numm);//把数组分割成多少块数组 每块大小$numm for($i=0;$i<=$he_num;$i++) { $fen_url = array(); $fen_url = cmi($fenge[$i]); //需要把得到的数组 (数组只包括 网址和源码) 分析 写入数据库 , foreach ((array)$fen_url as $url => $file) { $links = array(); $temp_links = array(); $cha_temp = array(); $loy = array(); $new_links = array(); $cha_links = array(); $cha_links_num = array(); $bianma = bianma($file); //获取得到htmlcode的编码 $file = Convert_File($file,$bianma); //转换所有编码为gb2312 if($file==-1) {echo "<b><font color=#C60A00>抓取失败</b></font> ".$url."<br>"; continue;} $loy = clean_lry($file,$url,"html"); //设置分析数组 $title=$loy["title"]; //从数组中得到标题,赋值给title $pagesize=number_format(strlen($file)/1024, 0, ".", ""); $fulltxt=Html2Text($loy["fulltext"]); $description=$loy["description"]; //从数组中得到标题,赋值给description $keywords=$loy["keywords"]; //从数组中得到标题,赋值给keywords $lrymd5=md5($fulltxt); $updatetime=time(); if($title==""){$title=str_cut($fulltxt,65); } //根据url,更新内容 echo "<b><font color=#0Ae600>已更新</font></b>"; echo $title; echo "<a href=".$url." target=_blank>".$url. "</a><br>"; $array=array('lrymd5'=>$lrymd5,'title'=>$title,'fulltxt'=>$fulltxt,'description'=>$description,'keywords'=>$keywords,'pagesize'=>$pagesize,'updatetime'=>$updatetime); $db->update("ve123_links",$array,"url='".$url."'"); } } } //一键找站 暂时不用的 function find_sites_($url) { $oldtime=time(); $site_id = -1; $numm=10; $links=array(); $fen_link=array(); $lrp =array(); $nei_link =array(); $wai_link =array(); $new_temp =array(); $cha_temp =array(); $new_site =array(); $cha_site =array(); $new_lik =array(); $cha_lik =array(); $fenge =array(); $lrp = cmi($url); $links = _striplinks($lrp[$url]); //从htmlcode中提取网址 $links = _expandlinks($links, $url); //补全网址 $fen_link=fen_link($links,$url); //把内链和外链分开 $nei_link=array_values(array_unique($fen_link[nei])); //过滤内链 重复的网址 $wai_link=GetSiteUrl($fen_link[wai]); //把外链都转换成首页 $wai_link=array_values(array_unique($wai_link)); //过滤外链 重复的网址 /*print_r($nei_link); echo "<br><br>"; print_r($wai_link);*/ //读出 ve123_sites_temp 中所有 site_id=-1 and no_id=0 global $db; $query=$db->query("select url from ve123_sites_temp where site_id='-1' and no_id='0'"); while($row=$db->fetch_array($query)) { $new_temp[]=$row[url]; } $cha_temp=array_diff($nei_link,$new_temp);//与内链进行比较 得出差集 //将差集创建到 ve123_sites_temp 中 foreach((array)$cha_temp as $value) { $arral=array('url'=>$value,'site_id'=>$site_id,'no_id'=>0); $db->insert("ve123_sites_temp",$arral); } //读出 ve123_temp 中所有 site_id=-1 global $db; global $db; $query=$db->query("select url from ve123_sites where site_no='-1'"); while($row=$db->fetch_array($query)) { $new_site[]=$row[url]; } $cha_site=array_diff($wai_link,$new_site);//与外链进行比较 得出差集 //将差集创建到 ve123_sites 中 foreach((array)$cha_site as $value) { $arral=array('url'=>$value,'site_no'=>$site_id); $db->insert("ve123_sites",$arral); } //读出 ve123_links 中所有 site_id=-1 global $db; global $db; $query=$db->query("select url from ve123_sites where site_id='-1'"); while($row=$db->fetch_array($query)) { $new_lik[]=$row[url]; } $cha_lik=array_diff($wai_link,$new_lik);//与外链进行比较 得出差集 //将得到的差集 创建到 ve123_links $he_num = ceil(count($cha_lik)/$numm);//计算需要循环多少次 $fenge=array_chunk($cha_lik,$numm);//把数组分割成多少块数组 每块大小$numm for($i=0;$i<=$he_num;$i++) { $fen_url = array(); $fen_url = cmi($fenge[$i]); //多线程开始采集 foreach ((array)$fen_url as $url => $file) { $bianma = bianma($file); //获取得到htmlcode的编码 $file = Convert_File($file,$bianma); //转换所有编码为gb2312 $loy = clean_lry($file,$url,"html"); //过滤 file 中标题等 到数组 $title=$loy["title"]; //从数组中得到标题,赋值给title $pagesize=number_format(strlen($file)/1024, 0, ".", ""); $fulltxt=Html2Text($loy["fulltext"]); $description=$loy["description"]; //从数组中得到标题,赋值给description $keywords=$loy["keywords"]; //从数组中得到标题,赋值给keywords $lrymd5=md5($fulltxt); $updatetime=time(); if($title==""){$title=str_cut($fulltxt,65); } //根据url,更新内容 $array=array('url'=>$value,'lrymd5'=>$lrymd5,'title'=>$title,'fulltxt'=>$fulltxt,'description'=>$description,'keywords'=>$keywords,'pagesize'=>$pagesize,'updatetime'=>$updatetime); $db->insert("ve123_links",$array); echo "<font color=#C60A00><b>抓取到:</b></font>".$title; echo "<a href=".$url." target=_blank>".$url."</a><br>"; } } $newtime=time(); echo " --- <b>用时:</b>"; echo date("H:i:s",$newtime-$oldtime-28800); echo "<br>"; del_links_temp($site_id); } //抓全站--- 单线程 function all_url_dan($url,$old,$nei,$ooo,$site_id,$include_word,$not_include_word) { if(!is_url($url)) { return false;} global $db,$config; $snoopy = new Snoopy; //国外snoopy程序 $snoopy->fetchlry($url); $links=$snoopy->resulry; if(!is_array($links)) {return;} $links=check_wai($links,$nei,$url); $links=array_values(array_unique($links)); $title=$snoopy->title; $fulltxt=$snoopy->fulltxt; $lrymd5=md5($fulltxt); $pagesize=$snoopy->pagesize; $description=$snoopy->description; $keywords=$snoopy->keywords; $updatetime=time(); if($title==""){$title=str_cut($fulltxt,65); } //读取url,更新内容 $array=array('lrymd5'=>$lrymd5,'title'=>$title,'fulltxt'=>$fulltxt,'description'=>$description,'keywords'=>$keywords,'pagesize'=>$pagesize,'updatetime'=>$updatetime); $db->update("ve123_links",$array,"url='".$url."'"); $all_num = count($links); $temp_links=array(); $cha_temp=array(); //开始读取 ve123_links_temp 中所有site_id 为$site_id 的url 然后和抓取的 $links 数组比较,将得到的差集创建到 ve123_links_temp 中 $query=$db->query("select url from ve123_links_temp where url like '%".getdomain($url)."%'"); while($row=$db->fetch_array($query)) { $temp_links[]=rtrim($row[url],"/"); } $cha_temp=array_diff($links,$temp_links); foreach((array)$cha_temp as $value) { $arral=array('url'=>$value,'site_id'=>$site_id); $db->insert("ve123_links_temp",$arral); } //开始读取 ve123_links 中所有site_id 为 $site_id 的url 然后和抓取的 $links 数组比较,将得到的差集创建到 ve123_links 中 合集则输出 已存在了 $query=$db->query("select url from ve123_links where url like '%".getdomain($url)."%'"); while($row=$db->fetch_array($query)) { $new_links[]=rtrim($row[url],"/"); } $cha_links=array_diff($links,$new_links); $cha_num = count($cha_links); foreach((array)$cha_links as $value) { if(check_include($value, $include_word, $not_include_word )) { $array=array('url'=>$value,'site_id'=>$site_id,'level'=>'1'); $db->insert("ve123_links",$array); } } printLinksReport($cha_num, $all_num, $cl=0); echo "<a href=".$old." target=_blank>".$old. "</a>"; ob_flush(); flush(); } //抓全站--- 单线程---不用的 function add_all_url_ ($url,$old,$numm,$ooo,$site_id,$include_word,$not_include_word) { if(!is_url($url)) { return false;} global $db,$config; $snoopy = new Snoopy; //国外snoopy程序 $snoopy->fetchlry($url); $links=$snoopy->resulry; if(!is_array($links)) {return;} $links=check_wai($links,$numm,$url); $links=array_values(array_unique($links)); $title=$snoopy->title; $fulltxt=$snoopy->fulltxt; $lrymd5=md5($fulltxt); $pagesize=$snoopy->pagesize; $description=$snoopy->description; $keywords=$snoopy->keywords; $updatetime=time(); if($title==""){$title=str_cut($fulltxt,65); } //读取url,更新内容 $array=array('lrymd5'=>$lrymd5,'title'=>$title,'fulltxt'=>$fulltxt,'description'=>$description,'keywords'=>$keywords,'pagesize'=>$pagesize,'updatetime'=>$updatetime); $db->update("ve123_links",$array,"url='".$url."'"); $all_num = count($links); $temp_links=array(); $cha_temp=array(); //开始读取 ve123_links_temp 中所有site_id 为$site_id 的url 然后和抓取的 $links 数组比较,将得到的差集创建到 ve123_links_temp 中 $query=$db->query("select url from ve123_links_temp where url like '%".getdomain($url)."%'"); while($row=$db->fetch_array($query)) { $temp_links[]=rtrim($row[url],"/"); } $cha_temp=array_diff($links,$temp_links); foreach((array)$cha_temp as $value) { $arral=array('url'=>$value,'site_id'=>$site_id); $db->insert("ve123_links_temp",$arral); } //开始读取 ve123_links 中所有site_id 为 $site_id 的url 然后和抓取的 $links 数组比较,将得到的差集创建到 ve123_links 中 合集则输出 已存在了 $query=$db->query("select url from ve123_links where url like '%".getdomain($url)."%'"); while($row=$db->fetch_array($query)) { $new_links[]=rtrim($row[url],"/"); } $he_links=array_intersect($links,$new_links); $he_num = count($he_links); $cha_links=array_diff($links,$new_links); $cha_num = count($cha_links); foreach((array)$cha_links as $value) { if(check_include($value, $include_word, $not_include_word )) { $array=array('url'=>$value,'site_id'=>$site_id,'level'=>'1'); $db->insert("ve123_links",$array); } } printLinksReport($cha_num, $all_num, $cl=0); echo "<a href=".$old." target=_blank>".$old. "</a>"; ob_flush(); flush(); } function printLinksReport($cha_num, $all_num, $cl) { global $print_results, $log_format; $cha_html = " <font color=\"blue\">页面包含<b>$all_num</b>条链接</font>。 <font color=\"red\"><b>$cha_num</b>条新链接。</font>\n"; $no_html = " <font color=\"blue\">页面包含<b>$all_num</b>条链接</font>。 没有新链接。\n"; if($cha_num==0) {print $no_html; flush();} else{print $cha_html;} } function add_links_insite($link,$old,$numm,$ooo,$site_id,$include_word,$not_include_word) { if(!is_url($link)) { return false; } global $db,$config; /* $spider=new spider; //系统自带蜘蛛 echo "<b>网站编码</b>(默认GB2312)<b>:"; $spider->url($link); echo "</b><br>"; $links= $spider->get_insite_links(); */ //$site_url=GetSiteUrl($link); $url_old=GetSiteUrl($old); echo "原始页=".$url_old." - - <"; echo "首层 id=".$site_id."> - - <"; echo "包含字段=".$include_word.">"; echo "<br>"; /*if($ooo==0) { $site=$db->get_one("select * from ve123_sites where url='".$url_old."'"); $site_id=$site["site_id"]; $include_word=$site["include_word"]; $not_include_word=$site["not_include_word"]; $spider_depth=$site["spider_depth"]; } */ $snoopy = new Snoopy; //国外snoopy程序 $snoopy->fetchlinks($link); $links=$snoopy->results; $links=check_wai($links,$numm,$link); $links=array_values(array_unique($links)); foreach((array)$links as $value) { $row=$db->get_one("select * from ve123_links_temp where url='".$value."'"); if(empty($row)) { $arral=array('url'=>$value,'site_id'=>$site_id); $db->insert("ve123_links_temp",$arral); } $value=rtrim($value,"/"); $row=$db->get_one("select * from ve123_links where url='".$value."'"); if (check_include($value, $include_word, $not_include_word )) { if(empty($row)&&is_url($value)) { echo "<font color=#C60A00><b>抓取到:</b></font>"; $array=array('url'=>$value,'site_id'=>$site_id,'level'=>'1'); $db->insert("ve123_links",$array); } else { echo "<b>已存在了:</b>";} echo "<a href=".$value." target=_blank>".$value. "</a><br>"; ob_flush(); flush(); //$row=$db->get_one("select * from ve123_links_temp where url='".$value."'"); // if(empty($row)&&is_url($value)) // { // $array=array('url'=>$value,'site_id'=>$site_id); // $db->insert("ve123_links_temp",$array); // } } } } //只保留内链或者外链 function check_wai($lry_all,$nei,$url) { $lry_nei=array();//站内链接数组 $lry_wai=array();//站外链接数组 $new_url=getdomain($url); if($nei=="") { foreach ((array)$lry_all as $value) { $lry_nei[]=rtrim($value,"/"); } return $lry_nei; } foreach ((array)$lry_all as $value) { if(getdomain($value)==$new_url) { $lry_nei[]=rtrim($value,"/"); //$lry_nei[]=$value; } else { $lry_wai[]=rtrim($value,"/"); } } if($nei==1){return $lry_nei;} if($nei==2){return $lry_wai;} } //把内链和外链分开 function fen_link($lry_all,$url) { $data=array();//站外链接数组 $new_url=getdomain($url); foreach ((array)$lry_all as $value) { if(getdomain($value)==$new_url) { $data['nei'][]=rtrim($value,"/"); } else { $data['wai'][]=rtrim($value,"/"); } } return $data; } function check_include($link, $include_word, $not_include_word) { $url_word = Array (); $not_url_word = Array (); $is_shoulu = true; if ($include_word != "") { $url_word = explode(",", $include_word); } if ($not_include_word != "") { $not_url_word = explode(",", $not_include_word); } foreach ($not_url_word as $v_key) { $v_key = trim($v_key); if ($v_key != "") { if (substr($v_key, 0, 1) == '*') { if (preg_match(substr($v_key, 1), $link)) { $is_shoulu = false; break; } } else { if (!(strpos($link, $v_key) === false)) { $is_shoulu = false; break; } } } } if ($is_shoulu && $include_word != "") { $is_shoulu = false; foreach ($url_word as $v_key) { $v_key = trim($v_key); if ($v_key != "") { if (substr($v_key, 0, 1) == '*') { if (preg_match(substr($v_key, 1), $link)) { $is_shoulu = true; break 2; } } else { if (strpos($link, $v_key) !== false) { $is_shoulu = true; break; } } } } } return $is_shoulu; } function add_links_site_fromtemp($in_url) { global $db; $domain=getdomain($in_url); $query=$db->query("select * from ve123_links_temp where url like '%".$domain."%' and no_id='0'"); while($row=$db->fetch_array($query)) { @$db->query("update ve123_links_temp set no_id='1' where url='".$row["url"]."'"); add_links_insite($row["url"],$row["url"],1,1); //sleep(3); } //sleep(5); add_links_site_fromtemp($in_url) ; } function insert_links($url) { global $db,$config; $spider=new spider; $spider->url($url); $links= $spider->links(); $sites= $spider->sites(); foreach($sites as $value) { $site_url=GetSiteUrl($link); $site=$db->get_one("select * from ve123_sites where url='".$site_url."'"); $site_id=$site["site_id"]; $row=$db->get_one("select * from ve123_links where url='".$value."'"); if(empty($row)&&is_url($value)) { echo $value."<br>"; $array=array('url'=>$value,'site_id'=>$site_id,'level'=>'0'); $db->insert("ve123_links",$array); } else { echo "已存在:".$value."<br>"; } ob_flush(); flush(); //sleep(1); $row=$db->get_one("select * from ve123_sites where url='".$value."'"); if(empty($row)&&is_url($value)) { $array=array('url'=>$value,'spider_depth'=>$config["spider_depth"],'addtime'=>time()); $db->insert("ve123_sites",$array); } } //sleep(1); foreach($links as $value) { $row=$db->get_one("select * from ve123_links_temp where url='".$value."'"); if(empty($row)&&is_url($value)) { $array=array('url'=>$value); $db->insert("ve123_links_temp",$array); } } } function GetUrl_AllSite($in_url) { global $db; $query=$db->query("select * from ve123_links_temp where url like '%".$in_url."%' and updatetime<='".(time()-(86400*30))."'"); while($row=$db->fetch_array($query)) { @$db->query("update ve123_links_temp set updatetime='".time()."' where url='".$row["url"]."'"); insert_links($row["url"]); //sleep(3); } //sleep(5); GetUrl_AllSite($in_url) ; } function Updan_link($url,$site_id) { global $db; $row=$db->get_one("select * from ve123_links_temp where url='".$url."'"); if(empty($row)) { $arral=array('url'=>$url,'site_id'=>$site_id); $db->insert("ve123_links_temp",$arral); } $row=$db->get_one("select * from ve123_links where url like '%".$url."%'"); if(empty($row)) { echo "<font color=#C60A00><b>抓取到:</b></font>".$url."<br>"; $array=array('url'=>$url,'site_id'=>$site_id,'level'=>'1'); $db->insert("ve123_links",$array); } else { echo "已存在:".$url."<br>"; } } function Updan_zhua($url,$site_id) { global $db; $lrp = array(); $links = array(); $fen_link = array(); $nei_link = array(); $new_temp = array(); $cha_temp = array(); $lrp = cmi($url); $links = _striplinks($lrp[$url]); //从htmlcode中提取网址 $links = _expandlinks($links, $url); //补全网址 $fen_link=fen_link($links,$url); //把内链和外链分开 $nei_link=array_values(array_unique($fen_link[nei])); //过滤内链 重复的网址 //读出 ve123_sites_temp 中所有 site_id=-1 and no_id=0 $query=$db->query("select url from ve123_sites_temp where site_id='".$site_id."'"); while($row=$db->fetch_array($query)) { $new_temp[]=$row[url]; } $cha_temp=array_diff($nei_link,$new_temp);//与内链进行比较 得出差集 //将差集创建到 ve123_sites_temp 中 foreach((array)$cha_temp as $value) { $arral=array('url'=>$value,'site_id'=>$site_id,'no_id'=>0); $db->insert("ve123_sites_temp",$arral); } } function Update_link($url) { global $db,$bug_url; $is_success=FALSE; $is_shoulu=FALSE; /*$spider=new spider; $spider->url($url); $title=$spider->title; $fulltxt=$spider->fulltxt; $lrymd5=md5($spider->fulltxt); $pagesize=$spider->pagesize; $keywords=$spider->keywords; $htmlcode=$spider->htmlcode; $description=$spider->description;*/ $snoopy = new Snoopy; //国外snoopy程序 $snoopy->fetchtext($url); $title=$snoopy->title; $fulltxt=$snoopy->fulltxt; $lrymd5=md5($fulltxt); $pagesize=$snoopy->pagesize; $description=$snoopy->description; $keywords=$snoopy->keywords; //echo "fulltxt=".$fulltxt."<br>"; $updatetime=time(); //$site_url=GetSiteUrl($url); //$site=$db->get_one("select * from ve123_sites where url='".$site_url."'"); //$site_id=$site["site_id"]; //echo "site_id".$site["site_id"]."<br>"; if($title==""){$title=str_cut($fulltxt,65); } echo "<b><font color=#0Ae600>已更新</font></b>"; echo $title; $array=array('lrymd5'=>$lrymd5,'title'=>$title,'fulltxt'=>$fulltxt,'description'=>$description,'keywords'=>$keywords,'pagesize'=>$pagesize,'updatetime'=>$updatetime); //$db->query("update ve123_links set updatetime='".time()."' where url='".$url."'"); //更新时间 //$s=array(); //$s=explode("?",$title); //$domain=GetSiteUrl($url); //$site=$db->get_one("select * from ve123_sites where url='".$domain."'"); $db->update("ve123_links",$array,"url='".$url."'"); $is_success=TRUE; if(empty($bug_url)) { exit(); } return $is_success; } function Update_All_Link_($in_url='',$days,$qiangzhi) { global $db; $new_url=array(); $fen_url=array(); $fenge=array(); $numm=20;//开启多少线程 //if($qiangzhi==0){ $lry="and strlen(lrymd5)!=32";} //else { ;} if(empty($in_url)) { $sql="select url from ve123_links where length(lrymd5)!=32 order by link_id desc"; } else { $sql="select url from ve123_links where url like '%".getdomain($in_url)."%' and length(lrymd5)!=32 order by link_id desc"; } echo $sql."<br>"; $query=$db->query($sql); while($row=$db->fetch_array($query)) { $new_url[]=$row[url]; } $he_num = ceil(count($new_url)/$numm);//计算需要循环多少次 //echo "<br><b>需要循环多少次=</b>".$he_num."<br>"; $fenge=array_chunk($new_url,$numm);//把数组分割成多少块数组 每块大小$numm for($i=0;$i<=$he_num;$i++) //for($i=0;$i<=1;$i++) { $fen_url=cmi($fenge[$i]); //需要把得到的数组 (数组只包括 网址和源码) 分析 写入数据库 , foreach ((array)$fen_url as $url => $file) { $bianma = bianma($file); //获取得到htmlcode的编码 $file = Convert_File($file,$bianma); //转换所有编码为gb2312 $lry = clean_lry($file,$url,"html"); $title=$lry["title"]; //从数组中得到标题,赋值给title $pagesize=number_format(strlen($file)/1024, 0, ".", ""); $fulltxt=Html2Text($lry["fulltext"]); $description=$lry["description"]; //从数组中得到标题,赋值给description $keywords=$lry["keywords"]; //从数组中得到标题,赋值给keywords $lrymd5=md5($fulltxt); $updatetime=time(); if($title==""){$title=str_cut($fulltxt,65); } echo "<b><font color=#0Ae600>已更新</font></b>"; echo $title; echo "<a href=".$url." target=_blank>".$url. "</a><br>"; $array=array('lrymd5'=>$lrymd5,'title'=>$title,'fulltxt'=>$fulltxt,'description'=>$description,'keywords'=>$keywords,'pagesize'=>$pagesize,'updatetime'=>$updatetime); $db->update("ve123_links",$array,"url='".$url."'"); } } } function cmi($links,$killspace=TRUE,$forhtml=TRUE,$timeout=6,$header=0,$follow=1){ $res=array();//用于保存结果 $mh = curl_multi_init();//创建多curl对象,为了几乎同时执行 foreach ((array)$links as $i => $url) { $conn[$url]=curl_init($url);//若url中含有gb2312汉字,例如FTP时,要在传入url的时候处理一下,这里不用 curl_setopt($conn[$url], CURLOPT_TIMEOUT, $timeout);//此时间须根据页面的HTML源码出来的时间,一般是在1s内的,慢的话应该也不会6秒,极慢则是在16秒内 curl_setopt($conn[$url], CURLOPT_HEADER, $header);//不返回请求头,只要源码 curl_setopt($conn[$url],CURLOPT_RETURNTRANSFER,1);//必须为1 curl_setopt($conn[$url], CURLOPT_FOLLOWLOCATION, $follow);//如果页面含有自动跳转的代码如301或者302HTTP时,自动拿转向的页面 curl_multi_add_handle ($mh,$conn[$url]);//关键,一定要放在上面几句之下,将单curl对象赋给多对象 } //下面一大步的目的是为了减少cpu的无谓负担,暂时不明,来自php.net的建议,几乎是固定用法 do { $mrc = curl_multi_exec($mh,$active);//当无数据时或请求暂停时,active=true } while ($mrc == CURLM_CALL_MULTI_PERFORM);//当正在接受数据时 while ($active and $mrc == CURLM_OK) {//当无数据时或请求暂停时,active=true,为了减少cpu的无谓负担,这一步很难明啊 if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } foreach ((array)$links as $i => $url) { $cinfo=curl_getinfo($conn[$url]);//可用于取得一些有用的参数,可以认为是header $res[$url]=curl_multi_getcontent($conn[$url]); if(!$forhtml){//节约内存 $res[$url]=NULL; } /*下面这一段放一些高消耗的程序代码,用来处理HTML,我保留的一句=NULL是要提醒,及时清空对象释放内存,此程序在并发过程中如果源码太大,内在消耗严重 //事实上,这里应该做一个callback函数或者你应该将你的逻辑直接放到这里来,我为了程序可重复,没这么做 preg_match_all($preg,$res[$i],$matchlinks); $res[$i]=NULL;*/ curl_close($conn[$url]);//关闭所有对象 curl_multi_remove_handle($mh , $conn[$url]); //用完马上释放资源 } curl_multi_close($mh);$mh=NULL;$conn=NULL;$links=NULL; return $res; } function clean_lry($file, $url, $type) { $data=array(); $file = preg_replace("/<link rel[^<>]*>/i", " ", $file); //$file = preg_replace("@<!--sphider_noindex-->.*?<!--\/sphider_noindex-->@si", " ",$file); $file = preg_replace("@<!--.*?-->@si", " ",$file); $file = preg_replace("@<script[^>]*?>.*?</script>@si", " ",$file); $file = preg_replace("/&nbsp;/", " ", $file); $file = preg_replace("/&raquo;/", " ", $file); $file=str_replace("'","‘",$file); $regs = Array (); preg_match("/<meta +name *=[\"']?description[\"']? *content=[\"']?([^<>'\"]+)[\"']?/i", $file, $regs); if (isset ($regs)) { $description = $regs[1]; $file = str_replace($regs[0], "", $file); } $regs = Array (); preg_match("/<meta +name *=[\"']?keywords[\"']? *content=[\"']?([^<>'\"]+)[\"']?/i", $file, $regs); if (isset ($regs)) { $keywords = $regs[1]; $file = str_replace($regs[0], "", $file); } $regs = Array (); $keywords = preg_replace("/[, ]+/", " ", $keywords); if (preg_match("@<title *>(.*?)<\/title*>@si", $file, $regs)) { $title = trim($regs[1]); $file = str_replace($regs[0], "", $file); } $file = preg_replace("@<style[^>]*>.*?<\/style>@si", " ", $file); //create spaces between tags, so that removing tags doesnt concatenate strings $file = preg_replace("/<[\w ]+>/", "\\0 ", $file); $file = preg_replace("/<\/[\w ]+>/", "\\0 ", $file); $file = strip_tags($file); //$fulltext = $file; //$file .= " ".$title; $file = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $file); $file = preg_replace('~&#([0-9]+);~e', 'chr("\\1")', $file); $file = strtolower($file); $file = preg_replace("/&[a-z]{1,6};/", " ", $file); $file = preg_replace("/[\*\^\+\?\\\.\[\]\^\$\|\{\)\(\}~!\"\/@#?%&=`?><:,]+/", " ", $file); $file = preg_replace("/\s+/", " ", $file); //$data['fulltext'] = $fulltext; $data['fulltext'] = addslashes($file); $data['title'] = addslashes($title); $data['description'] = $description; $data['keywords'] = $keywords; return $data; } function bianma($file) { preg_match_all("/<meta.+?charset=([-\w]+)/i",$file,$rs); $chrSet=strtoupper(trim($rs[1][0])); return $chrSet; } function Convert_File($file,$charSet) { $conv_file = html_entity_decode($file); $charSet = strtoupper(trim($charSet)); if($charSet != "GB2312"&&$charSet != "GBK") { $file=convertfile($charSet,"GB2312",$conv_file); if($file==-1){ return -1; } } return $file; } function convertfile($in_charset, $out_charset, $str) { //if(function_exists('mb_convert_encoding')) //{ $in_charset=explode(',',$in_charset); $encode_arr = array('GB2312','GBK','UTF-8','ASCII','BIG5','JIS','eucjp-win','sjis-win','EUC-JP'); $cha_temp=array_intersect($encode_arr,$in_charset); $cha_temp=implode('',$cha_temp); if(empty($in_charset)||empty($cha_temp)) { $encoded = mb_detect_encoding($str, $encode_arr); $in_charset=$encoded; } if(empty($in_charset)){ return -1; } echo $in_charset; return mb_convert_encoding($str, $out_charset, $in_charset); /*} else { require_once PATH.'include/charset.func.php'; $in_charset = strtoupper($in_charset); $out_charset = strtoupper($out_charset); if($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312')) { return utf8_to_gbk($str); } if(($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8') { return gbk_to_utf8($str); } return $str; }*/ } function Update_All_Link($in_url='',$days,$qiangzhi) { global $db; if(empty($in_url)) { //$sql="select * from ve123_links where updatetime<='".(time()-(86400*$days))."' order by link_id desc";//echo $days."<br>"; $sql="select * from ve123_links where updatetime+86400 <".time()." order by link_id ";//echo $days."<br>"; } else { $sql="select * from ve123_links where url like '%".getdomain($in_url)."%' order by link_id desc";//echo $days."<br>"; //$sql="select * from ve123_links where url like '%".$in_url."%' order by link_id desc";//echo $days."<br>"; } //$sql="select * from ve123_links order by link_id"; echo $sql."<br>"; $query=$db->query($sql); while($row=$db->fetch_array($query)) { if(is_url($row["url"])) { // echo "呵呵呵呵".$row["lrymd5"]."<br>"; ob_flush(); flush(); //sleep(1); //if($row["lrymd5"]==""){ Update_link($row["url"],$row["lrymd5"]); } if($qiangzhi==1){ Update_link($row["url"]); } else { if(strlen($row["lrymd5"])!=32){ Update_link($row["url"]); } else {echo ""; } } echo ""; } ////sleep(2); } // echo "<br><b>全部更新完成</b> 完成日期:"; // echo date("Y年m月d日 H:i:s",time()); //sleep(2); // Update_All_Link($in_url) ; } function url_ce($val, $parent_url, $can_leave_domain) { global $ext, $mainurl, $apache_indexes, $strip_sessids; $valparts = parse_url($val); $main_url_parts = parse_url($mainurl); //if ($valparts['host'] != "" && $valparts['host'] != $main_url_parts['host'] && $can_leave_domain != 1) {return '';} reset($ext); while (list ($id, $excl) = each($ext)) if (preg_match("/\.$excl$/i", $val)) return ''; if (substr($val, -1) == '\\') {return '';} if (isset($valparts['query'])) {if ($apache_indexes[$valparts['query']]) {return '';}} if (preg_match("/[\/]?mailto:|[\/]?javascript:|[\/]?news:/i", $val)) {return '';} if (isset($valparts['scheme'])) {$scheme = $valparts['scheme'];} else {$scheme ="";} if (!($scheme == 'http' || $scheme == '' || $scheme == 'https')) {return '';} $regs = Array (); while (preg_match("/[^\/]*\/[.]{2}\//", $valpath, $regs)) { $valpath = str_replace($regs[0], "", $valpath); } $valpath = preg_replace("/\/+/", "/", $valpath); $valpath = preg_replace("/[^\/]*\/[.]{2}/", "", $valpath); $valpath = str_replace("./", "", $valpath); if(substr($valpath,0,1)!="/") {$valpath="/".$valpath;} $query = ""; if (isset($val_parts['query'])) {$query = "?".$val_parts['query'];} if ($main_url_parts['port'] == 80 || $val_parts['port'] == "") {$portq = "";} else {$portq = ":".$main_url_parts['port'];} return $val; } function iframe_ce($val, $parent_url, $can_leave_domain) { global $ext, $mainurl, $apache_indexes, $strip_sessids; $valparts = parse_url($val); $main_url_parts = parse_url($mainurl); //if ($valparts['host'] != "" && $valparts['host'] != $main_url_parts['host'] && $can_leave_domain != 1) {return '';} reset($ext); while (list ($id, $excl) = each($ext)) if (preg_match("/\.$excl$/i", $val)) return ''; if (substr($val, -1) == '\\') {return '';} if (isset($valparts['query'])) {if ($apache_indexes[$valparts['query']]) {return '';}} if (preg_match("/[\/]?mailto:|[\/]?javascript:|[\/]?news:/i", $val)) {return '';} if (isset($valparts['scheme'])) {$scheme = $valparts['scheme'];} else {$scheme ="";} if (!($scheme == 'http' || $scheme == '' || $scheme == 'https')) {return '';} $regs = Array (); while (preg_match("/[^\/]*\/[.]{2}\//", $valpath, $regs)) { $valpath = str_replace($regs[0], "", $valpath); } $valpath = preg_replace("/\/+/", "/", $valpath); $valpath = preg_replace("/[^\/]*\/[.]{2}/", "", $valpath); $valpath = str_replace("./", "", $valpath); if(substr($valpath,0,1)!="/") {$valpath="/".$valpath;} $query = ""; if (isset($val_parts['query'])) {$query = "?".$val_parts['query'];} if ($main_url_parts['port'] == 80 || $val_parts['port'] == "") {$portq = "";} else {$portq = ":".$main_url_parts['port'];} return $val; } function _striplinks($document) { $match = array(); $links = array(); preg_match_all("'<\s*(a\s.*?href|[i]*frame\s.*?src)\s*=\s*([\'\"])?([+:%\/\?~=&\\\(\),._a-zA-Z0-9-]*)'isx",$document,$links,PREG_PATTERN_ORDER); foreach ($links[3] as $val) { if (($a = url_ce($val, $url, $can_leave_domain)) != '') { $match[] = $a; } $checked_urls[$val[1]] = 1; } return $match; } function _expandlinks($links,$URI) { preg_match("/^[^\?]+/",$URI,$match); $match = preg_replace("|/[^\/\.]+\.[^\/\.]+$|","",$match[0]); $match = preg_replace("|/$|","",$match); $match_part = parse_url($match); $match_root = $match_part["scheme"]."://".$match_part["host"]; $URI_PARTS = parse_url($URI); $host = $URI_PARTS["host"]; $search = array( "|^http://".preg_quote($host)."|i", "|^(\/)|i", "|^(?!http://)(?!mailto:)|i", "|/\./|", "|/[^\/]+/\.\./|" ); $replace = array( "", $match_root."/", $match."/", "/", "/" ); $expandedLinks = preg_replace($search,$replace,$links); return $expandedLinks; } function foothtml() { echo "<div style=\"text-align:center;\"><a target=\"_blank\" href=\"http://www.php.com\"> Php</a></div>"; } ?> ``` ```
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
小白学 Python 爬虫(25):爬取股票信息
人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Linux基础入门 小白学 Python 爬虫(4):前置准备(三)Docker基础入门 小白学 Python 爬虫(5):前置准备(四)数据库基础 小白学 Python 爬虫(6):前置准备(...
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
世界上最牛的网络设备,价格低廉,其貌不扬......
夜深人静,电视和电脑都已经关机休息,但是我还在默默工作,我安静地趴在你家中的某个地方,7*24小时不眠不休,任劳任怨,目的只有一个,能让你舒服地躺在床上,畅快地刷手机!没错,这就是我,...
《面试宝典》2019年springmvc面试高频题(java)
前言 2019即将过去,伴随我们即将迎来的又是新的一年,过完春节,马上又要迎来新的金三银四面试季。那么,作为程序猿的你,是否真的有所准备的呢,亦或是安于本职工作,继续做好手头上的事情。 当然,不论选择如何,假如你真的准备在之后的金三银四跳槽的话,那么作为一个Java工程师,就不可不看了。如何在几个月的时间里,快速的为即将到来的面试进行充分的准备呢? 1、什么是Spring MVC ?简单...
一名大专同学的四个问题
【前言】   收到一封来信,赶上各种事情拖了几日,利用今天要放下工作的时机,做个回复。   2020年到了,就以这一封信,作为开年标志吧。 【正文】   您好,我是一名现在有很多困惑的大二学生。有一些问题想要向您请教。   先说一下我的基本情况,高考失利,不想复读,来到广州一所大专读计算机应用技术专业。学校是偏艺术类的,计算机专业没有实验室更不用说工作室了。而且学校的学风也不好。但我很想在计算机领...
复习一周,京东+百度一面,不小心都拿了Offer
京东和百度一面都问了啥,面试官百般刁难,可惜我全会。
轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传。函数计算准备计算资源,并以弹性伸缩的方式运行用户代码,而用户只需根据实际代码运行所消耗的资源进行付费。Fun: Fun 是一个用于支持 Serverless 应用部署的工具,能帮助您便捷地管理函数计算、API ...
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试一个ArrayList我都能跟面试官扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
2020年1月中国编程语言排行榜,python是2019增长最快编程语言
编程语言比例 排名 编程语言 最低工资 工资中位数 最低工资 最高工资 人头 人头百分比 1 rust 20713 17500 5042 46250 480 0.14% 2 typescript 18503 22500 6000 30000 1821 0.52% 3 lua 18150 17500 5250 35000 2956 0.84% 4 go 17989 16...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
Idea 中最常用的10款插件(提高开发效率),一定要学会使用!
学习使用一些插件,可以提高开发效率。对于我们开发人员很有帮助。这篇博客介绍了开发中使用的插件。
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
工作十年的数据分析师被炒,没有方向,你根本躲不过中年危机
2020年刚刚开始,就意味着离职潮高峰的到来,我身边就有不少人拿着年终奖离职了,而最让我感到意外的,是一位工作十年的数据分析师也离职了,不同于别人的主动辞职,他是被公司炒掉的。 很多人都说数据分析是个好饭碗,工作不累薪资高、入门简单又好学。然而今年34的他,却真正尝到了中年危机的滋味,平时也有不少人都会私信问我: 数据分析师也有中年危机吗?跟程序员一样是吃青春饭的吗?该怎么保证自己不被公司淘汰...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
立即提问