springJDBC学习笔记和实例

前言:相对于Mybatis(ibatis),个人感觉springJDBC更灵活,主要实现类JdbcTemplate;它替我们完成了资源的创建以及释放工作,从而简化了我们对JDBC的使用。它还可以帮助我们避免一些常见的错误,比如忘记关闭数据库连接。JdbcTemplate将完成JDBC核心处理流程,比如SQL语句的创建、执行,而把SQL语句的生成以及查询结果的提取工作留给我们的应用代码。它可以完成SQL查询、更新以及调用存储过程,可以对ResultSet进行遍历并加以提取。它还可以捕获JDBC异常并将其转换成org.springframework.dao包中定义的,通用的,信息更丰富的异常。

概述:

1)core
即核心包,它包含了JDBC的核心功能。此包内有很多重要的类,包括:JdbcTemplate类、SimpleJdbcInsert类,SimpleJdbcCall类,以及NamedParameterJdbcTemplate类。
2)datasource
即数据源包,访问数据源的实用工具类。它有多种数据源的实现,可以在JavaEE容器外部测试JDBC代码。
3)object
即对象包,以面向对象的方式访问数据库。它允许执行查询并返回结果作为业务对象。它可以在数据表的列和业务对象的属性之间映射查询结果。
4)support
即支持包,是core包和object包的支持类。例如提供了异常转换功能的SQLException类。

springJDBC完整实例:

工程结构:

结构说明:工程结构也不难理解,分为控制层(controller)、服务层(service)、持久层(dao),下面一步一步说明;

1.导入相关的springjdbcjar包,jar包一会分享到百度云盘,如果无法下载可以在评论留下邮箱我私发;

2.web配置文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5"
 3     xmlns="http://java.sun.com/xml/ns/javaee"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7   <display-name>springJDBCDemo</display-name>
 8   <welcome-file-list>
 9     <welcome-file>index.jsp</welcome-file>
