基於Https協議返回Jason字符串


一:代碼結構

image



二:框架結果:

spring+springMvc+springJdbchtml



三:源代碼


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){
			    	List<ZbInfoVo> zivList = 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<ZbInfoVo> 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 LocalRowMapper<T> implements RowMapper<T> {

    /** * 添加字段註釋. */
    private Class<?> targetClazz;

    /** * 添加字段註釋. */
    private HashMap<String, Field> 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 {

	List<ZbInfoVo> query();

}




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
@Transactional
public class ZbInfoServiceImp  implements ZbInfoService {
	@Resource
	private Dao defaultDao;


	@SuppressWarnings("unchecked")
	@Override
	public List<ZbInfoVo> query() {
		 String sql="select * from zb_bal z where z.BDGYEAR=to_char(sysdate,'yyyy')";
		 JdbcTemplate jdbcTemplate=defaultDao.getJdbcTemplate();
		 List<ZbInfoVo> 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 static <T> String serialize(T object) {
		return JSON.toJSONString(object);
	}

	public static <T> T deserialize(String string, Class<T> clz) {
		return JSON.parseObject(string, clz);
	}
	public static <T> T load(Path path, Class<T> clz) throws IOException {
		return deserialize(new String(Files.readAllBytes(path),DEFAULT_CHARSET_NAME), clz);
	}

	public static <T> 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 <T> String toJSONString(List<T> 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<String, Object> data = new HashMap<String, Object>();
		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<Map<String, Object>> toList(Object object) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		JSONArray jsonArray = JSONArray.fromObject(object);
		for (Object obj : jsonArray) {
			JSONObject jsonObject = (JSONObject) obj;
			Map<String, Object> map = new HashMap<String, Object>();
			Iterator it = jsonObject.keys();
			while (it.hasNext()) {
				String key = (String) it.next();
				Object value = jsonObject.get(key);
				map.put((String) key, value);
			}
			list.add(map);
		}
		return 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");

        List<Person> lp = new ArrayList<Person>();
        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<pantp>===========服務端日誌----POST方式接收HTTP請求,HTTP服務端收到的請求報文以下:==========\n");
        System.out.println(inJson);
        System.out.println("\nauthor<pantp>=================================================================\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<Map<String, Object>> accountList=jdbcTemplate.queryForList(sql,new Object[]{keyid});
				 if(accountList.size()>0){
					 for(int i=0;i<accountList.size();i++){
						 JSONObject json=new JSONObject();
						 Map<String,Object> 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<Student> studentList = new ArrayList<Student>();
		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<String, List<Student>> map = new HashMap<String, List<Student>>();
		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<String, Object> map = new HashMap<String, Object>();
		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配置文件java

<!-- 模擬HTTP的調用,寫的一個只處理POST請求的http服務 start -->
        <dependency>
		    <groupId>commons-httpclient</groupId>
		    <artifactId>commons-httpclient</artifactId>
		    <version>3.1</version>
		</dependency>
		 <!-- 模擬HTTP的調用,寫的一個只處理POST請求的http服務 end -->
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 * * <!-- 模擬HTTP的調用,寫的一個只處理POST請求的http服務 start --> * <servlet> * <servlet-name>PostHttpServer</servlet-name> * <servlet-class>com.todaytech.yth.gdsd.base.httpsPost.test6.PostHttpServer</servlet-class> * </servlet> * <servlet-mapping> * <servlet-name>PostHttpServer</servlet-name> * <url-pattern>/postHttpServer</url-pattern> * </servlet-mapping> <!-- 模擬HTTP的調用,寫的一個只處理POST請求的http服務 end --> */
@SuppressWarnings("unused")
@Controller
public 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("\nauthor<pantp>===========服務端日誌----POST方式接收HTTP請求,HTTP服務端收到的請求報文以下:==========\n");
        System.out.println(inJson);
        System.out.println("\nauthor<pantp>=================================================================\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<pantp>===========服務端日誌----POST方式接收HTTP請求,HTTP服務端收到的請求報文以下:==========\n"); System.out.println(inJson); System.out.println("\nauthor<pantp>=================================================================\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<pantp>===========客戶端日誌----POST方式調用HTTP服務,HTTP服務端響應報文以下:=============\n");
         System.out.println(outPackage);
         System.out.println("\nauthor<pantp>================================================================\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<pantp>===========客戶端日誌----POST方式調用HTTP服務,HTTP服務端響應報文以下:=============\n");
         System.out.println(outPackage);
         System.out.println("\nauthor<pantp>================================================================\n");
    }

    //POST方式發送HTTP請求
    public static void main(String[] args) {
    	requestObject();
    }

}




7:xml文件配置

<bean id="zbCtrl" class="com.todaytech.yth.gdsd.base.DataInfo.Controller.ZbInfoCtrl">
            <!--(1)依賴注入,配置當前類中相應的屬性-->
           <property name="zbis" ref="zbis"></property>
           <property name="loginCheck" ref="loginCheck"></property>
	 </bean>
	 <bean name="zbis" class="com.todaytech.yth.gdsd.base.DataInfo.Service.imp.ZbInfoServiceImp"></bean>
	 <bean name="loginCheck" class="com.todaytech.yth.gdsd.base.DataInfo.Service.imp.LoginInfoCheckServiceImp"></bean>
相關文章
相關標籤/搜索