Spring学习心得(二)——日志和数据库
上一篇介绍了Spring的基本配置,本节介绍使用Spring生成日志和操作数据库的实战。
第一步,配置spring的log4j日志。
1.引入log4j所需要的jar包,在上一篇博客的附件中包含log4j-1.2.15.jar,如果还没有引入,直接拷贝到“WebRoot/WEB-INF/lib/”中即可。
2.配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>MySpring</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring*.xml</param-value> </context-param> <context-param> <param-name>webAppRootKey</param-name> <param-value>myProject.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/conf/log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>test</servlet-name> <servlet-class>servlet.TestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>test</servlet-name> <url-pattern>*.lzy</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
这一步的作用就是让spring帮忙照料下log4j的配置文件管理, 如果跳过第二步, 这里其实就和spring没什么关系,就是单独使用log4j了. (虽然后台还有将log4j交由spring容器接管之类的,我们不用关心了.)
3.写log4j的配置文件(本人是小白,在网上抄了一个)
在“WebRoot/WEB-INF/lib/”路径下建立conf文件夹,并新建log4j.properties文件
log4j.rootLogger= DEBUG, CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender #org.apache.log4j.HTMLLayout #org.apache.log4j.PatternLayout #org.apache.log4j.SimpleLayout #org.apache.log4j.TTCCLayout log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n #log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender #log4j.appender.FILE.layout = org.apache.log4j.PatternLayout #log4j.appender.FILE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] - %m%n #\u8FD9\u91CC\u7684${myProject.root}\u662F\u5728\u7B2C\u4E8C\u6B65\u4E2D\u914D\u7F6E\u51FA\u6765\u7684. \u4E5F\u53EF\u4EE5\u5199\u7EDD\u5BF9\u8DEF\u5F84 #log4j.appender.FILE.File=${myProject.root}/log/sqmslog.log #log4j.appender.FILE2 = org.apache.log4j.RollingFileAppender #log4j.appender.FILE2.MaxFileSize = 500KB log4j.logger.org.springframework=WARN log4j.logger.test=DEBUG
第二部,spring操作数据库数据库。
1.把Spring操作数据库依赖的一些jar包导入,需要的jar包有asm、beans、context、core、expression、web、jdbc、transaction、dbcp、pool上一篇文章附件中有所需要的大部分jar包,本文附件中补全了需要的所有jar包,可以根据需要选择合适的版本使用。
2.编辑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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="TestBo" class="servlet.TestBo"> <property name="name" value="123"></property> <property name="dataSource" ref="dataSource" /> </bean> <bean id="TestAction" class="servlet.TestAction"> <property name="name" value="abc"></property> <property name="testbo" ref="TestBo"></property> </bean> <!-- 数据库设置 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" value="/WEB-INF/conf/jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> </beans>
这里使用的是将数据库信息写在文件jdbc.properties里, 你也可以将信息直接写在dataSource的bean属性里(将第一个bean去掉),
3.在“WebRoot/WEB-INF/lib/conf”文件夹下建立jdbc.properties文件。
jdbc.driverClassName=org.gjt.mm.mysql.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true jdbc.username=root jdbc.password=***
第三部,测试。
TestServlet.java
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; /** * Servlet implementation class TestServlet */ @WebServlet("/TestServlet") public class TestServlet extends HttpServlet { private static final long serialVersionUID = 1L; TestAction ta; /** * @see HttpServlet#HttpServlet() */ public TestServlet() { super(); // TODO Auto-generated constructor stub } /** * service * @throws IOException */ public void service(HttpServletRequest request,HttpServletResponse response) throws IOException{ PrintWriter pw=response.getWriter(); pw.write(ta.getTestbo().getName()); pw.flush(); pw.close(); } public void init(ServletConfig servletConfig) throws ServletException{ servletConfig.getServletContext(); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext()); this.ta = (TestAction) ctx.getBean("TestAction"); this.ta.sayHello(); System.out.println("TestServlet init"); // TestAction ta = new TestAction(); // ta.sayHello(); } }
TestBo.java
package servlet; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; public class TestBo { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private JdbcTemplate jdbcTemplate; private DataSource dataSource; public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); System.out.println(jdbcTemplate+"----"); } public int getindex() { int countOfActorsNamedJoe = this.jdbcTemplate.queryForInt( "select count(*) from help_topic"); return countOfActorsNamedJoe; } }
TestAction.java
package servlet; public class TestAction { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private TestBo testbo; public void sayHello() { // TODO Auto-generated method stub System.out.println(name+" "+testbo.getindex()); } public TestBo getTestbo() { return testbo; } public void setTestbo(TestBo testbo) { this.testbo = testbo; } }
后记,本人在操作数据库时碰到一个莫名其妙的问题:
严重: StandardWrapper.Throwable java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z at org.apache.commons.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:914) at org.apache.commons.dbcp2.PoolableConnection.validate(PoolableConnection.java:283) at org.apache.commons.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:357) at org.apache.commons.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2304) at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2287) at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2038) at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533) at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:382) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:456) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:464) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:472) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:477) at org.springframework.jdbc.core.JdbcTemplate.queryForInt(JdbcTemplate.java:486) at servlet.TestBo.getindex(TestBo.java:33) at servlet.TestAction.sayHello(TestAction.java:18) at servlet.TestServlet.init(TestServlet.java:48) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:817) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1527) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1484) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)
这是因为mysql-connector-java-5.0.5-bin.jar版本和dbpc版本不匹配,我把mysql-connector-java-5.0.5-bin.jar换成了mysql-connector-java-5.1.26-bin.jar就解决了。