10   </welcome-file-list>
11
12   <servlet>
13         <servlet-name>dispatcherServlet</servlet-name>
14         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
15         <init-param>
16             <param-name>contextConfigLocation</param-name>
17             <param-value>
18                 classpath:conf/spring.xml
19             </param-value>
20         </init-param>
21         <load-on-startup>1</load-on-startup>
22     </servlet>
23     <servlet-mapping>
24         <servlet-name>dispatcherServlet</servlet-name>
25         <url-pattern>/do/*</url-pattern>
26     </servlet-mapping>
27
28     <filter>
29         <filter-name>encodingFilter</filter-name>
30         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
31         <init-param>
32             <param-name>encoding</param-name>
33             <param-value>UTF-8</param-value>
34         </init-param>
35     </filter>
36     <filter-mapping>
37         <filter-name>encodingFilter</filter-name>
38         <url-pattern>/*</url-pattern>
39     </filter-mapping>
40 </web-app>

说明:<display-name>一般就写工程名了,<servlet>加载配置文件和请求路径配置;

3.spring.xml配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:util="http://www.springframework.org/schema/util"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 7             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
 8             http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 9             http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
10
11     <!-- 读取配置文件 -->
12     <bean id="propertyConfigurer" class="com.sf.springJDBC.base.http.CustomizedPropertyPlaceholderConfigurer">
13         <property name="locations">
14             <list>
15                 <value>classpath:conf/config.properties</value>
16             </list>
17         </property>
18     </bean>
19
20     <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
21     <context:component-scan base-package="com.sf.springJDBC" />
22        <!---该类设置后台编码为utf-8,如果没有该类可能导致jsp请求返回的数据中文显示为问号-->
23     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
24         <property name="messageConverters">
25             <list>
26                 <bean id="UTF8StringHttpMessageConverter" class="com.sf.springJDBC.base.UTF8StringHttpMessageConverter">
27                 </bean>
28             </list>
29         </property>
30     </bean>
31
32     <!-- 支持spring3.0新的mvc注解 -->
33     <mvc:annotation-driven/>
34
35     <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
36     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
37         <property name="cacheSeconds" value="0" />
38         <property name="messageConverters">
39             <list>
40                 <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
41             </list>
42         </property>
43     </bean>
44
45     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
46         <property name="maxUploadSize" value="102400000" />
47         <property name="resolveLazily" value="true"/>
48         <property name="maxInMemorySize" value="4096"/>
49     </bean>
50
51     <!-- 数据库配置-->
52     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
53         <property name="driverClassName" value="${dataSource.driver}" />
54         <property name="url" value="${dataSource.url}" />
55         <property name="username" value="${dataSource.username}" />
56         <property name="password" value="${dataSource.password}" />
57         <property name="initialSize" value="${dataSource.initialSize}" />
58         <property name="maxIdle" value="${dataSource.minIdle}" />
59         <property name="maxActive" value="${dataSource.maxActive}" />
60         <property name="maxWait" value="${dataSource.maxWait}" />
61         <property name="timeBetweenEvictionRunsMillis" value="${dataSource.timeBetweenEvictionRunsMillis}" />
62         <property name="minEvictableIdleTimeMillis" value="${dataSource.minEvictableIdleTimeMillis}" />
63         <property name="validationQuery" value="select 1 from dual" />
64         <property name="poolPreparedStatements" value="true" />
65         <property name="defaultAutoCommit" value="true" />
66     </bean>
67
68     <!-- 给jdbc模板注入数据源-->
69     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
70         <property name="dataSource" ref="dataSource"></property>
71     </bean>
72
73
74 </beans>

上面的注解说的很清楚了;

4.数据源配置文件config.properties:

 1 #oracle
 2 dataSource.driver=oracle.jdbc.driver.OracleDriver
 3
 4 #test 14-2
 5 dataSource.url=jdbc:oracle:thin:@ip:port:dbname
 6 dataSource.username=username
 7 dataSource.password=password
 8
 9 #Initialize connection
10 dataSource.initialSize=5
11 dataSource.minIdle=10
12 dataSource.maxActive=500
13 dataSource.maxWait=6000
14 dataSource.timeBetweenEvictionRunsMillis=3000
15 dataSource.minEvictableIdleTimeMillis=300000

5.工程主代码:

⑴控制层Controller

 1 package com.sf.springJDBC.controller;
 2
 3 import java.util.HashMap;
 4 import java.util.Map;
 5
 6 import javax.annotation.Resource;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9
10 import org.springframework.stereotype.Controller;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 import org.springframework.web.bind.annotation.ResponseBody;
13
14 import com.sf.springJDBC.base.BaseController;
15 import com.sf.springJDBC.service.TestService;
16
17
18 @Controller
19 @RequestMapping("/test")
20 public class TestController extends BaseController{
21     @Resource
22     private TestService testService;
23
24     @ResponseBody
25     @RequestMapping(value = "/gettest")
26     public String getTest(HttpServletRequest request, HttpServletResponse response) {
27         Map<String,Object> map = new HashMap<String, Object>();
28         map = testService.getTest();
29         String data = resMapToJson(map);
30         return data;
31     }
32 }

⑵服务层:service

1 package com.sf.springJDBC.service;
2
3 import java.util.Map;
4
5 public interface TestService {
6     public Map<String, Object> getTest();
7 }

(3)服务实现接口service.impl

package com.sf.springJDBC.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sf.springJDBC.dao.BaseDao;
import com.sf.springJDBC.dao.sql.TestSql;
import com.sf.springJDBC.service.TestService;

@Service()
public class TestServiceImpl implements TestService {

    @Autowired
    private BaseDao baseDao;
    public Map<String, Object> getTest() {
        Map<String,Object> map = new HashMap<String, Object>();
        String sql = TestSql.getQuestionsql;
        map = baseDao.selectOne(sql, null);
        return map;
    }

}

持久层dao

 1 package com.sf.springJDBC.dao;
 2
 3 import java.util.List;
 4 import java.util.Map;
 5
 6 public interface BaseDao {
 7
 8     public Map<String, Object> selectOne(String sql, Object[] params);
 9
10     public List<Map<String, Object>> selectList(String sql, Object[] params);
11
12     public int selectForInt(String sql, Object[] params);
13
14     public long selectForLong(String sql, Object[] params);
15
16     public int update(String sql, Object[] params);
17
18     public int executeBatch(String[] sql);
19
20     public int executeBatch(String sql, List<Object[]> objList);
21
22 }

(4)实现接口:dao.impl

  1 package com.sf.springJDBC.dao.impl;
  2
  3 import java.sql.PreparedStatement;
  4 import java.sql.SQLException;
  5 import java.sql.Timestamp;
  6 import java.util.ArrayList;
  7 import java.util.HashMap;
  8 import java.util.List;
  9 import java.util.Map;
 10 import org.springframework.beans.factory.annotation.Autowired;
 11 import org.springframework.dao.DataAccessException;
 12 import org.springframework.jdbc.core.JdbcTemplate;
 13 import org.springframework.jdbc.core.PreparedStatementCallback;
 14 import org.springframework.stereotype.Repository;
 15
 16 import com.sf.springJDBC.dao.BaseDao;
 17
 18
 19 @Repository
 20 public class BaseDaoImpl implements BaseDao {
 21
 22     @Autowired
 23     private JdbcTemplate jdbcTemplate;
 24
 25
 26     public Map<String, Object> selectOne(String sql, Object[] params) {
 27         Map<String, Object> result = new HashMap<String, Object>();
 28         try {
 29             List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, params);
 30             if (list.size() > 0) {
 31                 result = list.get(0);
 32             }
 33         } catch (Exception e) {
 34             e.printStackTrace();
 35         }
 36         return result;
 37     }
 38
 39
 40     public List<Map<String, Object>> selectList(String sql, Object[] params) {
 41         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
 42         try {
 43             list = jdbcTemplate.queryForList(sql, params);
 44         } catch (Exception e) {
 45             e.printStackTrace();
 46         }
 47         return list;
 48     }
 49
 50
 51     public int selectForInt(String sql, Object[] params) {
 52         int count = 0;
 53         try {
 54             count = jdbcTemplate.queryForInt(sql, params);
 55         } catch (Exception e) {
 56             e.printStackTrace();
 57         }
 58         return count;
 59     }
 60
 61
 62     public long selectForLong(String sql, Object[] params) {
 63         long count = 0l;
 64         try {
 65             count = jdbcTemplate.queryForLong(sql, params);
 66         } catch (Exception e) {
 67             e.printStackTrace();
 68         }
 69         return count;
 70     }
 71
 72
 73     public int update(String sql, Object[] params) {
 74         int count = 0;
 75         try {
 76             count = jdbcTemplate.update(sql, params);
 77         } catch (Exception e) {
 78             e.printStackTrace();
 79         }
 80         return count;
 81     }
 82
 83
 84     public int executeBatch(String[] sql) {
 85         int count = 0;
 86         try {
 87             count = jdbcTemplate.batchUpdate(sql).length;
 88         } catch (Exception e) {
 89             e.printStackTrace();
 90         }
 91         return count;
 92     }
 93
 94
 95
 96
 97     public int executeBatch(String sql, List<Object[]> objList) {
 98
 99     /*    Object[] objs = new Object[]{1,2,3};
100         objs = new Object[]{1,2,3};
101         objs = new Object[]{1,2,3};
102         objList.add(objs);*/
103
104         int count = 0;
105         final List<Object[]> paramList = objList;
106         try {
107             count = jdbcTemplate.execute(sql, new PreparedStatementCallback<int[]>() {
108
109                 public int[] doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
110                     ps.getConnection().setAutoCommit(false);
111                     for (int i = 0; i < paramList.size(); i++) {
112                         Object[] objs = paramList.get(i);
113                         for (int j = 0; j < objs.length; j++) {
114                             Object obj = objs[j];
115                             int num = j + 1;
116                             if (obj instanceof Integer) {
117                                 ps.setInt(num, (Integer) obj);
118                             } else if (obj instanceof Long) {
119                                 ps.setLong(num, (Long) obj);
120                             } else if (obj instanceof java.sql.Date) {
121                                 ps.setDate(num, (java.sql.Date)obj);
122                             } else if (obj instanceof Timestamp) {
123                                 ps.setTimestamp(num, (Timestamp) obj);
124                             } else if(obj instanceof Double){
125                                 ps.setDouble(num,(Double)obj);
126                             }
127                             else {
128
129                                 ps.setString(num, String.valueOf(obj));
130                             }
131                         }
132                         ps.addBatch();
133                     }
134                     int[] o = ps.executeBatch();
135                     ps.getConnection().commit();
136                     ps.getConnection().setAutoCommit(true);
137                     // 如果用<aop:config> 来控制事务,需要把上一行注掉,否则会报错
138                     return o;
139                 }
140             }).length;
141         } catch (Exception e) {
142             e.printStackTrace();
143         }
144         return count;
145     }
146
147 }

