spring支持的dataSource有好多,
如:自带的org.springframework.jdbc.datasource.DriverManagerDataSource
ibatis、c3p0、JDBC、hibernate等等;
首先看第一种,使用自带的datasource:
1、项目结构
提示:spring的jar需要放在WEB-INF的lib目录下,只是放在项目的liberaries中会报错!原因:不同的类加载器加载类的时候寻找的是不同路径下的类。
2、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" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><!-- 编码过滤器 --><filter><filter-name>EncodeFilter</filter-name><filter-class>com.pt.filter.EncodeFileter</filter-class></filter><filter-mapping><filter-name>EncodeFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 用户管理servlet --><servlet><servlet-name>userManager</servlet-name><servlet-class>com.pt.UserManager</servlet-class></servlet><servlet-mapping><servlet-name>userManager</servlet-name><url-pattern>/user</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!-- 自动加载spring配置文件 --><context-param><!-- 配置文件路径 --><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener> </web-app>
3、spring的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beansxmlns="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-2.5.xsd"><!-- 配置数据源 --><bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://192.168.61.28:3306/test" /> <property name="username" value="encysys48" /> <property name="password" value="encysys48" /> </bean><bean id = "user" class = "com.pt.Users" scope="singleton"> </bean></beans>
4、spring的datasource的使用
package com.pt;import java.io.IOException; import java.sql.Connection; import java.sql.Statement;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource;import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader;public class UserManager extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stub doPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubresp.setCharacterEncoding("GBK");//获取spring上下文ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();DataSource ds = (DataSource)ctx.getBean("dataSource");Connection conn=null;Statement stmt = null;try{conn=ds.getConnection();stmt = conn.createStatement();if(conn!=null){resp.getWriter().write("获取connection成功");resp.getWriter().write("\n");}else{resp.getWriter().write("获取connection失败");resp.getWriter().write("\n");}String sql = "insert into users(id,name) values('2012001','陶伟基')";stmt.executeUpdate(sql);}catch(Exception ex){}finally{try{conn.close();stmt.close();}catch(Exception ex){}}resp.getWriter().write("测试成功");}}
5、过滤器
package com.pt.filter; import java.io.IOException;import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse;public class EncodeFileter implements Filter {public void destroy() {// TODO Auto-generated method stub }public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {// TODO Auto-generated method stubSystem.out.println("进入编码过滤器");arg0.setCharacterEncoding("UTF-8");arg2.doFilter(arg0, arg1);}public void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stub }}
其他文件可以不用写!
二、ibatis数据源
<?xml version="1.0" encoding="UTF-8"?> <beansxmlns="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-2.5.xsd"><!-- 配置数据源 --><bean id = "dataSource" name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://192.168.61.28:3306/test" /> <property name="username" value="encysys48" /> <property name="password" value="encysys48" /> </bean><bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"><!-- 注入ibatis的配置文件 --><property name="configLocations"><!-- 不加classpath:会出现错误 --><value>classpath:SqlMapConfig.xml</value></property><property name="dataSource"><!-- 此处填写ID --><ref local="dataSource"/></property></bean><bean id = "user" class = "com.pt.Users" scope="singleton"><property name="sqlMapClient" ref="sqlMapClient" /></bean></beans>
package com.pt;import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;public class Users extends SqlMapClientDaoSupport implements DataObjManager {private int id;private String name;private static Users users;public boolean add(Object obj) {// TODO Auto-generated method stubif(obj instanceof Users)getSqlMapClientTemplate().update("addUser", (Users)obj);elseSystem.out.println("输入类型错误!!!");return false;}public boolean deleteById(Object obj) {// TODO Auto-generated method stubreturn false;}public Object getById(Object obj) {// TODO Auto-generated method stubreturn null;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}}
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap><typeAlias alias = "user" type = "com.pt.Users" /><insert id="addUser" parameterClass="user">insert into users values(#id#,#name#)</insert> </sqlMap>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"> <sqlMapConfig><sqlMap resource="com/pt/xml/Users.xml" /> </sqlMapConfig>
package com.pt;import java.io.IOException; import java.sql.Connection; import java.sql.Statement;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource;import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoader;public class UserManager extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stub doPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubresp.setCharacterEncoding("GBK");//获取spring上下文ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();//注意,在这儿不可以自己new对象,必须由spring创建,这样ibatis才生效Users user = (Users)ctx.getBean("user");user.setId(20111907);user.setName("panteng");user.add(user);resp.getWriter().write("测试成功");}}
package com.pt;public interface DataObjManager {public boolean add(Object obj);public boolean deleteById(Object obj);public Object getById(Object obj); }