码迷,mamicode.com
首页 > 数据库 > 详细

springJDBC学习笔记和实例

时间:2016-11-22 12:38:46      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:依赖注入   desc   map   schema   exception   tin   als   dba   ota   

前言:相对于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实例,如果有什么不妥或不正确的地方,欢迎指正。。。

springJDBC学习笔记和实例

标签:依赖注入   desc   map   schema   exception   tin   als   dba   ota   

原文地址:http://www.cnblogs.com/chafe/p/6088292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!