(5)sql语句单独写在一个类里面,方便管理:

1 package com.sf.springJDBC.dao.sql;
2
3 public class TestSql {
4     public static String getQuestionsql = "select * from bs_question_info where question_busi_id=‘ZJ16111000192‘" ;
5 }

当sql需要传参数时,参数用?传入,后台服务层传参数方式:baseDao.selectOne(sql, new Object[]{param1,param2});

(6)读取配置文件CustomizedPropertyPlaceholderConfigurer.java

 1 package com.sf.springJDBC.base.http;
 2
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 import java.util.Properties;
 6
 7 import org.springframework.beans.BeansException;
 8 import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
 9 import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
10
11 /*
12  * 读取配置文件
13  */
14 public class CustomizedPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
15
16     private static Map<String, Object> ctxPropertiesMap;
17
18     @Override
19     protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
20         super.processProperties(beanFactoryToProcess, props);
21         ctxPropertiesMap = new HashMap<String, Object>();
22         for (Object key : props.keySet()) {
23             String keyStr = key.toString();
24             String value = props.getProperty(keyStr);
25             ctxPropertiesMap.put(keyStr, value);
26         }
27     }
28
29     public static Object getContextProperty(String name) {
30         return ctxPropertiesMap.get(name);
31     }
32 }

