一:代码结构
二:框架结果:
spring+springMvc+springJdbc
三:源代码
1:Ctrl 层
package com.todaytech.yth.gdsd.base.DataInfo.Controller;import java.io.IOException;import java.util.List;import javax.annotation.Resource;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.todaytech.yth.gdsd.base.DataInfo.Model.ZbInfoVo;import com.todaytech.yth.gdsd.base.DataInfo.Service.LoginInfoCheckService;import com.todaytech.yth.gdsd.base.DataInfo.Service.ZbInfoService;import com.todaytech.yth.gdsd.base.DataInfo.Util.GetIPUtil;import com.todaytech.yth.gdsd.base.DataInfo.Util.JasonUtil;import com.todaytech.yth.gdsd.base.DataInfo.Util.JsonResult;import com.todaytech.yth.gdsd.base.DataInfo.Util.StatusCode;import com.tt.pwp.framework.prefs.PrefsManager;/** * 信息化接口:指标信息 * @author admin * */@SuppressWarnings("unused")@Controller@RequestMapping("/DataInfor")public class ZbInfoCtrl { @Resource private PrefsManager prefsManager; private ZbInfoService zbis; private LoginInfoCheckService loginCheck; public ZbInfoService getZbis() { return zbis; } public void setZbis(ZbInfoService zbis) { this.zbis = zbis; } public LoginInfoCheckService getLoginCheck() { return loginCheck; } public void setLoginCheck(LoginInfoCheckService loginCheck) { this.loginCheck = loginCheck; } /** * 测试调用地址:http://localhost:8081/gdsd-all/DataInfor/zbInfo.do?login_unitno=0001&login_name=MDAwMQ==&login_pass=MTIzNDU2 * 一个正常的服务调用接口 * 返回有状态位的jason串 * @param request * @param response * @return * @throws IOException * @throws ServletException */ @RequestMapping( value = "/zbInfo.do",produces = "application/json;charset=UTF-8") @ResponseBody public JsonResult queryZbInfo(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{ Object data = null; //获取入参 String login_unitno = request.getParameter("login_unitno");//接口接入单位编码 String login_name = request.getParameter("login_name");//接口登录用户信息 String login_pass = request.getParameter("login_pass");//接口登录密码 String ip=GetIPUtil.getIP(request);//获取请求用户的ip信息 //做登录信息的校验 int flag=loginCheck.checkUserInfo(login_unitno,login_name,login_pass,ip); //获取返回信息 String message= StatusCode.returnMessage(flag); try { //如果登录信息正常,则通过接口文档的入参信息查询返回的结果信息 if(flag==200){ ListzivList = zbis.query( ); //无查询条件的查询数据 //查询的结果信息 Jason序列化转换 data= JasonUtil.serialize(zivList); //实现 jason 对象 JsonResult jr = new JsonResult(flag, message,data ); //返回jason 对象 return jr; }else{ return new JsonResult(flag,message, data); } } catch (Exception e) { e.printStackTrace(); return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(), data); } } /** * 返回一个jason串 * @param request * @param response * @throws IOException * @throws ServletException */ @RequestMapping( value = "/zbInfotest.do",produces = "application/json;charset=UTF-8") @ResponseBody public void queryZbInfoTest(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{ RequestDispatcher rd; try { List zivList = zbis.query( ); // response.setContentType("application/json; charset=UTF-8"); response.getWriter().print(JasonUtil.serialize(zivList)); } catch (Exception e) { e.printStackTrace(); } }}
2:Model 层
package com.todaytech.yth.gdsd.base.DataInfo.Model;import java.math.BigDecimal;import java.sql.Date;/** * 信息化接口:指标信息 * @author admin * */public class ZbInfoVo { private long id ;//指标账id private String bdgyear ;//年度 private long unitid ;//单位id private String src_id ;//资金来源 private String bdgt_id_type ;//功能科目类型id private long budgetid ;//功能分类科目id private long prj_id ;//项目id private long item_id ;//经济分类科目id private BigDecimal zb_amt ;//总指标 private BigDecimal direct_amt ;//直接支付指标 private BigDecimal accredit_amt ;//授权支付指标 private BigDecimal direct_plan ;//已报用款计划直接支付金额 private BigDecimal accredit_plan ;//已报用款计划授权支付金额 private String tradition_amt ;//一般支付指标 private int org_id ;//负责科室关联pwp_org private String adjlevel ;//预算级次(0本级1上级) private String yearbal_status ;//是否已生成结转(0否;1是) private String zb_project_type ;//项目类型(取项目预算的项目类型字段值) private String is_heding ;//是否结转(0否;1是) private BigDecimal early_amt ;//年初指标 private BigDecimal early_change_amt ;//年初变动指标 private BigDecimal additional_amt ;//追加变动指标 private BigDecimal tradition_num ;//一般支付发生数 private String fundtype ;//经费类型(1人员经费2公用经费3项目经费4区统筹经费5镇街经费) private int issue_num ;//下达次数 private String bz ;//备注 private String is_unify ;//是否统发工资(0否;1是) private String is_freeze ;//是否冻结(0不冻结;1冻结) private String origin_id ;//经费来源id(对应ys_ryjfyssb_detail、ys_gyjfysgl_detail、ys_xmyssqb_detail的id) private String entire_manage ;//封套管理(0封套内,1封套外) private String send_status ;//发送状态(0待确认,1待发送,2已发送) private String unitno ;//单位编码(bs_bdg_unit) private String budgetno ;//功能分类科目编码 private String itemno ;//经济分类代码(bs_jjflyskm:econ_bdgid) private String prj_code ;//项目代码(bs_xmk :prj_code) private String freeze_reason ;//冻结原因 private long freeze_account ;//冻结人 private String freeze_time ;//冻结时间 private String unfreeze_account ;//解冻人 private Date unfreeze_time ;//解冻时间 private Date create_Date ;//指标下达时间 private long source_zb_id ;//(被结转的)源指标 private int yearbal_no ;//指标结转次数 private String is_toback ;//是否收回(0否;1是) private Date toback_Date ;//收回时间 private String zb_issuedtype ;//指标下达类型(0:年初预算下达1:调整预算下达2:年终指标结转下达3:跨年部分退款) private BigDecimal toback_amt ;//年终回收指标 public long getId() { return id; } public void setId(long id) { this.id = id; } public String getBdgyear() { return bdgyear; } public void setBdgyear(String bdgyear) { this.bdgyear = bdgyear; } public long getUnitid() { return unitid; } public void setUnitid(long unitid) { this.unitid = unitid; } public String getSrc_id() { return src_id; } public void setSrc_id(String src_id) { this.src_id = src_id; } public String getBdgt_id_type() { return bdgt_id_type; } public void setBdgt_id_type(String bdgt_id_type) { this.bdgt_id_type = bdgt_id_type; } public long getBudgetid() { return budgetid; } public void setBudgetid(long budgetid) { this.budgetid = budgetid; } public long getPrj_id() { return prj_id; } public void setPrj_id(long prj_id) { this.prj_id = prj_id; } public long getItem_id() { return item_id; } public void setItem_id(long item_id) { this.item_id = item_id; } public BigDecimal getZb_amt() { return zb_amt; } public void setZb_amt(BigDecimal zb_amt) { this.zb_amt = zb_amt; } public BigDecimal getDirect_amt() { return direct_amt; } public void setDirect_amt(BigDecimal direct_amt) { this.direct_amt = direct_amt; } public BigDecimal getAccredit_amt() { return accredit_amt; } public void setAccredit_amt(BigDecimal accredit_amt) { this.accredit_amt = accredit_amt; } public BigDecimal getDirect_plan() { return direct_plan; } public void setDirect_plan(BigDecimal direct_plan) { this.direct_plan = direct_plan; } public BigDecimal getAccredit_plan() { return accredit_plan; } public void setAccredit_plan(BigDecimal accredit_plan) { this.accredit_plan = accredit_plan; } public String getTradition_amt() { return tradition_amt; } public void setTradition_amt(String tradition_amt) { this.tradition_amt = tradition_amt; } public int getOrg_id() { return org_id; } public void setOrg_id(int org_id) { this.org_id = org_id; } public String getAdjlevel() { return adjlevel; } public void setAdjlevel(String adjlevel) { this.adjlevel = adjlevel; } public String getYearbal_status() { return yearbal_status; } public void setYearbal_status(String yearbal_status) { this.yearbal_status = yearbal_status; } public String getZb_project_type() { return zb_project_type; } public void setZb_project_type(String zb_project_type) { this.zb_project_type = zb_project_type; } public String getIs_heding() { return is_heding; } public void setIs_heding(String is_heding) { this.is_heding = is_heding; } public BigDecimal getEarly_amt() { return early_amt; } public void setEarly_amt(BigDecimal early_amt) { this.early_amt = early_amt; } public BigDecimal getEarly_change_amt() { return early_change_amt; } public void setEarly_change_amt(BigDecimal early_change_amt) { this.early_change_amt = early_change_amt; } public BigDecimal getAdditional_amt() { return additional_amt; } public void setAdditional_amt(BigDecimal additional_amt) { this.additional_amt = additional_amt; } public BigDecimal getTradition_num() { return tradition_num; } public void setTradition_num(BigDecimal tradition_num) { this.tradition_num = tradition_num; } public String getFundtype() { return fundtype; } public void setFundtype(String fundtype) { this.fundtype = fundtype; } public int getIssue_num() { return issue_num; } public void setIssue_num(int issue_num) { this.issue_num = issue_num; } public String getBz() { return bz; } public void setBz(String bz) { this.bz = bz; } public String getIs_unify() { return is_unify; } public void setIs_unify(String is_unify) { this.is_unify = is_unify; } public String getIs_freeze() { return is_freeze; } public void setIs_freeze(String is_freeze) { this.is_freeze = is_freeze; } public String getOrigin_id() { return origin_id; } public void setOrigin_id(String origin_id) { this.origin_id = origin_id; } public String getEntire_manage() { return entire_manage; } public void setEntire_manage(String entire_manage) { this.entire_manage = entire_manage; } public String getSend_status() { return send_status; } public void setSend_status(String send_status) { this.send_status = send_status; } public String getUnitno() { return unitno; } public void setUnitno(String unitno) { this.unitno = unitno; } public String getBudgetno() { return budgetno; } public void setBudgetno(String budgetno) { this.budgetno = budgetno; } public String getItemno() { return itemno; } public void setItemno(String itemno) { this.itemno = itemno; } public String getPrj_code() { return prj_code; } public void setPrj_code(String prj_code) { this.prj_code = prj_code; } public String getFreeze_reason() { return freeze_reason; } public void setFreeze_reason(String freeze_reason) { this.freeze_reason = freeze_reason; } public long getFreeze_account() { return freeze_account; } public void setFreeze_account(long freeze_account) { this.freeze_account = freeze_account; } public String getFreeze_time() { return freeze_time; } public void setFreeze_time(String freeze_time) { this.freeze_time = freeze_time; } public String getUnfreeze_account() { return unfreeze_account; } public void setUnfreeze_account(String unfreeze_account) { this.unfreeze_account = unfreeze_account; } public Date getUnfreeze_time() { return unfreeze_time; } public void setUnfreeze_time(Date unfreeze_time) { this.unfreeze_time = unfreeze_time; } public Date getCreate_Date() { return create_Date; } public void setCreate_Date(Date create_Date) { this.create_Date = create_Date; } public long getSource_zb_id() { return source_zb_id; } public void setSource_zb_id(long source_zb_id) { this.source_zb_id = source_zb_id; } public int getYearbal_no() { return yearbal_no; } public void setYearbal_no(int yearbal_no) { this.yearbal_no = yearbal_no; } public String getIs_toback() { return is_toback; } public void setIs_toback(String is_toback) { this.is_toback = is_toback; } public Date getToback_Date() { return toback_Date; } public void setToback_Date(Date toback_Date) { this.toback_Date = toback_Date; } public String getZb_issuedtype() { return zb_issuedtype; } public void setZb_issuedtype(String zb_issuedtype) { this.zb_issuedtype = zb_issuedtype; } public BigDecimal getToback_amt() { return toback_amt; } public void setToback_amt(BigDecimal toback_amt) { this.toback_amt = toback_amt; } @Override public String toString() { return "ZbInfoVo [id=" + id + ", bdgyear=" + bdgyear + ", unitid=" + unitid + ", src_id=" + src_id + ", bdgt_id_type=" + bdgt_id_type + ", budgetid=" + budgetid + ", prj_id=" + prj_id + ", item_id=" + item_id + ", zb_amt=" + zb_amt + ", direct_amt=" + direct_amt + ", accredit_amt=" + accredit_amt + ", direct_plan=" + direct_plan + ", accredit_plan=" + accredit_plan + ", tradition_amt=" + tradition_amt + ", org_id=" + org_id + ", adjlevel=" + adjlevel + ", yearbal_status=" + yearbal_status + ", zb_project_type=" + zb_project_type + ", is_heding=" + is_heding + ", early_amt=" + early_amt + ", early_change_amt=" + early_change_amt + ", additional_amt=" + additional_amt + ", tradition_num=" + tradition_num + ", fundtype=" + fundtype + ", issue_num=" + issue_num + ", bz=" + bz + ", is_unify=" + is_unify + ", is_freeze=" + is_freeze + ", origin_id=" + origin_id + ", entire_manage=" + entire_manage + ", send_status=" + send_status + ", unitno=" + unitno + ", budgetno=" + budgetno + ", itemno=" + itemno + ", prj_code=" + prj_code + ", freeze_reason=" + freeze_reason + ", freeze_account=" + freeze_account + ", freeze_time=" + freeze_time + ", unfreeze_account=" + unfreeze_account + ", unfreeze_time=" + unfreeze_time + ", create_Date=" + create_Date + ", source_zb_id=" + source_zb_id + ", yearbal_no=" + yearbal_no + ", is_toback=" + is_toback + ", toback_Date=" + toback_Date + ", zb_issuedtype=" + zb_issuedtype + ", toback_amt=" + toback_amt + "]"; }}package com.todaytech.yth.gdsd.base.DataInfo.Model;/** * 单位信息 * @author admin * */public class DataInfoUnitInfoVo { private String unitno; //单位编码 private String login_name; //单位登录信息 private String login_pass;//单位校验密码 private String login_ipinfo ;//单位发送请求的ip信息 public String getUnitno() { return unitno; } public void setUnitno(String unitno) { this.unitno = unitno; } public String getLogin_name() { return login_name; } public void setLogin_name(String login_name) { this.login_name = login_name; } public String getLogin_pass() { return login_pass; } public void setLogin_pass(String login_pass) { this.login_pass = login_pass; } public String getLogin_ipinfo() { return login_ipinfo; } public void setLogin_ipinfo(String login_ipinfo) { this.login_ipinfo = login_ipinfo; } @Override public String toString() { return "DataInfoUnitInfoVo [unitno=" + unitno + ", login_name=" + login_name + ", login_pass=" + login_pass + ", login_ipinfo=" + login_ipinfo + "]"; }}
3:RowMap 数据逻辑处理层
package com.todaytech.yth.gdsd.base.DataInfo.RowMap;import java.lang.reflect.Field;import java.math.BigDecimal;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.sql.Timestamp;import java.util.Date;import java.util.HashMap;import org.springframework.jdbc.core.RowMapper;/* * 文件名:LocalRowMapper.java * 版权:Copyright 2007-2017 517na Tech. Co. Ltd. All Rights Reserved. * 描述: LocalRowMapper.java * 修改人:xiaofan * 修改时间:2017年3月19日 * 修改内容:新增 */public class LocalRowMapperimplements RowMapper { /** * 添加字段注释. */ private Class targetClazz; /** * 添加字段注释. */ private HashMap fieldMap; /** * 构造函数. * * @param targetClazz * . */ public LocalRowMapper(Class targetClazz) { this.targetClazz = targetClazz; fieldMap = new HashMap<>(); Field[] fields = targetClazz.getDeclaredFields(); for (Field field : fields) { // 同时存入大小写,如果表中列名区分大小写且有列ID和列iD,则会出现异常。 // 阿里开发公约,建议表名、字段名必须使用小写字母或数字;禁止出现数字开头,禁止两个下划线中间只出现数字。 fieldMap.put(field.getName(), field); // fieldMap.put(getFieldNameUpper(field.getName()), field); } } /** * {@inheritDoc}. */ @SuppressWarnings("unchecked") @Override public T mapRow(ResultSet rs, int arg1) throws SQLException { T obj = null; try { obj = (T) targetClazz.newInstance(); final ResultSetMetaData metaData = rs.getMetaData(); int columnLength = metaData.getColumnCount(); String columnName = null; for (int i = 1; i <= columnLength; i++) { columnName = metaData.getColumnName(i); if(fieldMap.get(columnName.toLowerCase())!=null){ //刘军20190318修改 Field field = fieldMap.get(columnName.toLowerCase()); Class fieldClazz = fieldMap.get(columnName.toLowerCase()).getType() ; field.setAccessible(true); // fieldClazz == Character.class || fieldClazz == char.class if (fieldClazz == int.class || fieldClazz == Integer.class) { // int field.set(obj, rs.getInt(columnName)); } else if (fieldClazz == boolean.class || fieldClazz == Boolean.class) { // boolean field.set(obj, rs.getBoolean(columnName)); } else if (fieldClazz == String.class) { // string field.set(obj, rs.getString(columnName)); } else if (fieldClazz == float.class) { // float field.set(obj, rs.getFloat(columnName)); } else if (fieldClazz == double.class || fieldClazz == Double.class) { // double field.set(obj, rs.getDouble(columnName)); } else if (fieldClazz == BigDecimal.class) { // bigdecimal field.set(obj, rs.getBigDecimal(columnName)); } else if (fieldClazz == short.class || fieldClazz == Short.class) { // short field.set(obj, rs.getShort(columnName)); } else if (fieldClazz == Date.class) { // date field.set(obj, rs.getDate(columnName)); } else if (fieldClazz == Timestamp.class) { // timestamp field.set(obj, rs.getTimestamp(columnName)); } else if (fieldClazz == Long.class || fieldClazz == long.class) { // long field.set(obj, rs.getLong(columnName)); } field.setAccessible(false); } } } catch (Exception e) { e.printStackTrace(); } return obj; } /** * 方法首字母大写. * * @param fieldName * 字段名. * @return 字段名首字母大写. */ private String getFieldNameUpper(String fieldName) { char[] cs = fieldName.toCharArray(); cs[0] -= 32; // 方法首字母大写 return String.valueOf(cs); }}
4:Service 服务层
package com.todaytech.yth.gdsd.base.DataInfo.Service;import java.util.List;import com.todaytech.yth.gdsd.base.DataInfo.Model.ZbInfoVo;/** * 信息化接口:指标信息 * @author admin * */public interface ZbInfoService { Listquery();} package com.todaytech.yth.gdsd.base.DataInfo.Service;/** * 数据信息化接口登录校验 * @author admin * */public interface LoginInfoCheckService { /** * 数据信息化接口登录校验 * @param login_unitno * @param login_name * @param login_pass * @param ip * @return */ public int checkUserInfo (String login_unitno, String login_name, String login_pass, String ip);}package com.todaytech.yth.gdsd.base.DataInfo.Service.imp;import java.util.List;import javax.annotation.Resource;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.todaytech.yth.gdsd.base.DataInfo.Model.ZbInfoVo;import com.todaytech.yth.gdsd.base.DataInfo.RowMap.LocalRowMapper;import com.todaytech.yth.gdsd.base.DataInfo.Service.ZbInfoService;import com.tt.pwp.framework.data.dao.Dao;/** * 信息化接口:指标信息 * @author admin * */@Service@Transactionalpublic class ZbInfoServiceImp implements ZbInfoService { @Resource private Dao defaultDao; @SuppressWarnings("unchecked") @Override public Listquery() { String sql="select * from zb_bal z where z.BDGYEAR=to_char(sysdate,'yyyy')"; JdbcTemplate jdbcTemplate=defaultDao.getJdbcTemplate(); List zivList = jdbcTemplate.query(sql, new LocalRowMapper(ZbInfoVo.class)) ; return zivList ; }} package com.todaytech.yth.gdsd.base.DataInfo.Model;/** * 单位信息 * @author admin * */public class DataInfoUnitInfoVo { private String unitno; //单位编码 private String login_name; //单位登录信息 private String login_pass;//单位校验密码 private String login_ipinfo ;//单位发送请求的ip信息 public String getUnitno() { return unitno; } public void setUnitno(String unitno) { this.unitno = unitno; } public String getLogin_name() { return login_name; } public void setLogin_name(String login_name) { this.login_name = login_name; } public String getLogin_pass() { return login_pass; } public void setLogin_pass(String login_pass) { this.login_pass = login_pass; } public String getLogin_ipinfo() { return login_ipinfo; } public void setLogin_ipinfo(String login_ipinfo) { this.login_ipinfo = login_ipinfo; } @Override public String toString() { return "DataInfoUnitInfoVo [unitno=" + unitno + ", login_name=" + login_name + ", login_pass=" + login_pass + ", login_ipinfo=" + login_ipinfo + "]"; }}
5:工具类层
package com.todaytech.yth.gdsd.base.DataInfo.Util;import java.io.UnsupportedEncodingException;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;/** * * BASE64加密解密 * * @author YUANWEi */@SuppressWarnings("restriction")public class BASE64Util { /** * BASE64解密 * @param key * @return * @throws Exception */ public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } /** * BASE64加密 * @param key * @return * @throws Exception */ public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); } // 加密 public static String getBase64(String str) { byte[] b = null; String s = null; try { b = str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (b != null) { s = new BASE64Encoder().encode(b); } return s; } // 解密 public static String getFromBase64(String s) { byte[] b = null; String result = null; if (s != null) { BASE64Decoder decoder = new BASE64Decoder(); try { b = decoder.decodeBuffer(s); result = new String(b, "utf-8"); } catch (Exception e) { e.printStackTrace(); } } return result; } public static void main(String[] args) { String key="1234567890qwertyuiopasdfghjklzxcvbnm"; System.out.println(getFromBase64(getBase64(key))); System.out.println(getBase64("0001")); }}package com.todaytech.yth.gdsd.base.DataInfo.Util;import javax.servlet.http.HttpServletRequest;/** * 获取ip访客的ip信息 * @author admin * */public class GetIPUtil { public static String getIP(HttpServletRequest request){ String ip = request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); /* if(ip.equals("127.0.0.1")){ //根据网卡取本机配置的IP InetAddress inet=null; try { inet = InetAddress.getLocalHost(); } catch (Exception e) { e.printStackTrace(); } ip= inet.getHostAddress(); } */ } // 多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 if(ip != null && ip.length() > 15){ if(ip.indexOf(",")>0){ ip = ip.substring(0,ip.indexOf(",")); } } return ip; }}package com.todaytech.yth.gdsd.base.DataInfo.Util;import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardOpenOption;import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletRequest;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import com.alibaba.fastjson.JSON;/** * * @author admin * */public class JasonUtil { private static final String DEFAULT_CHARSET_NAME = "UTF-8"; // 获得请求的报文,并作简单的校验 public String getInJson(HttpServletRequest request) throws IOException { byte buffer[] = new byte[64 * 1024]; InputStream in = request.getInputStream();// 获取输入流对象 int len = in.read(buffer); // 必须对数组长度进行判断,否则在new byte[len]会报NegativeArraySizeException异常 if (len < 0) { throw new IOException("请求报文为空"); } String encode = request.getCharacterEncoding();// 获取请求头编码 // 必须对编码进行校验,否则在new String(data, encode);会报空指针异常 if (null == encode || encode.trim().length() < 0) { throw new IOException("请求报文未指明请求编码"); } byte data[] = new byte[len]; // 把buffer数组的值复制到data数组 System.arraycopy(buffer, 0, data, 0, len); // 通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String String inJson = new String(data, encode); return inJson; } public String Object2Json(Object obj) { JSONObject json = JSONObject.fromObject(obj);// 将java对象转换为json对象 String str = json.toString();// 将json对象转换为字符串 return str; } /** * List集合转换成JSON对象 * @author admin * */ public staticString serialize(T object) { return JSON.toJSONString(object); } public static T deserialize(String string, Class clz) { return JSON.parseObject(string, clz); } public static T load(Path path, Class clz) throws IOException { return deserialize(new String(Files.readAllBytes(path),DEFAULT_CHARSET_NAME), clz); } public static void save(Path path, T object) throws IOException { if (Files.notExists(path.getParent())) { Files.createDirectories(path.getParent()); } Files.write(path, serialize(object).getBytes(DEFAULT_CHARSET_NAME), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } /*** * 将List对象序列化为JSON文本 */ public static String toJSONString(List list) { JSONArray jsonArray = JSONArray.fromObject(list); return jsonArray.toString(); } /*** * 将对象序列化为JSON文本 * * @param object * @return */ public static String toJSONString(Object object) { JSONArray jsonArray = JSONArray.fromObject(object); return jsonArray.toString(); } /*** * 将JSON对象数组序列化为JSON文本 * * @param jsonArray * @return */ public static String toJSONString(JSONArray jsonArray) { return jsonArray.toString(); } /*** * 将JSON对象序列化为JSON文本 * * @param jsonObject * @return */ public static String toJSONString(JSONObject jsonObject) { return jsonObject.toString(); } /*** * 将对象转换为List对象 * * @param object * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static List toArrayList(Object object) { List arrayList = new ArrayList(); JSONArray jsonArray = JSONArray.fromObject(object); Iterator it = jsonArray.iterator(); while (it.hasNext()) { JSONObject jsonObject = (JSONObject) it.next(); Iterator keys = jsonObject.keys(); while (keys.hasNext()) { Object key = keys.next(); Object value = jsonObject.get(key); arrayList.add(value); } } return arrayList; } /*** * 将对象转换为Collection对象 * * @param object * @return */ @SuppressWarnings("rawtypes") public static Collection toCollection(Object object) { @SuppressWarnings("unused") JSONArray jsonArray = JSONArray.fromObject(object); return null; } /*** * 将对象转换为JSON对象数组 * * @param object * @return */ public static JSONArray toJSONArray(Object object) { return JSONArray.fromObject(object); } /*** * 将对象转换为JSON对象 * * @param object * @return */ public static JSONObject toJSONObject(Object object) { return JSONObject.fromObject(object); } /*** * 将对象转换为HashMap * * @param object * @return */ public static HashMap toHashMap(Object object) { HashMap data = new HashMap (); JSONObject jsonObject = JSONObject.fromObject(object); Iterator it = jsonObject.keys(); while (it.hasNext()) { String key = String.valueOf(it.next()); Object value = jsonObject.get(key); data.put(key, value); } return data; } /*** * 将对象转换为List> * * @param object * @return */ // 返回非实体类型(Map)的List public static List package com.todaytech.yth.gdsd.base.DataInfo.Util;/** * 功能:输出的json字段的值是StatusCode类决定 * 就是说返回状态的值是成功200还是失败400还是错误404,这些值 * 是StatusCode这个类定义的。 */public enum StatusCode { /** 成功 */ SUCCESS(200, "成功"), /** 没有登录 */ NOT_LOGIN(400, "登录异常"), /** * 没有授权 */ NOT_PRIVILEGE(500,"没有授权"), /** * IP请求信息异常 */ IP_INFO_EXCEPTION(501,"IP请求信息异常"), /** *请求用户名信息错误 */ LOGIN_NAME_EXCEPTION(502,"请求用户名信息错误"), /** * 请求密码信息错误 */ LOGIN_PASS_EXCEPTION(503,"请求密码信息错误"), /** 发生异常 */ EXCEPTION(401, "发生异常"), /** 系统错误 */ SYS_ERROR(402, "系统错误"), /** 参数错误 */ PARAMS_ERROR(403, "参数错误 "), /** 不支持或已经废弃 */ NOT_SUPPORTED(410, "不支持或已经废弃"), /** AuthCode错误 */ INVALID_AUTHCODE(444, "无效的AuthCode"), /** 太频繁的调用 */ TOO_FREQUENT(445, "太频繁的调用"), /** 未知的错误 */ UNKNOWN_ERROR(499, "未知错误"); private int code; private String message; StatusCode(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } /** * * @param code * @return */ public static String returnMessage(int code){ String message=""; switch (code) { case 200: message="成功"; break; case 400: message="异常"; break; case 500: message="没有授权"; break; case 501: message="IP请求信息异常"; break; case 502: message="请求用户名信息错误"; break; case 503: message="请求密码信息错误"; break; case 401: message="发生异常"; break; case 402: message="系统错误"; break; case 403: message="参数错误"; break; case 410: message="不支持或已经废弃"; break; default: break; } return message; }}package com.todaytech.yth.gdsd.base.DataInfo.Util;/** * 这个类定义了返回的json格式,即json含有哪些字段 */public class JsonResult { private int code; private String message; private Object data; public JsonResult(int code, String message, Object data) { this.code = code; this.message = message; this.data = data ; } public int getCode() { return code; } public String getMessage() { return message; } public Object getData() { return data; }}
6:白盒测试层
package com.todaytech.yth.gdsd.base.DataInfo.test;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import sun.misc.BASE64Decoder;public class decodeUtil { @SuppressWarnings("restriction") public static String decode(String toDecodeContent) throws UnsupportedEncodingException { if (toDecodeContent == null) { return null; } toDecodeContent = URLDecoder.decode(toDecodeContent, "UTF-8") .replaceAll(" ", "+"); byte[] buf = null; String result = null; try { buf = new BASE64Decoder().decodeBuffer(toDecodeContent); result = new String(buf, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } finally { } return result; }}package com.todaytech.yth.gdsd.base.DataInfo.test;import java.io.Serializable;public class Person implements Serializable{ private static final long serialVersionUID = 1L; private String name; private int age; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; }}package com.todaytech.yth.gdsd.base.DataInfo.test;import java.util.ArrayList;import java.util.List;import com.todaytech.yth.gdsd.base.DataInfo.Util.JasonUtil;public class Test_ListObjectToJason { public static void main(String[] args) { Person person1 = new Person(); person1.setAddress("address"); person1.setAge(11); person1.setName("amao"); Person person2 = new Person(); person2.setAddress("address"); person2.setAge(11); person2.setName("amao"); Listlp = new ArrayList (); lp.add(person1); lp.add(person2); System.out.println(JasonUtil.serialize(lp)); }} package com.todaytech.yth.gdsd.base.DataInfo.test;import java.io.IOException;import java.io.InputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.annotation.Resource;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import com.tt.pwp.framework.data.dao.Dao;import com.tt.pwp.framework.prefs.PrefsManager;import sxf.Student;@Controller@RequestMapping("/DataInfor")public class Test_User { @Resource private Dao defaultDao; @Resource private PrefsManager prefsManager; @RequestMapping( value = "/Test.do",produces = "application/json;charset=UTF-8") public void TestRequest(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{ String inJson = null;// 保存HTTP客户端请求报文 String outJson = null;// 保存HTTP服务端输出报文 // 获得输人报文然后打印出来 inJson = getInJson(request); System.out.println("\nauthor===========服务端日志----POST方式接收HTTP请求,HTTP服务端收到的请求报文如下:==========\n"); System.out.println(inJson); System.out.println("\nauthor =================================================================\n"); JSONArray result=new JSONArray(); RequestDispatcher rd; String keyid = "1"; //request.getParameter("keyid").trim(); try { if(keyid !=null){ String sql="select t.account_code,t.account_name,g.org_name from pwp_account t,pwp_org g where g.org_id=t.org_id and t.account_status=1 and t.account_deleted=0 and t.account_id=?"; JdbcTemplate jdbcTemplate=defaultDao.getJdbcTemplate(); List > accountList=jdbcTemplate.queryForList(sql,new Object[]{keyid}); if(accountList.size()>0){ for(int i=0;i account=accountList.get(i); json.put("account_code", account.get("account_code").toString()); json.put("account_name", account.get("account_name").toString()); json.put("org_name", account.get("org_name").toString()); result.add(json); } } // 下面部分是输出部分的处理 response.setContentType("application/json; charset=UTF-8"); response.getWriter().print(result); }else{ // 下面部分是输出部分的处理 JSONObject json=new JSONObject(); json.put("code", "0"); json.put("message", "成功"); json.put("data", "12345"); result.add(json); response.setContentType("application/json; charset=UTF-8"); response.getWriter().print(result); } } catch (Exception e) { e.printStackTrace(); } } // 获得请求的报文,并作简单的校验 public String getInJson(HttpServletRequest request) throws IOException { byte buffer[] = new byte[64 * 1024]; InputStream in = request.getInputStream();// 获取输入流对象 int len = in.read(buffer); // 必须对数组长度进行判断,否则在new byte[len]会报NegativeArraySizeException异常 if (len < 0) { throw new IOException("请求报文为空"); } String encode = request.getCharacterEncoding();// 获取请求头编码 // 必须对编码进行校验,否则在new String(data, encode);会报空指针异常 if (null == encode || encode.trim().length() < 0) { throw new IOException("请求报文未指明请求编码"); } byte data[] = new byte[len]; // 把buffer数组的值复制到data数组 System.arraycopy(buffer, 0, data, 0, len); // 通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String String inJson = new String(data, encode); return inJson; } /** * http://localhost:8081/gdsd-all/DataInfor/addstudent.do?username=liudehua&age=60 * @param username * @param age * @return */ @RequestMapping(value = "/addstudent.do", produces = "application/json;charset=UTF-8") @ResponseBody public Object addstudent(String username, int age) { // 返回数组 List studentList = new ArrayList (); Student stu = new Student(); stu.setName(username); stu.setAge(age); studentList.add(stu); stu = new Student(); stu.setName("wushan"); stu.setAge(20); studentList.add(stu); Map > map = new HashMap >(); map.put("studentList", studentList); return map; } /** * http://localhost:8081/gdsd-all/DataInfor/addstudentHttp.do?username=liudehua&age=60 * * @param request * @return */ // 通过HttpServletRequest接收,post方式和get方式都可以。 @RequestMapping(value = "/addstudentHttp.do", produces = "application/json;charset=UTF-8") @ResponseBody public Object addstudent(HttpServletRequest request) { String username = request.getParameter("username"); int age = Integer.valueOf(request.getParameter("age")); Student student = new Student(); student.setName(username); student.setAge(age); return student; } /** * http://localhost:8081/gdsd-all/DataInfor/addstudentBeen.do?username=liudehua&age=60 * username和age必须和Student的类的成员变量名称完全一致 * * @param student * @return */ // 通过一个bean来接收,post方式和get方式都可以 @RequestMapping("/addstudentBeen.do") @ResponseBody public Object addstudent(Student student) { Map map = new HashMap (); map.put("student", student); return map; } /** * http://localhost:8081/gdsd-all/DataInfor/addstudentVariable?username=liudehua&age=60 * @param username * @param age * @return */ // 通过@PathVariable获取路径中的参数 @RequestMapping("/addstudentVariable/{username}/{age}") @ResponseBody public Object addstudentVariable(@PathVariable String username, @PathVariable int age) { Student student = new Student(); student.setName(username); student.setAge(age); return student; } /** * http://localhost:8081/gdsd-all/DataInfor/addstudentParam.do?username=liudehua&age=60 * @param username * @param age * @return */ // 用注解@RequestParam绑定请求参数到方法入参 @RequestMapping("/addstudentParam.do") @ResponseBody public Object addstudentParam(@RequestParam("username") String username, @RequestParam("age") int age) { Student student = new Student(); student.setName(username); student.setAge(age); return student; }} jar 包 maven配置文件
commons-httpclient commons-httpclient 3.1 package com.todaytech.yth.gdsd.base.DataInfo.test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.security.Principal;import java.util.Arrays;import java.util.Collections;import java.util.Enumeration;import java.util.HashMap;import java.util.Locale;import java.util.Map;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.ServletInputStream;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;/** PostHttpServer.java 服务端 * ******************************************************** * 模拟的一个Http服务,处理客户端的post请求 ********************************************************** * ---@author [zt_zoro1272@163.com ] ********************************************************** * ---@version ********************************************************** * ---@since 2014-8-28 * * ** *PostHttpServer *com.todaytech.yth.gdsd.base.httpsPost.test6.PostHttpServer ** */@SuppressWarnings("unused")@Controllerpublic class PostHttpServer extends HttpServlet { private static final long serialVersionUID = 1L; /* * 代码逻辑分以下三部分: * 1.获得请求报文 * 2.根据请求报文的信息去做业务逻辑,然后封装返回报文 * 3.输出相应报文 */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String inJson = null;// 保存HTTP客户端请求报文 String outJson = null;// 保存HTTP服务端输出报文 // 获得输人报文然后打印出来 inJson = getInJson(request); System.out.println("\nauthorPostHttpServer */postHttpServer *===========服务端日志----POST方式接收HTTP请求,HTTP服务端收到的请求报文如下:==========\n"); System.out.println(inJson); System.out.println("\nauthor =================================================================\n"); // 以下代码部分获得请求报文,然后去做校验,转换以及其他的调用其他的业务逻辑等,这里就不管它 // ........................................................................ // 下面部分是输出部分的处理 // outJson = "{\"Response\": {\"code\": \"0\",\"message\": \"成功\",\"data\": \"12345\"}}";// 输出不部分也以JSON格式的字符串输出,这里我就写死 JSONArray result=new JSONArray(); JSONObject json=new JSONObject(); json.put("code", "0"); json.put("message", "成功"); json.put("data", "66666"); result.add(json); response.setContentType("application/json; charset=UTF-8"); response.getWriter().print(result); } // 获得请求的报文,并作简单的校验 public String getInJson(HttpServletRequest request) throws IOException { byte buffer[] = new byte[64 * 1024]; InputStream in = request.getInputStream();// 获取输入流对象 int len = in.read(buffer); // 必须对数组长度进行判断,否则在new byte[len]会报NegativeArraySizeException异常 if (len < 0) { throw new IOException("请求报文为空"); } String encode = request.getCharacterEncoding();// 获取请求头编码 // 必须对编码进行校验,否则在new String(data, encode);会报空指针异常 if (null == encode || encode.trim().length() < 0) { throw new IOException("请求报文未指明请求编码"); } byte data[] = new byte[len]; // 把buffer数组的值复制到data数组 System.arraycopy(buffer, 0, data, 0, len); // 通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String String inJson = new String(data, encode); return inJson; } // 不提供get的处理方式 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* String inJson = null;// 保存HTTP客户端请求报文 String outJson = null;// 保存HTTP服务端输出报文 // 获得输人报文然后打印出来 inJson = getInJson(request); System.out.println("\nauthor ===========服务端日志----POST方式接收HTTP请求,HTTP服务端收到的请求报文如下:==========\n"); System.out.println(inJson); System.out.println("\nauthor =================================================================\n"); // 以下代码部分获得请求报文,然后去做校验,转换以及其他的调用其他的业务逻辑等,这里就不管它 // ........................................................................ // 下面部分是输出部分的处理 outJson = "{\"Response\": {\"code\": \"0\",\"message\": \"成功\",\"data\": \"12345\"}}";// 输出不部分也以JSON格式的字符串输出,这里我就写死 response.setContentType("application/json; charset=UTF-8"); response.getWriter().print(outJson);*/ }} package com.todaytech.yth.gdsd.base.DataInfo.test;import java.io.IOException;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;import org.apache.commons.httpclient.methods.EntityEnclosingMethod;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.RequestEntity;import com.todaytech.yth.gdsd.base.DataInfo.Model.ZbInfoVo;/**PostHttpClient.java 客户端 * ******************************************************** * 采用httpclient插件的post方式发送流二进制流数据到HTTP服务端 ********************************************************** * ---@author [zt_zoro1272@163.com ] ********************************************************** * ---@version ********************************************************** * ---@since 2014-8-28 */public class PostHttpClient { /** * ******************************************************** * ---功能描述: 发送post请求,客户端采用二进制流发送,服务端采用二进制流介绍 ********************************************************** * ---@param json 入参的json格式的报文 * ---@param url http服务器的地址 * ---@return 返回响应信息 ********************************************************** * ---@author [zt_zoro1272@163.com ] ********************************************************** * ---@since 2014-8-28 ********************************************************** * ---@update:[变更日期YYYY-MM-DD][更改人姓名][变更描述] ********************************************************** * */ public static String postHttpReq(String json,String url) { HttpClient httpClient = new HttpClient(); byte b[] = json.getBytes();//把字符串转换为二进制数据 RequestEntity requestEntity = new ByteArrayRequestEntity(b); EntityEnclosingMethod postMethod = new PostMethod(); postMethod.setRequestEntity(requestEntity);// 设置数据 postMethod.setPath(url);// 设置服务的url postMethod.setRequestHeader("Content-Type", "text/html;charset=GBK");// 设置请求头编码 // 设置连接超时 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( 5 * 1000); // 设置读取超时 httpClient.getHttpConnectionManager().getParams().setSoTimeout(20 * 1000); String responseMsg = ""; int statusCode = 0; try { statusCode = httpClient.executeMethod(postMethod);// 发送请求 responseMsg = postMethod.getResponseBodyAsString();// 获取返回值 } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { postMethod.releaseConnection();// 释放连接 } if (statusCode != HttpStatus.SC_OK) { System.out.println("HTTP服务异常" + statusCode); } return responseMsg; } /** * 测试 使用springMvc的风格传递Jason串和返回jason串。 */ public static void requestUrl(){ String json = "{\"PubInfo\": {\"clinet\": \"127.0.0.1\",\"company\": \"月月鸟0820\"},\"Request\": {\"strBillId\": \"18221075148\",\"strCcsOpId\": \"1234\",\"account_id\": \"1\"}}"; // String url = "http://localhost:8081/gdsd-all/postHttpServer"; String url = "http://localhost:8081/gdsd-all/DataInfor/Test.do"; String outPackage = null; System.out.println("客户端日志----POST方式调用HTTP,请求报文为:" + json); outPackage = postHttpReq(json, url); System.out.println("\nauthor===========客户端日志----POST方式调用HTTP服务,HTTP服务端响应报文如下:=============\n"); System.out.println(outPackage); System.out.println("\nauthor ================================================================\n"); } /** * */ public static void requestObject(){ ZbInfoVo ziv =new ZbInfoVo(); String json = "{\"PubInfo\": {\"clinet\": \"127.0.0.1\",\"company\": \"月月鸟0820\"},\"Request\": {\"strBillId\": \"18221075148\",\"strCcsOpId\": \"1234\",\"account_id\": \"1\"}}"; String url = "http://localhost:8081/gdsd-all/DataInfor/zbInfo.do"; String outPackage = null; System.out.println("客户端日志----POST方式调用HTTP,请求报文为:" + json); outPackage = postHttpReq(json, url); System.out.println("\nauthor ===========客户端日志----POST方式调用HTTP服务,HTTP服务端响应报文如下:=============\n"); System.out.println(outPackage); System.out.println("\nauthor ================================================================\n"); } //POST方式发送HTTP请求 public static void main(String[] args) { requestObject(); }}