(7)控制层继承的基础类:BaseController.java

  1 package com.sf.springJDBC.base;
  2
  3 import java.io.IOException;
  4 import java.io.StringReader;
  5 import java.util.HashMap;
  6 import java.util.List;
  7 import java.util.Map;
  8 import java.util.regex.Matcher;
  9 import java.util.regex.Pattern;
 10
 11 import javax.servlet.http.HttpServletRequest;
 12 import javax.xml.parsers.DocumentBuilder;
 13 import javax.xml.parsers.DocumentBuilderFactory;
 14 import javax.xml.parsers.ParserConfigurationException;
 15
 16 import org.codehaus.jackson.JsonParseException;
 17 import org.codehaus.jackson.map.JsonMappingException;
 18 import org.codehaus.jackson.map.ObjectMapper;
 19 import org.w3c.dom.Document;
 20 import org.w3c.dom.Node;
 21 import org.w3c.dom.NodeList;
 22 import org.xml.sax.InputSource;
 23 import org.xml.sax.SAXException;
 24
 25 import net.sf.json.JSONArray;
 26
 27 import com.alibaba.fastjson.JSON;
 28 import com.oncon.core.common.util.JsonUtils;
 29 import com.oncon.core.common.web.controller.SuperController;
 30
 31 public class BaseController extends SuperController {
 32     protected List<Map<String,Object>> list;
 33     protected Map<String, Object> result;
 34
 35     public BaseController() {
 36         // 初始化
 37         result = new HashMap<String, Object>();
 38         result.put("status", "1");
 39         result.put("desc", "失败");
 40     }
 41
 42     /**
 43      * 返回给前端json
 44      *
 45      * @param map
 46      * @return
 47      */
 48     protected String resMapToJson(Map<String, Object> map) {
 49         return JsonUtils.getObjectString(map);
 50     }
 51     protected String resMapToJson2(Map<String, String> map) {
 52         return JsonUtils.getObjectString(map);
 53     }
 54
 55     protected String resObjToJson(Object obj) {
 56         return JSONArray.fromObject(obj).toString();
 57     }
 58
 59     /**
 60      * 获取登录用户信息
 61      *
 62      * @param request
 63      * @return
 64      */
 65 //    protected UserInfoBean getUserInfo(HttpServletRequest request) {
 66 //        if (request.getSession().getAttribute("USERINFO") == null) {
 67 //            return null;
 68 //        }
 69 //        return (UserInfoBean) request.getSession().getAttribute("USERINFO");
 70 //    }
 71
 72     /**
 73      * 转化传入的json,示例:{"version":"1"}
 74      *
 75      * @param requestJson
 76      * @return
 77      */
 78     // @RequestBody String requestJson
 79     @SuppressWarnings("unchecked")
 80     protected Map<String, Object> resJsonToMap(String requestJson) {
 81         if (requestJson == null || "".equals(requestJson)) {
 82             return new HashMap<String, Object>();
 83         }
 84         return JsonUtils.toObject(requestJson, HashMap.class);
 85     }
 86
 87     /**
 88      * json转为map
 89      *
 90      * @param map
 91      * @param key
 92      * @return
 93      */
 94     protected String getMapToParamVal(Map<String, Object> map, String key) {
 95         String val = getStringValueFromMap(key, map);
 96         if (val == null) {
 97             return "";
 98         } else {
 99             return val.trim();
100         }
101     }
102     /**
103
104      * 调用JsonUtils jar包的方法 返回给前端json
105      *
106      * @param map
107      * @return
108      */
109     protected String resListToJson(List<Map<String, Object>> list) {
110         return JSON.toJSONString(list);
111     }
112     /**
113      * 获取url传入参数
114      *
115      * @param request
116      * @param key
117      * @return
118      */
119     protected String getResToParamVal(HttpServletRequest request, String key) {
120         String val = request.getParameter(key);
121         if (val == null) {
122             return "";
123         } else {
124             return val.trim();
125         }
126     }
127
128
129
130     /**
131      * Used to convert from JSON to XML or XML to JSON
132      */
133     protected ObjectMapper objectMapper = new ObjectMapper();
134
135     /**
136      * Judge the date type is XML or JSON
137      * @return
138      */
139     protected String analyseDataType(String strData) {
140         if (strData == null || strData.trim().length() <= 0) {
141             return "";
142         }
143
144         Pattern pattern = Pattern.compile("^<\\?xml.*");
145         Matcher matcher = pattern.matcher(strData);
146         boolean b = matcher.matches();
147         if (b) {
148             return "xml";
149         }
150
151         pattern = Pattern.compile("^\\{.\\}$");
152         matcher = pattern.matcher(strData);
153         b = matcher.matches();
154         if (b) {
155             return "json";
156         }
157         return "";
158     }
159     /**
160      * Get the request parameters, return map object
161      * @param strParam
162      * @return
163      */
164     @SuppressWarnings("unchecked")
165     protected Map<String, String> getParam(String strParam) {
166         Map<String, String> mapParam = null;
167
168         // Judge the date type is XML or JSON
169         String dataType = analyseDataType(strParam);
170
171         // XML
172         if ("xml".equalsIgnoreCase(dataType)) {
173             StringReader stringReader = new StringReader(strParam);
174             InputSource inputSource = new InputSource(stringReader);
175             Document doc = null;
176
177             try {
178                 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
179                 DocumentBuilder builder = factory.newDocumentBuilder();
180                 doc = builder.parse(inputSource);
181                 NodeList nodeList = doc.getElementsByTagName("ws:pin");
182                 if (nodeList == null || nodeList.getLength() <= 0) {
183                     return null;
184                 }
185
186                 Node node = nodeList.item(0);
187                 if (node == null) {
188                     return null;
189                 }
190
191                 //
192                 strParam = node.getFirstChild().getNodeValue();
193
194             } catch (ParserConfigurationException e) {
195                 e.printStackTrace();
196             } catch (SAXException e) {
197                 e.printStackTrace();
198             } catch (IOException e) {
199                 e.printStackTrace();
200             }
201         }
202
203         // JSON
204         try {
205             //System.out.println("strParam"+strParam);
206             mapParam = objectMapper.readValue(strParam, HashMap.class);
207             //System.out.println("mapParam"+mapParam);
208         } catch (JsonParseException e) {
209             e.printStackTrace();
210             //logger.error(e.getMessage());
211         } catch (JsonMappingException e) {
212             e.printStackTrace();
213             //logger.error(e.getMessage());
214         } catch (IOException e) {
215             e.printStackTrace();
216             //logger.error(e.getMessage());
217         } finally {
218             mapParam = mapParam != null ? mapParam : new HashMap<String, String>();
219         }
220
221         return mapParam;
222     }
223 }

(8)设置后台编码为utf-8,spring.xml配置文件需要加载该类,如果前台获取数据中文不是问号胡乱码,可以注释;

  1 package com.sf.springJDBC.base;
  2
  3 import java.io.IOException;
  4 import java.io.InputStreamReader;
  5 import java.io.OutputStreamWriter;
  6 import java.io.UnsupportedEncodingException;
  7 import java.nio.charset.Charset;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10
 11 import org.springframework.http.HttpInputMessage;
 12 import org.springframework.http.HttpOutputMessage;
 13 import org.springframework.http.MediaType;
 14 import org.springframework.http.converter.AbstractHttpMessageConverter;
 15 import org.springframework.http.converter.HttpMessageNotReadableException;
 16 import org.springframework.http.converter.HttpMessageNotWritableException;
 17 import org.springframework.util.FileCopyUtils;
 18
 19 public class UTF8StringHttpMessageConverter extends AbstractHttpMessageConverter<String> {
 20
 21
 22     public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
 23
 24     private final List<Charset> availableCharsets;
 25
 26     private boolean writeAcceptCharset = true;
 27
 28     public UTF8StringHttpMessageConverter() {
 29         super(new MediaType("text", "plain", DEFAULT_CHARSET), MediaType.ALL);
 30         this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
 31     }
 32
 33     /**
 34      * Indicates whether the {@code Accept-Charset} should be written to any
 35      * outgoing request.
 36      * <p>
 37      * Default is {@code true}.
 38      */
 39     public void setWriteAcceptCharset(boolean writeAcceptCharset) {
 40         this.writeAcceptCharset = writeAcceptCharset;
 41     }
 42
 43     @Override
 44     public boolean supports(Class<?> clazz) {
 45         return String.class.equals(clazz);
 46     }
 47
 48     @Override
 49     protected String readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException {
 50         Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
 51         return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));
 52     }
 53
 54     @Override
 55     protected Long getContentLength(String s, MediaType contentType) {
 56         Charset charset = getContentTypeCharset(contentType);
 57         try {
 58             return (long) s.getBytes(charset.name()).length;
 59         } catch (UnsupportedEncodingException ex) {
 60             // should not occur
 61             throw new InternalError(ex.getMessage());
 62         }
 63     }
 64
 65     @Override
 66     protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException {
 67         if (writeAcceptCharset) {
 68             outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
 69         }
 70         Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
 71         FileCopyUtils.copy(s, new OutputStreamWriter(outputMessage.getBody(), charset));
 72     }
 73
 74     /**
 75      * Return the list of supported {@link Charset}.
 76      *
 77      * <p>
 78      * By default, returns {@link Charset#availableCharsets()}. Can be
 79      * overridden in subclasses.
 80      *
 81      * @return the list of accepted charsets
 82      */
 83     protected List<Charset> getAcceptedCharsets() {
 84         return this.availableCharsets;
 85     }
 86
 87     private Charset getContentTypeCharset(MediaType contentType) {
 88         if (contentType != null && contentType.getCharSet() != null) {
 89             return contentType.getCharSet();
 90         } else {
 91             return DEFAULT_CHARSET;
 92         }
 93     }
 94
 95 /*    @Override
 96     protected String readInternal(Class<? extends String> arg0,
 97             HttpInputMessage arg1) throws IOException,
 98             HttpMessageNotReadableException {
 99         // TODO Auto-generated method stub
100         return null;
101     }
102
103     @Override
104     protected boolean supports(Class<?> arg0) {
105         // TODO Auto-generated method stub
106         return false;
107     }
108
109     @Override
110     protected void writeInternal(String arg0, HttpOutputMessage arg1)
111             throws IOException, HttpMessageNotWritableException {
112         // TODO Auto-generated method stub
113
114     }*/
115
116 }

5.部署到tomcat启动服务,请求后台数据地址:http://localhost:8080/工程名/do/test/gettest

6.总结:

这种方式获取数据都是存到map里面,很容易解析数据;穿参数也相当灵活,而且对参数类型随意定义;

以上是一个完整的springjdbc实例,如果有什么不妥或不正确的地方,欢迎指正。。。

时间: 2024-10-10 10:50:52

springJDBC学习笔记和实例的相关文章

Linux 程序设计学习笔记----文件管理实例应用

一.使用ls -l 以排序方式输出目录信息 1.需求以及知识点覆盖 ls -l 命令根据后面的参数将列出某文件即目录下的基本信息. 如果没有具体的目录或者文件,则列出当前目录下所有的非隐藏文件的信息,包括文件类型,文件权限,硬链接个数,拥有者.拥有者所在组,文件大小,文件更新时间等. such as : 若没有指定的文件,则输出所有目录下的文件信息: 所以,本应用要实现的基本功能和需要的知识点有: ①参数检查.包括参数个数检查,如果有多个需要列出信息的文件及目录,则遍历所有的参数,另外需要读取当

shell脚本交互:expect学习笔记及实例详解

最近项目需求,需要写一些shell脚本交互,管道不够用时,expect可以很好的实现脚本之间交互,搜索资料,发现网上好多文章都是转载的,觉得这篇文章还不错,所以简单修改之后拿过来和大家分享一下~ 1. expect是spawn: 后面加上需要执行的shell命令,比如说spawn sudo touch testfile 1.3 expect: 只有spawn执行的命令结果才会被expect捕捉到,因为spawn会启动一个进程,只有这个进程的相关信息才会被捕捉到,主要包括:标准输入的提示信息,Li

Android学习笔记——Handler实例

Handler的实质就是异步消息处理. 实例一: Handler的基本用法 XML布局代码: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientati

Objective-C学习笔记_实例变量可?度及方法

? 实例变量可?度 可见度 特点 public(公有的) 实例变量可以在类的外部和内部操作 protected(受保护的,默认的) 实例变量只能在本类和其?类内部操作 private(私有的) 实例对象只能在本类内访问 所谓的内部,指的是相应类的@implementation和@end之间. 示例代码如下: #import <Foundation/Foundation.h> @interface Person : NSObject { @public NSString *_hobby; /**

WPF(Windows10通用应用程序开发) 线性插值动画 or 帧动画学习笔记及实例

线性插值动画: [Storyboard]基本属性: TargetProperty:目标属性 TargetName:目标名称 From:指向属性的初始值:(可省略) To/By:(二选一) To:指向属性动画完成后的值:(可省略) By:指向属性初始值增加的值:(可省略) Duration:动画执行时间:格式:hh:mm:ss(如:0:0:1表示动画执行1s) AutoReverse:时间线(动画)达到Duration终点时是否倒退(true/false) RepeatBehavior:表示时间线

Eclipse插件开发 学习笔记 PDF 第一篇到第四篇 免分下载 开发基础 核心技术 高级进阶 综合实例

<<Eclipse插件开发 学习笔记>>,本书由浅入深.有重点.有针对性地介绍了Eclipse插件开发技术,全书分为4篇共24章.第一篇介绍Eclipse平台界面开发的基础知识.包含SWT控件的使用.界面布局.事件处理等内容:第二篇是插件开发核心技术,主要介绍插件开发的核心知识要点,包含行为(Action).视图(ViewPart).编辑器(Editor).透视图(Perspective)等10章的内容.第三篇主要讲述插件开发的高级内容,包含开发高级内容.富client平台技术(R

第十七篇:实例分析(3)--初探WDDM驱动学习笔记(十)

续: 还是记录一下, BltFuncs.cpp中的函数作用: CONVERT_32BPP_TO_16BPP 是将32bit的pixel转换成16bit的形式. 输入是DWORD 32位中, BYTE 0,1,2分别是RGB分量, 而BYTE3则是不用的 为了不减少color的范围, 所以,都是取RGB8,8,8的高RGB5, 6, 5位, 然后将这16位构成一个pixel. CONVERT_16BPP_TO_32BPP是将16bit的pixel转换成32bit的形式 输入是WORD 16BIT中

第十七篇:实例分析(4)--初探WDDM驱动学习笔记(十一)

感觉有必要把 KMDDOD_INITIALIZATION_DATA 中的这些函数指针的意思解释一下, 以便进一步的深入代码. DxgkDdiAddDevice 前面已经说过, 这个函数的主要内容是,将BASIC_DISPLAY_DRIVER实例指针存在context中, 以便后期使用, 支持多实例. DxgkDdiStartDevice 取得设备信息, 往注册表中加入内容, 从POST设备中获取FRAME BUFFER以及相关信息(DxgkCbAcquirePostDisplayOwnershi

angular学习笔记(五)-阶乘计算实例(1)

<!DOCTYPE html> <html ng-app> <head> <title>2.3.2计算阶乘实例1</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script src="script.js"></script> </