陈士柏 преди 4 години
родител
ревизия
8223580e98
променени са 90 файла, в които са добавени 9851 реда и са изтрити 0 реда
  1. 76 0
      AuthenticationInterceptor.java
  2. 133 0
      Base64.java
  3. 223 0
      Build.java
  4. 59 0
      Build_elec.java
  5. 31 0
      CharacterEncodingFilter.java
  6. 21 0
      Clien_test.java
  7. 198 0
      CodeUtil.java
  8. 32 0
      Config.java
  9. 10 0
      ConfigDao.java
  10. 39 0
      ConfigDaoImpl.java
  11. 10 0
      ConfigService.java
  12. 29 0
      ConfigServiceImpl.java
  13. 98 0
      ConstDefault.java
  14. 142 0
      Consume.java
  15. 26 0
      ConsumeDao.java
  16. 143 0
      ConsumeDaoImpl.java
  17. 26 0
      ConsumeService.java
  18. 59 0
      ConsumeServiceImpl.java
  19. 301 0
      DataClient.java
  20. 37 0
      DataSourceAspect.java
  21. 50 0
      Device.java
  22. 12 0
      DictionaryCompare.java
  23. 43 0
      DynamicDataSourceHolder.java
  24. 12 0
      DynamicDatasource.java
  25. 296 0
      Elec.java
  26. 18 0
      ElecDao.java
  27. 87 0
      ElecDaoImpl.java
  28. 18 0
      ElecService.java
  29. 44 0
      ElecServiceImpl.java
  30. 51 0
      EndPay.java
  31. 18 0
      GloablExceptionHandler.java
  32. 34 0
      Globals.java
  33. 350 0
      HttpClientHelper.java
  34. 200 0
      HttpUtils.java
  35. 377 0
      HttpsClient.java
  36. 23 0
      InterceptorConfig.java
  37. 164 0
      JaxbUtil.java
  38. 56 0
      JsonUtil.java
  39. 26 0
      LeyouCorsConfig.java
  40. 95 0
      Login.java
  41. 52 0
      LoginFilter.java
  42. 2 0
      MANIFEST.MF
  43. 49 0
      MD5Utils.java
  44. 55 0
      Msg.java
  45. 23 0
      MyX509TrustManager.java
  46. 36 0
      ObjectUtil.java
  47. 12 0
      PassToken.java
  48. 76 0
      Pay.java
  49. 275 0
      PayResult.java
  50. 128 0
      PayWxUtil.java
  51. 43 0
      Price.java
  52. 34 0
      QueryUrlEnum.java
  53. 79 0
      Recharge.java
  54. 19 0
      RechargeDao.java
  55. 107 0
      RechargeDaoImpl.java
  56. 20 0
      RechargeService.java
  57. 36 0
      RechargeServiceImpl.java
  58. 134 0
      RedPacketAlgorithm.java
  59. 582 0
      RedisUtil.java
  60. 53 0
      ResUtil.java
  61. 52 0
      ResponseUtil.java
  62. 86 0
      ResultStatusCode.java
  63. 103 0
      ResultUtil.java
  64. 42 0
      SHA1.java
  65. 845 0
      StringUtil.java
  66. 21 0
      Test.java
  67. 21 0
      TokenUtil.java
  68. 84 0
      TongYiReturn.java
  69. 163 0
      User.java
  70. 25 0
      UserDao.java
  71. 140 0
      UserDaoImpl.java
  72. 12 0
      UserLoginToken.java
  73. 27 0
      UserService.java
  74. 76 0
      UserServiceImpl.java
  75. 115 0
      Users.java
  76. 23 0
      WebMvcConfig.java
  77. 105 0
      WechatUnifiedOrder.java
  78. 19 0
      WeiXinUtil.java
  79. 693 0
      Wp.java
  80. 53 0
      WxConfig.java
  81. 53 0
      WxConstants.java
  82. 31 0
      WxMenuService.java
  83. 95 0
      WxMenuServiceImpl.java
  84. 584 0
      WxPay.java
  85. 381 0
      WxUtil.java
  86. 211 0
      applicationContext.xml
  87. 72 0
      struts.xml
  88. 187 0
      test.json
  89. 40 0
      test2.java
  90. 10 0
      zc.properties

+ 76 - 0
AuthenticationInterceptor.java

@@ -0,0 +1,76 @@
+package com.happy.interceptor;
+
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.Login;
+import com.happy.Until.ResultUtil;
+import com.happy.Until.TokenUtil;
+import com.happy.annotation.PassToken;
+import com.happy.annotation.UserLoginToken;
+import com.happy.constant.ResultStatusCode;
+import com.happy.service.UserService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.method.HandlerMethod;
+import org.springframework.web.servlet.HandlerInterceptor;
+import org.springframework.web.servlet.ModelAndView;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.lang.reflect.Method;
+import java.time.LocalDateTime;
+import java.util.List;
+
+
+public class AuthenticationInterceptor implements HandlerInterceptor {
+    @Autowired
+    UserService userService;
+
+    @Override
+    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
+        String access_token = TokenUtil.getRequestToken(httpServletRequest);
+        // 如果不是映射到方法直接通过
+        if(!(object instanceof HandlerMethod)){
+            return true;
+        }
+        HandlerMethod handlerMethod=(HandlerMethod)object;
+        Method method=handlerMethod.getMethod();
+        //检查是否有passtoken注释,有则跳过认证
+        if (method.isAnnotationPresent(PassToken.class)) {
+            PassToken passToken = method.getAnnotation(PassToken.class);
+            if (passToken.required()) {
+                return true;
+            }
+        }
+        //检查有没有需要用户权限的注解
+        if (method.isAnnotationPresent(UserLoginToken.class)) {
+            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
+            if (userLoginToken.required()) {
+                // 执行认证
+                if (access_token == null) {
+                    throw new RuntimeException(JSONObject.toJSONString(ResultUtil.build(ResultStatusCode.SHIRO_ERROR)));
+                }
+                //1. 根据token,查询用户信息
+                List<Login> logins = userService.findByToken(access_token);
+                //2. 若用户不存在,
+                if (logins.isEmpty()) {
+                    throw new RuntimeException(JSONObject.toJSONString(ResultUtil.build(ResultStatusCode.LOGINED_IN2)));
+                }
+                //3. token失效
+                LocalDateTime tie = LocalDateTime.parse(logins.get(0).getAccess_token());
+                if (tie.isBefore(LocalDateTime.now())) {
+                    throw new RuntimeException(JSONObject.toJSONString(ResultUtil.build(ResultStatusCode.LOGINED_IN3)));
+                }
+                return true;
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
+
+    }
+    @Override
+    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
+
+    }
+}

+ 133 - 0
Base64.java

@@ -0,0 +1,133 @@
+package com.happy.Unitil_elc;
+
+import java.io.ByteArrayOutputStream;
+
+public class Base64 {
+
+    // map 6-bit int to char
+    private static final char[] chars64 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a',
+                                            'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
+                                            '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
+
+    // map char to 6-bit int
+    private static final int[]  ints64  = new int[128];
+    static {
+        for (int i = 0; i < 64; i++) {
+            ints64[chars64[i]] = i;
+        }
+    }
+
+    /**
+     * 转换byte数组成Base64 string
+     * 
+     * @param unencoded
+     * @return
+     */
+    public static final String encode(byte[] unencoded) {
+        // Take 24-bits from three octets, translate into four encoded chars.
+        // If necessary, pad with 0 bits on the right at the end
+        // Use = signs as padding at the end to ensure encodedLength % 4 == 0
+        if (unencoded == null || unencoded.length == 0) return null;
+
+        ByteArrayOutputStream out = new ByteArrayOutputStream((int) (unencoded.length * 1.37));
+        int byteCount = 0;
+        int carryOver = 0;
+
+        for (int i = 0; i < unencoded.length; i++) {
+            int bc = (byteCount % 3);
+            byte b = unencoded[i];
+            int lookup = 0;
+
+            // First byte use first six bits, save last two bits
+            if (bc == 0) {
+                lookup = (b >> 2) & 0x3F;
+                carryOver = b & 0x03; // last two bits
+                out.write(chars64[lookup]);
+            } else if (bc == 1) {
+                // Second byte use previous two bits and first four new bits,
+                // save last four bits
+                lookup = ((carryOver << 4) | ((b >> 4) & 0x0F));
+                carryOver = b & 0x0F; // last four bits
+                out.write(chars64[lookup]);
+            } else if (bc == 2) {
+                // Third byte use previous four bits and first two new bits,
+                // then use last six new bits
+                lookup = ((carryOver << 2) | ((b >> 6) & 0x03));
+                out.write(chars64[lookup]);
+
+                lookup = b & 0x3F; // last six bits
+                out.write(chars64[lookup]);
+                carryOver = 0;
+            }
+            byteCount++;
+        }
+
+        if (byteCount % 3 == 1) { // one leftover
+            int lookup = (carryOver << 4) & 0xF0;
+            out.write(chars64[lookup]);
+            out.write('=');
+            out.write('=');
+        } else if (byteCount % 3 == 2) { // two leftovers
+            int lookup = (carryOver << 2) & 0x3C;
+            out.write(chars64[lookup]);
+            out.write('=');
+        }
+        return out.toString();
+    }
+
+    /**
+     * Decode Base64 string back to byte array
+     * 
+     * @param encoded
+     * @return
+     */
+    public static final byte[] decode(String encoded) {
+        if (encoded == null || encoded.length() == 0) return null;
+
+        byte[] bytes = encoded.getBytes();
+
+        ByteArrayOutputStream out = new ByteArrayOutputStream((int) (bytes.length * 0.67));
+        int byteCount = 0;
+        int carryOver = 0;
+
+        DECODE_LOOP: for (int i = 0; i < bytes.length; i++) {
+            int ch = bytes[i];
+
+            // Read the next non-whitespace character
+            // if (Character.isWhitespace((char)ch))
+            // continue;
+
+            // The '=' sign is just padding; geffective end of stream
+            if (ch == '=') break DECODE_LOOP;
+
+            // Convert from raw form to 6-bit form
+            int newbits = ints64[ch];
+
+            int bc = (byteCount % 4);
+            if (bc == 0) {
+                // First char save all six bits, go for another
+                carryOver = newbits & 0x3F;
+            } else if (bc == 1) {
+                // second char use 6 previous bits and first 2 new bits
+                int data = ((carryOver << 2) + ((newbits >> 4) & 0x03));
+                out.write(data);
+                carryOver = newbits & 0x0F; // save 4 bits
+            } else if (bc == 2) {
+                // Third char use previous four bits and first four new bits,
+                // save last two bits
+                int data = ((carryOver << 4) + ((newbits >> 2) & 0x0F));
+                out.write(data);
+                carryOver = newbits & 0x03; // save 2 bits
+            } else if (bc == 3) {
+                // Fourth char use previous two bits and all six new bits
+                int data = ((carryOver << 6) + (newbits & 0x3F));
+                out.write(data);
+                carryOver = 0;
+            }
+            byteCount++;
+        }
+
+        return out.toByteArray();
+    }
+
+}

+ 223 - 0
Build.java

@@ -0,0 +1,223 @@
+package com.happy.action;
+
+import com.alibaba.fastjson.JSONObject;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.happy.Model.Build_elec;
+import com.happy.Model.Price;
+import com.happy.Until.ResUtil;
+import com.happy.service.ConsumeService;
+import com.happy.service.ElecService;
+import com.happy.service.RechargeService;
+import com.happy.service.UserService;
+import com.opensymphony.xwork2.ActionSupport;
+import net.sf.json.JSONArray;
+import org.apache.struts2.ServletActionContext;
+import org.apache.struts2.interceptor.ServletRequestAware;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import testExport.DataClient;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+public class Build extends ActionSupport implements ServletRequestAware {
+
+    private HttpServletRequest request;
+
+    public HttpServletResponse response;
+
+    public String roomSelect;
+
+    @Resource
+    public ElecService elecService;
+    @Resource
+    public UserService userService;
+    @Resource
+    public ConsumeService consumeService;
+    @Resource
+    public RechargeService rechargeService;
+    @Autowired
+    public RedisTemplate redisTemplate;
+
+    public String getRoomSelect() {
+        return roomSelect;
+    }
+
+    public void setRoomSelect(String roomSelect) {
+        this.roomSelect = roomSelect;
+    }
+
+    public HttpServletRequest getRequest() {
+        return request;
+    }
+
+    public void setRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public void setServletRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public HttpServletResponse getResponse() {
+        return response;
+    }
+
+    public void setResponse(HttpServletResponse response) {
+        this.response = response;
+    }
+
+    public String bd_elec() throws Exception {
+        ArrayList<JSONObject> aj_school = new ArrayList<>();
+        List<Build_elec> schools = elecService.querySchool();
+        for (int i=0; i<schools.size(); i++) {
+            JSONObject resultJson1 = new JSONObject();
+            resultJson1.put("school", schools.get(i).getSchool());
+            List<Build_elec> builds = elecService.queryBuild(schools.get(i).getSchool());
+            ArrayList<JSONObject> aj_build = new ArrayList();
+            //resultJson1.put("builds", aj2);
+            for (int j=0; j<builds.size(); j++){
+                JSONObject resultJson2 = new JSONObject();
+                resultJson2.put("building", builds.get(j).getBuild());
+                List<Build_elec> floors = elecService.queryFloors(
+                        schools.get(i).getSchool(), builds.get(j).getBuild());
+                ArrayList<JSONObject> aj_floor = new ArrayList();
+                for (int k=0; k<floors.size(); k++){
+                    JSONObject resultJson3 = new JSONObject();
+                    resultJson3.put("floor", floors.get(k).getFloors());
+                    List<Build_elec> dom = elecService.queryDom(
+                            schools.get(i).getSchool(), builds.get(j).getBuild(), floors.get(k).getFloors());
+                    ArrayList adom = new ArrayList();
+                    for (int m=0; m<dom.size(); m++){
+                        adom.add(dom.get(m).getDom());
+                    }
+                    resultJson3.put("rooms", adom);
+                    aj_floor.add(resultJson3);
+                }
+                resultJson2.put("floors", aj_floor);
+                aj_build.add(resultJson2);
+            }
+            resultJson1.put("builds", aj_build);
+            aj_school.add(resultJson1);
+        }
+        String resultJson = JSONArray.fromObject(aj_school).toString();
+        try {
+            redisTemplate.delete("build");
+        }catch (Exception e){
+            System.out.println("build已清");
+        }
+        redisTemplate.opsForValue().set("build", resultJson);
+        ResUtil.write("绑定成功", ServletActionContext.getResponse());
+        return null;
+    }
+
+    public String elec() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        try {
+            String data = (String) redisTemplate.opsForValue().get("build");
+            resultJson.put("mess", "返回成功");
+            resultJson.put("data", data);
+        }catch (Exception e){
+            resultJson.put("mess", "获取数据异常");
+        }
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+    public String overElec() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        if (roomSelect==null){
+            resultJson.put("mess", "请选择房间号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String school = roomSelect.substring(0, 5);
+        String room = roomSelect.substring(5, 9);
+        List<Build_elec> spl = elecService.queryUser_id(school, room);
+        if (spl == null){
+            resultJson.put("mess", "未查询到户号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String user_id = spl.get(0).getUser_id();
+        DataClient.getToken();
+        JSONObject jb = DataClient.getAccountInfo(user_id);
+        if (jb == null){
+            resultJson.put("mess", "未查询到户号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        Object data = jb.get("data");
+        Gson gson=new Gson();
+        HashMap<String, String> userMoney = gson.fromJson(data.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
+        double elcMoney = Double.parseDouble(userMoney.get("usablemoney"));
+        Double amount = 0.00;
+        List<Price> elcPrice = consumeService.water_price("电费");
+        amount = elcMoney / elcPrice.get(0).getPrice() ;
+        System.out.println(amount);
+        JSONObject j2 = new JSONObject();
+        j2.put("mess", "0");
+        j2.put("amount", amount);
+        ResUtil.write(j2, ServletActionContext.getResponse());
+        return null;
+    }
+
+    public String getMonthBill() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        if (roomSelect==null){
+            resultJson.put("mess", "请选择房间号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String school = roomSelect.substring(0, 5);
+        String room = roomSelect.substring(5, 9);
+        List<Build_elec> spl = elecService.queryUser_id(school, room);
+        if (spl == null){
+            resultJson.put("mess", "未查询到户号!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        String user_id = spl.get(0).getUser_id();
+        DataClient.getToken();
+        List<String> dateList = new ArrayList<>();
+        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
+        for (int i=0; i>-12; i--){
+            Calendar calendar = Calendar.getInstance();
+            calendar.add(Calendar.MONTH,i);
+            dateList.add(simpleDateFormat.format(calendar.getTime()));
+        }
+        String da = JSONArray.fromObject(dateList).toString();
+        JSONObject json = DataClient.getMonthBill(user_id, da);
+        Gson gson=new Gson();
+        Object data=null;
+        try {
+            data = json.get("data");
+        }catch (Exception e){
+            resultJson.put("mess", "未查询到数据");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        List<HashMap<String, String>> user_elc = gson.fromJson(data.toString(), new TypeToken<List<HashMap<String, String>>>(){}.getType());
+        if (user_elc==null){
+            resultJson.put("mess", "未查询到数据");
+            return null;
+        }
+        ArrayList<String> use_elc = new ArrayList<>();
+        ArrayList<String> date_time = new ArrayList<>();
+        for (int i=0; i<user_elc.size(); i++){
+            use_elc.add(user_elc.get(i).get("zongPower"));
+            date_time.add(user_elc.get(i).get("dataTime"));
+        }
+
+        resultJson.put("use_elc", use_elc);
+        resultJson.put("date_time", date_time);
+        resultJson.put("mess", "0");
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+}

+ 59 - 0
Build_elec.java

@@ -0,0 +1,59 @@
+package com.happy.Model;
+
+public class Build_elec {
+
+    public int id;
+    public String school;
+    public String build;
+    public String floors;
+    public String dom;
+    public String user_id;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getSchool() {
+        return school;
+    }
+
+    public void setSchool(String school) {
+        this.school = school;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getFloors() {
+        return floors;
+    }
+
+    public void setFloors(String floors) {
+        this.floors = floors;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String getUser_id() {
+        return user_id;
+    }
+
+    public void setUser_id(String user_id) {
+        this.user_id = user_id;
+    }
+}

+ 31 - 0
CharacterEncodingFilter.java

@@ -0,0 +1,31 @@
+//
+// Source code recreated from a .class file by IntelliJ IDEA
+// (powered by Fernflower decompiler)
+//
+
+package com.happy.filter;
+
+import java.io.IOException;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+public class CharacterEncodingFilter implements Filter {
+	public CharacterEncodingFilter() {
+	}
+
+	public void destroy() {
+	}
+
+	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+		request.setCharacterEncoding("utf-8");
+		response.setCharacterEncoding("utf-8");
+		chain.doFilter(request, response);
+	}
+
+	public void init(FilterConfig arg0) throws ServletException {
+	}
+}

+ 21 - 0
Clien_test.java

@@ -0,0 +1,21 @@
+package testExport;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.happy.Model.QueryUrlEnum;
+import com.happy.Unitil_elc.CodeUtil;
+import com.happy.Unitil_elc.HttpClientHelper;
+import com.happy.Unitil_elc.JsonUtil;
+import com.happy.Unitil_elc.StringUtil;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+public class Clien_test {
+    public static void main(String[] args) {
+        DataClient.getToken();
+        DataClient.getUserAccountInfo();
+    }
+}

+ 198 - 0
CodeUtil.java

@@ -0,0 +1,198 @@
+package com.happy.Unitil_elc;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+public class CodeUtil {
+
+
+    /**
+     * 解密
+     * @param src       源数据
+     * @param secret    秘钥
+     * @param iv        初始化向量
+     * @return          String
+     */
+    public static String dataDecode(String src, String secret, String iv){
+        try {
+            // 判断Key是否正确
+            if (secret == null) {
+                System.out.print("Key为空null");
+                return null;
+            }
+            // 判断Key是否为16位
+            if (secret.length() != 16) {
+                System.out.print("Key长度不是16位");
+                return null;
+            }
+            byte[] raw = secret.getBytes(StandardCharsets.US_ASCII);
+            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
+            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+            IvParameterSpec ips  = new IvParameterSpec(iv.getBytes());
+            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
+            // byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
+            byte[] encrypted1 = Base64.decode(src);
+            try {
+                byte[] original = cipher.doFinal(encrypted1);
+                return new String(original, StandardCharsets.UTF_8);
+            } catch (Exception e) {
+                System.out.println(e.toString());
+                return null;
+            }
+        } catch (Exception ex) {
+            System.out.println(ex.toString());
+            return null;
+        }
+    }
+
+    /**
+     *  加密
+     * @param src       源数据
+     * @param secret    秘钥
+     * @param iv        初始化向量
+     * @return          String
+     */
+    public static String dataEncode(String src, String secret, String iv) throws Exception {
+        if (secret == null) {
+            System.out.print("Key为空null");
+            return null;
+        }
+        // 判断Key是否为16位
+        if (secret.length() != 16) {
+            System.out.print("Key长度不是16位");
+            return null;
+        }
+        byte[] raw = secret.getBytes(StandardCharsets.UTF_8);
+        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
+        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
+        IvParameterSpec ips = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
+        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
+        byte[] encrypted = cipher.doFinal(src.getBytes(StandardCharsets.UTF_8));
+        // return new BASE64Encoder().encode(encrypted);// 此处使用BASE64做转码功能,同时能起到2次加密的作用。
+        return Base64.encode(encrypted);
+    }
+
+    /**
+     * 获取签名
+     * @param src       源数据
+     * @param signKey   签名秘钥
+     * @return          String
+     */
+    public static String getSign(String src,String signKey){
+        String result = "";
+        try {
+            byte[] keyByte = signKey.getBytes(StandardCharsets.UTF_8);
+            byte[] dataByte = src.getBytes(StandardCharsets.UTF_8);
+            byte[] hmacMd5Byte = getHmacMd5Bytes(keyByte, dataByte);
+            StringBuilder md5Str = new StringBuilder();
+            for (byte b : hmacMd5Byte) {
+                if (Integer.toHexString(0xFF & b).length() == 1) md5Str.append("0").append(Integer.toHexString(0xFF & b));
+                else md5Str.append(Integer.toHexString(0xFF & b));
+            }
+            result = md5Str.toString().toUpperCase();
+
+        } catch (Exception ignored) {
+        }
+        return result;
+
+    }
+
+
+    /**
+     * 将待加密数据data,通过密钥key,使用hmac-md5算法进行加密,然后返回加密结果。 参照rfc2104 HMAC算法介绍实现。
+     *
+     * @author sc
+     * @param key 密钥
+     * @param data 待加密数据
+     * @return 加密结果
+     */
+    private static byte[] getHmacMd5Bytes(byte[] key, byte[] data) throws NoSuchAlgorithmException {
+        /*
+         * HmacMd5 calculation formula: H(K XOR opad, H(K XOR ipad, text)) HmacMd5 计算公式:H(K XOR opad, H(K XOR ipad,
+         * text)) H代表hash算法,本类中使用MD5算法,K代表密钥,text代表要加密的数据 ipad为0x36,opad为0x5C。
+         */
+        int length = 64;
+        byte[] ipad = new byte[length];
+        byte[] opad = new byte[length];
+        for (int i = 0; i < 64; i++) {
+            ipad[i] = 0x36;
+            opad[i] = 0x5C;
+        }
+        byte[] actualKey = key; // Actual key.
+        byte[] keyArr = new byte[length]; // Key bytes of 64 bytes length
+        /*
+         * If key's length is longer than 64,then use hash to digest it and use the result as actual key.
+         * 如果密钥长度,大于64字节,就使用哈希算法,计算其摘要,作为真正的密钥。
+         */
+        if (key.length > length) {
+            actualKey = md5(key);
+        }
+        System.arraycopy(actualKey, 0, keyArr, 0, actualKey.length);
+        /*
+         * append zeros to K 如果密钥长度不足64字节,就使用0x00补齐到64字节。
+         */
+        if (actualKey.length < length) {
+            for (int i = actualKey.length; i < keyArr.length; i++)
+                keyArr[i] = 0x00;
+        }
+
+        /*
+         * calc K XOR ipad 使用密钥和ipad进行异或运算。
+         */
+        byte[] kIpadXorResult = new byte[length];
+        for (int i = 0; i < length; i++) {
+            kIpadXorResult[i] = (byte) (keyArr[i] ^ ipad[i]);
+        }
+
+        /*
+         * append "text" to the end of "K XOR ipad" 将待加密数据追加到K XOR ipad计算结果后面。
+         */
+        byte[] firstAppendResult = new byte[kIpadXorResult.length + data.length];
+        System.arraycopy(kIpadXorResult, 0, firstAppendResult, 0, kIpadXorResult.length);
+        System.arraycopy(data, 0, firstAppendResult, keyArr.length, data.length);
+
+        /*
+         * calc H(K XOR ipad, text) 使用哈希算法计算上面结果的摘要。
+         */
+        byte[] firstHashResult = md5(firstAppendResult);
+
+        /*
+         * calc K XOR opad 使用密钥和opad进行异或运算。
+         */
+        byte[] kOpadXorResult = new byte[length];
+        for (int i = 0; i < length; i++) {
+            kOpadXorResult[i] = (byte) (keyArr[i] ^ opad[i]);
+        }
+
+        /*
+         * append "H(K XOR ipad, text)" to the end of "K XOR opad" 将H(K XOR ipad, text)结果追加到K XOR opad结果后面
+         */
+        byte[] secondAppendResult = new byte[kOpadXorResult.length + firstHashResult.length];
+        System.arraycopy(kOpadXorResult, 0, secondAppendResult, 0, kOpadXorResult.length);
+        System.arraycopy(firstHashResult, 0, secondAppendResult, keyArr.length, firstHashResult.length);
+
+        /*
+         * H(K XOR opad, H(K XOR ipad, text)) 对上面的数据进行哈希运算。
+         */
+        return md5(secondAppendResult);
+    }
+
+
+    /**
+     * 计算参数的md5信息
+     *
+     * @param str 待处理的字节数组
+     * @return md5摘要信息
+     */
+    private static byte[] md5(byte[] str) throws NoSuchAlgorithmException {
+        MessageDigest md = MessageDigest.getInstance("MD5");
+        md.update(str);
+        return md.digest();
+    }
+
+
+}

+ 32 - 0
Config.java

@@ -0,0 +1,32 @@
+package com.happy.Model;
+
+public class Config {
+
+    public int id;
+    public String name;
+    public int value;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public int getValue() {
+        return value;
+    }
+
+    public void setValue(int value) {
+        this.value = value;
+    }
+}

+ 10 - 0
ConfigDao.java

@@ -0,0 +1,10 @@
+package com.happy.dao;
+
+import com.happy.Model.Config;
+
+import java.util.List;
+
+public interface ConfigDao {
+
+    public List<Config> query(String name);
+}

+ 39 - 0
ConfigDaoImpl.java

@@ -0,0 +1,39 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.Config;
+import com.happy.Model.Consume;
+import com.happy.dao.ConfigDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository("ConfigDao")
+public class ConfigDaoImpl implements ConfigDao {
+
+    @Autowired
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+        return namedParameterJdbcTemplate;
+    }
+
+    public void setNamedParameterJdbcTemplate(
+            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+    }
+
+    public List<Config> query(String name){
+        String sql="select * from config where name=:name";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("name", name);
+        List<Config> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Config>(Config.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+}

+ 10 - 0
ConfigService.java

@@ -0,0 +1,10 @@
+package com.happy.service;
+
+import com.happy.Model.Config;
+
+import java.util.List;
+
+public interface ConfigService {
+
+    public List<Config> query(String name);
+}

+ 29 - 0
ConfigServiceImpl.java

@@ -0,0 +1,29 @@
+package com.happy.service.impl;
+
+import com.happy.Model.Config;
+import com.happy.dao.ConfigDao;
+import com.happy.dao.ConsumeDao;
+import com.happy.service.ConfigService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@Service("ConfigService")
+public class ConfigServiceImpl implements ConfigService {
+
+    @Resource
+    public ConfigDao configDao;
+
+    public ConfigDao getConfigDao() {
+        return configDao;
+    }
+
+    public void setConfigDao(ConfigDao configDao) {
+        this.configDao = configDao;
+    }
+
+    public List<Config> query(String name){
+        return configDao.query(name);
+    }
+}

+ 98 - 0
ConstDefault.java

@@ -0,0 +1,98 @@
+package com.happy.constant;
+
+import org.apache.http.client.HttpClient;
+
+import java.text.SimpleDateFormat;
+
+/**
+ * lockcslock
+ *
+ * @author yp
+ */
+public final class ConstDefault {
+
+    public static final String DATETIMES_FORMAT_STRING = "yyyy-MM-dd HH:mm:ss";
+    public static final String DATE_FORMAT_STRING = "yyyy-MM-dd";
+    public static final String TIMES_FORMAT_STRING = "HH:mm:ss";
+
+    public static final SimpleDateFormat DATETIMES_FORMAT = new SimpleDateFormat(DATETIMES_FORMAT_STRING);
+    public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_STRING);
+    public static final SimpleDateFormat TIMES_FORMAT = new SimpleDateFormat(TIMES_FORMAT_STRING);
+
+    public final static class USERROLE {
+        public final static int NORMMAL = 4;
+        public final static int SYSTEMADMIN = 1;
+        public final static int DEVICEADMIN = 2;
+    }
+
+    public final static class THIRDTYPE {
+
+        public final static int WEIXINPUBLIC = 1;
+        public final static int WEIXIN_MINI = 2;
+        public final static int WEIXIN_OPEN = 3;
+
+    }
+
+    public final static int ANONYMOUSID = -1;
+    public final static int DEFAULTORG = 1;
+    public final static int DEFAULTROLEPERMISSON = 0;
+    public final static int SOUND_KEY = 1;
+
+    //密码得前缀字符串
+    public static String FTSTR = "PARTYDUES";
+    //密码得后缀字符串
+    public static String BGSTR = "LYKJ";
+
+    //微信登录的token
+    public static String WXID = "wx";
+
+    public static String WXPASSWORD = "partydues";
+
+    public enum SignType {
+        MD5, HMACSHA256
+    }
+
+    public static final String DOMAIN_API = "api.mch.weixin.qq.com";
+    public static final String DOMAIN_API2 = "api2.mch.weixin.qq.com";
+    public static final String DOMAIN_APIHK = "apihk.mch.weixin.qq.com";
+    public static final String DOMAIN_APIUS = "apius.mch.weixin.qq.com";
+
+    public static final String FAIL     = "FAIL";
+    public static final String SUCCESS  = "SUCCESS";
+    public static final String HMACSHA256 = "HMAC-SHA256";
+    public static final String MD5 = "MD5";
+
+    public static final String FIELD_SIGN = "sign";
+    public static final String FIELD_SIGN_TYPE = "sign_type";
+
+    public static final String WXPAYSDK_VERSION = "WXPaySDK/3.0.9";
+    public static final String USER_AGENT = WXPAYSDK_VERSION +
+            " (" + System.getProperty("os.arch") + " " + System.getProperty("os.name") + " " + System.getProperty("os.version") +
+            ") Java/" + System.getProperty("java.version") + " HttpClient/" + HttpClient.class.getPackage().getImplementationVersion();
+
+    public static final String MICROPAY_URL_SUFFIX     = "/pay/micropay";
+    public static final String UNIFIEDORDER_URL_SUFFIX = "/pay/unifiedorder";
+    public static final String ORDERQUERY_URL_SUFFIX   = "/pay/orderquery";
+    public static final String REVERSE_URL_SUFFIX      = "/secapi/pay/reverse";
+    public static final String CLOSEORDER_URL_SUFFIX   = "/pay/closeorder";
+    public static final String REFUND_URL_SUFFIX       = "/secapi/pay/refund";
+    public static final String REFUNDQUERY_URL_SUFFIX  = "/pay/refundquery";
+    public static final String DOWNLOADBILL_URL_SUFFIX = "/pay/downloadbill";
+    public static final String REPORT_URL_SUFFIX       = "/payitil/report";
+    public static final String SHORTURL_URL_SUFFIX     = "/tools/shorturl";
+    public static final String AUTHCODETOOPENID_URL_SUFFIX = "/tools/authcodetoopenid";
+
+    // sandbox
+    public static final String SANDBOX_MICROPAY_URL_SUFFIX     = "/sandboxnew/pay/micropay";
+    public static final String SANDBOX_UNIFIEDORDER_URL_SUFFIX = "/sandboxnew/pay/unifiedorder";
+    public static final String SANDBOX_ORDERQUERY_URL_SUFFIX   = "/sandboxnew/pay/orderquery";
+    public static final String SANDBOX_REVERSE_URL_SUFFIX      = "/sandboxnew/secapi/pay/reverse";
+    public static final String SANDBOX_CLOSEORDER_URL_SUFFIX   = "/sandboxnew/pay/closeorder";
+    public static final String SANDBOX_REFUND_URL_SUFFIX       = "/sandboxnew/secapi/pay/refund";
+    public static final String SANDBOX_REFUNDQUERY_URL_SUFFIX  = "/sandboxnew/pay/refundquery";
+    public static final String SANDBOX_DOWNLOADBILL_URL_SUFFIX = "/sandboxnew/pay/downloadbill";
+    public static final String SANDBOX_REPORT_URL_SUFFIX       = "/sandboxnew/payitil/report";
+    public static final String SANDBOX_SHORTURL_URL_SUFFIX     = "/sandboxnew/tools/shorturl";
+    public static final String SANDBOX_AUTHCODETOOPENID_URL_SUFFIX = "/sandboxnew/tools/authcodetoopenid";
+
+}

+ 142 - 0
Consume.java

@@ -0,0 +1,142 @@
+package com.happy.Model;
+
+import java.math.BigDecimal;
+
+public class Consume {
+
+    public Integer id;
+    public String card_number;
+    public String stu_number;
+    public String user_name;
+    public String order_no;
+    public String pay_time;
+    public String begin_time;
+    public String end_time;
+    public double use_amount;
+    public String merchant_name;
+    public String start_code;
+    public String device_code;
+    public Integer type;
+    public int state;
+    public double use_size;
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public double getUse_amount() {
+        return use_amount;
+    }
+
+    public void setUse_amount(double use_amount) {
+        this.use_amount = use_amount;
+    }
+
+    public int getState() {
+        return state;
+    }
+
+    public void setState(int state) {
+        this.state = state;
+    }
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public String getOrder_no() {
+        return order_no;
+    }
+
+    public void setOrder_no(String order_no) {
+        this.order_no = order_no;
+    }
+
+    public String getPay_time() {
+        return pay_time;
+    }
+
+    public void setPay_time(String pay_time) {
+        this.pay_time = pay_time;
+    }
+
+    public String getBegin_time() {
+        return begin_time;
+    }
+
+    public void setBegin_time(String begin_time) {
+        this.begin_time = begin_time;
+    }
+
+    public String getEnd_time() {
+        return end_time;
+    }
+
+    public void setEnd_time(String end_time) {
+        this.end_time = end_time;
+    }
+
+    public double getUse_size() {
+        return use_size;
+    }
+
+    public void setUse_size(double use_size) {
+        this.use_size = use_size;
+    }
+
+    public String getMerchant_name() {
+        return merchant_name;
+    }
+
+    public void setMerchant_name(String merchant_name) {
+        this.merchant_name = merchant_name;
+    }
+
+    public String getStart_code() {
+        return start_code;
+    }
+
+    public void setStart_code(String start_code) {
+        this.start_code = start_code;
+    }
+
+    public String getDevice_code() {
+        return device_code;
+    }
+
+    public void setDevice_code(String device_code) {
+        this.device_code = device_code;
+    }
+
+    public Integer getType() {
+        return type;
+    }
+
+    public void setType(Integer type) {
+        this.type = type;
+    }
+}

+ 26 - 0
ConsumeDao.java

@@ -0,0 +1,26 @@
+package com.happy.dao;
+
+import com.happy.Model.Consume;
+import com.happy.Model.Price;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public interface ConsumeDao {
+
+    public List<Consume> queryRecordByOrder(String order_no);
+
+    public List<Consume> queryRecordByCard(String card_number, String begin_time);
+
+    public List<Consume> queryRecordByStu(String stu_number, String begin_time);
+
+    public int insertComsume(Consume consume);
+
+    public int updateBalance(String stu_number, double balance);
+
+    public int updateConsume2(String order_no, String pay_time, double use_amount, double use_size, int state);
+
+    public int updateConsume(String order_no, String pay_time, BigDecimal use_amount, BigDecimal use_size, int state);
+
+    public List<Price> water_price(String name);
+}

+ 143 - 0
ConsumeDaoImpl.java

@@ -0,0 +1,143 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.Consume;
+import com.happy.Model.Price;
+import com.happy.dao.ConsumeDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+@Repository("ConsumeDao")
+public class ConsumeDaoImpl implements ConsumeDao {
+
+    @Autowired
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+        return namedParameterJdbcTemplate;
+    }
+
+    public void setNamedParameterJdbcTemplate(
+            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+    }
+
+    public List<Consume> queryRecordByOrder(String order_no){
+        String sql="select * from consume where order_no=:order_no";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_no", order_no);
+        List<Consume> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Consume>(Consume.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Consume> queryRecordByCard(String card_number, String begin_time){
+        String sql="select * from consume where card_number=:card_number and use_amount>0 and begin_time like '"+ begin_time +"%' order by id desc";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("card_number", card_number);
+        List<Consume> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Consume>(Consume.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Consume> queryRecordByStu(String stu_number, String begin_time){
+        String sql="select * from consume where stu_number=:stu_number and use_amount>0 and begin_time like '"+ begin_time +"%' order by id desc";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", stu_number);
+        List<Consume> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Consume>(Consume.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public int insertComsume(Consume consume){
+        String sql = "insert into consume(stu_number, user_name, order_no, begin_time, start_code, device_code) values(:stu_number, :user_name, :order_no, :begin_time, :start_code, :device_code)";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", consume.getStu_number());
+        sps.addValue("user_name", consume.getUser_name());
+        sps.addValue("order_no", consume.getOrder_no());
+        sps.addValue("begin_time", consume.getBegin_time());
+        sps.addValue("start_code", consume.getStart_code());
+        sps.addValue("device_code", consume.getDevice_code());
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int updateBalance(String stu_number, double balance){
+        String sql = "update users set balance=:balance where stu_number=:stu_number";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", stu_number);
+        sps.addValue("balance", balance);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int updateConsume(String order_no, String pay_time, BigDecimal use_amount, BigDecimal use_size, int state){
+        String sql = "update consume set pay_time=:pay_time, use_amount=:use_amount, use_size=:use_size, state=:state where order_no=:order_no";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pay_time", pay_time);
+        sps.addValue("use_amount", use_amount);
+        sps.addValue("state", state);
+        sps.addValue("order_no", order_no);
+        sps.addValue("use_size", use_size);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int updateConsume2(String order_no, String pay_time, double use_amount, double use_size, int state){
+        String sql = "update consume set pay_time=:pay_time, use_amount=:use_amount, use_size=:use_size, state=:state where order_no=:order_no";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("pay_time", pay_time);
+        sps.addValue("use_amount", use_amount);
+        sps.addValue("state", state);
+        sps.addValue("order_no", order_no);
+        sps.addValue("use_size", use_size);
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public List<Price> water_price(String name){
+        String sql = "select * from price where name=:name";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("name", name);
+        List<Price> list = namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Price>(Price.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+}

+ 26 - 0
ConsumeService.java

@@ -0,0 +1,26 @@
+package com.happy.service;
+
+import com.happy.Model.Consume;
+import com.happy.Model.Price;
+
+import java.math.BigDecimal;
+import java.util.List;
+
+public interface ConsumeService {
+
+    public List<Consume> queryRecordByOrder(String order_no);
+
+    public List<Consume> queryRecordByCard(String card_number, String begin_time);
+
+    public List<Consume> queryRecordByStu(String stu_number, String begin_time);
+
+    public int insertComsume(Consume consume);
+
+    public int updateBalance(String stu_number, double balance);
+
+    public int updateConsume(String order_no, String pay_time, BigDecimal use_amount, BigDecimal use_size, int state);
+
+    public int updateConsume2(String order_no, String pay_time, double use_amount, double use_size, int state);
+
+    public List<Price> water_price(String name);
+}

+ 59 - 0
ConsumeServiceImpl.java

@@ -0,0 +1,59 @@
+package com.happy.service.impl;
+
+
+import com.happy.Model.Consume;
+import com.happy.Model.Price;
+import com.happy.dao.ConsumeDao;
+import com.happy.service.ConsumeService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.math.BigDecimal;
+import java.util.List;
+
+@Service("ConsumeService")
+public class ConsumeServiceImpl implements ConsumeService {
+
+    @Resource
+    public ConsumeDao consumeDao;
+
+    public ConsumeDao getConsumeDao() {
+        return consumeDao;
+    }
+
+    public void setConsumeDao(ConsumeDao consumeDao) {
+        this.consumeDao = consumeDao;
+    }
+
+    public List<Consume> queryRecordByOrder(String order_no){
+        return consumeDao.queryRecordByOrder(order_no);
+    }
+
+    public List<Consume> queryRecordByCard(String card_number, String begin_time){
+        return consumeDao.queryRecordByCard(card_number, begin_time);
+    }
+
+    public List<Consume> queryRecordByStu(String stu_number, String begin_time){
+        return consumeDao.queryRecordByStu(stu_number, begin_time);
+    }
+
+    public int insertComsume(Consume consume){
+        return consumeDao.insertComsume(consume);
+    }
+
+    public int updateBalance(String stu_number, double balance){
+        return consumeDao.updateBalance(stu_number, balance);
+    }
+
+    public int updateConsume(String order_no, String pay_time, BigDecimal use_amount, BigDecimal use_size, int state){
+        return consumeDao.updateConsume(order_no, pay_time, use_amount, use_size, state);
+    }
+
+    public int updateConsume2(String order_no, String pay_time, double use_amount, double use_size, int state){
+        return consumeDao.updateConsume2(order_no, pay_time, use_amount, use_size, state);
+    }
+
+    public List<Price> water_price(String name){
+        return consumeDao.water_price(name);
+    }
+}

+ 301 - 0
DataClient.java

@@ -0,0 +1,301 @@
+package testExport;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+
+import com.happy.Model.QueryUrlEnum;
+import com.happy.Unitil_elc.*;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+public class DataClient {
+
+    static String token = "c19ac221e0504552b6c2ebed4b2b069b";
+
+    public static void main(String[] args) {
+        getToken();
+        getUserAccountInfo();
+//        queryBuildingUsed();
+//        queryBuilding();
+//        queryDataCenter();
+//        customerRegister();
+//        getAccountInfo();
+//        customerInfoModify();
+//        getUserAccountInfo();
+//        recharege();
+//        disconnect();
+//        powerRealData();
+//        getPowerLastHistoryCumulant();
+//        getHistoryCumulant();
+//        getMonthBill();
+//        getLastHistoryCumulant();
+
+    }
+
+    /* 除获取token外的所有请求都需要带有token数据,demo中简单起见未做token的保存处理,实际使用中请自行实现 */
+    public static void getToken() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("operatorSecret", Globals.OPERATOR_SECRET);
+        try {
+           JSONObject jsonObject = queryData(QueryUrlEnum.QUERY_TOKEN.getUrl(), map, null);
+           String data = jsonObject.getString("data");
+           JSONObject dataObject = JSONObject.parseObject(data);
+           token = dataObject.getString("accessToken");
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 查询建筑日/小时用量数据
+    public static void queryBuildingUsed() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("buildingCode", "JHEQ-2#");//建筑编码
+        map.put("type", "1");//数据类型
+        map.put("dataTime", "2019091717");//数据时间
+        try {
+            queryData(QueryUrlEnum.QUERY_BUILDING_USED.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 查询建筑信息
+    public static void queryBuilding() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("buildingCode", "JHEQ-1#");//建筑编码
+        map.put("dataCenterCode", "000000");//数据中心编码
+        try {
+            queryData(QueryUrlEnum.QUERY_BUILDING.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 查询数据中心信息
+    public static void queryDataCenter() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("dataCenterCode", "000001");//数据中心编码
+        try {
+            queryData(QueryUrlEnum.QUERY_DATACENTER.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 电费月账单(水费月账单参数相同,只有接口不同,)
+    public static JSONObject getMonthBill(String user_id, String months) {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", user_id);//户号"HZJH201901220010"
+        map.put("queryTimes", months);//查询时间点 [yyyy-MM,yyyy-MM……]
+        Object money = null;
+        try {
+            return queryData(QueryUrlEnum.POWER_MONTH_BILL.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    // 账户信息
+    public static JSONObject getAccountInfo(String user_id) {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", user_id);//户号
+        try {
+            return queryData(QueryUrlEnum.ACCOUNT_INFO.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    // 用户信息
+    public static void getUserAccountInfo() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", "HZJH201903190022");//户号
+        try {
+            queryData(QueryUrlEnum.USER_INFO.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 用户注册
+    public static void customerRegister() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", "HZJH201903190022");//户号 注意不可重复
+        map.put("phone", "18888888888");//手机号
+        map.put("time", "2019-03-06 14:00:00");//注册时间
+        map.put("name", "李华");//名称
+        map.put("linkman", "李华");//联系人
+        try {
+            queryData(QueryUrlEnum.ACCOUNT_REGISTER.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 用户充值
+    public static void recharege() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", "HZJH201903190022");//户号 注意不可重复
+        map.put("tradeNo", "2018090101010103");//交易号 一个交易号只能充值一次
+        map.put("money", "1");//金额
+        try {
+            queryData(QueryUrlEnum.ACCOUNT_RECHARGE.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 用户信息修改
+    public static void customerInfoModify() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("userId", "HZJH201903190022");//户号 注意不可重复
+        map.put("phone", "18888888888");//手机号
+        map.put("linkman", "Li-Hua");//注册时间
+        map.put("name", "李华");//名称
+        try {
+            queryData(QueryUrlEnum.ACCOUNT_MODIFY.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 历史数据
+    public static void getHistoryCumulant() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("pointId", "610112W005000044");//表计编码
+        map.put("startTime", "20190813");//开始时间
+        map.put("endTime", "20190831");//结束时间
+        map.put("pointType", "1");//设备类型信息:1电表;2水表
+        map.put("type", "0");//数据类型   0, 所有(可以理解为,最小采集周期间隔的数据,如小时数据); 1, 按天,采集周期为天的数据
+        try {
+            queryData(QueryUrlEnum.HISTORY_CUMULANT.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 电表最新一条历史数据
+    public static void getPowerLastHistoryCumulant() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("pointId", "000000000001");//表计编码
+        try {
+            queryData(QueryUrlEnum.LAST_HISTORY.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    // 最新一条历史数据
+    public static void getLastHistoryCumulant() {
+        HashMap<String, String> map = new HashMap<>();
+        map.put("pointId", "00000090409190");//表计编码
+        map.put("pointType", "2");
+        try {
+            queryData(QueryUrlEnum.LAST_HISTORY_CUMULANT.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 拉合闸
+    public static void disconnect() {
+        HashMap<String, String> map = new HashMap<>();
+
+        map.put("pointId", "000000000001");//表计编号
+        map.put("operType", "1");//1.拉闸2.合闸
+        try {
+            queryData(QueryUrlEnum.REMOTE_DISCONNECT.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    // 电表实时信息  电表实时信息抄读时间较长,注意设置连接的超时时间
+    public static void powerRealData() {
+        String token = "23fff64f891e4bca8280224d916e789a";
+        HashMap<String, String> map = new HashMap<>();
+
+        map.put("pointId", "000000000001");//表计编号
+        try {
+            queryData(QueryUrlEnum.METER_REAL_INFO.getUrl(), map, token);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    /**
+     * 请求数据
+     *
+     * @param path    请求接口
+     * @param dataMap 所需的数据Map
+     */
+    public static JSONObject queryData(String path, Map<String, String> dataMap, String token) throws Exception {
+        // 加密data部分
+        String encode = CodeUtil.dataEncode(JSON.toJSONString(dataMap), Globals.DATA_SECRET, Globals.DATA_SECRET_IV);
+        /*组装必要参数 start */
+        String seq = "0001";
+        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
+        Map<String, String> map = new HashMap<>();
+        map.put("operatorId", Globals.OPERATOR_ID);
+        map.put("data", encode);
+        map.put("timeStamp", timeStamp);
+        map.put("seq", seq);
+        /*组装必要参数 end */
+        if (encode == null) return null;
+
+        /*生成签名 start*/
+        // 为防止+在收发过程中被变成空格,将加密后的密文中的所有空格替换一下
+        // 需要签名的参数: operatorId + 加密后的data + 时间戳 + 自增序列
+        String signSrc = Globals.OPERATOR_ID + encode.replaceAll(" ", "+") + timeStamp + seq;
+        String sig = CodeUtil.getSign(signSrc, Globals.SIGN_KEY);
+        //将签名放入参数Map
+        map.put("sig", sig);
+        /*生成签名 start*/
+        /*执行请求,使用可以附加token的doPost方*/
+        HttpClientHelper instance = HttpClientHelper.getInstance();
+        //token也可以放进参数列表
+        String result = instance.doPost(Globals.URL_PREFIX + (path.startsWith("/") ? path : ("/" + path)), map, token);
+        if (StringUtil.isEmpty(result)) return null;
+
+        /*解析数据 start*/
+        JSONObject jsonObject = JSON.parseObject(result);
+        // 失败
+        if (!"0".equals(jsonObject.getString("ret"))) {
+            printJsonMessage("send Error:", jsonObject);
+            return null;
+        }
+        // 验签,注意生成签名的参数顺序应和发送时一样
+        // 为防止'+'在收发过程中被变成' ',将加密后的密文中的所有空格替换一下
+        String resultSigStr = jsonObject.getString("operatorId") + jsonObject.getString("data").replaceAll(" ", "+")
+                + jsonObject.getString("msg") + jsonObject.getString("ret");
+        String resultSig = CodeUtil.getSign(resultSigStr, Globals.SIGN_KEY);
+        if (StringUtil.isNotEmpty(jsonObject.getString("sig")) && jsonObject.getString("sig").equals(resultSig)) {
+            // 解密数据,需要数据秘钥和秘钥初始化向量
+            String data = CodeUtil.dataDecode(jsonObject.getString("data"), Globals.DATA_SECRET, Globals.DATA_SECRET_IV);
+            jsonObject.put("data", data);
+        }
+        /*解析数据 end*/
+        // 打印 or 其他操作
+//        printJsonMessage("Send Message:", map);
+//        printJsonMessage("Receive Message:", result);
+//        printJsonMessage("Decode Message:", jsonObject);
+        return jsonObject;
+    }
+
+    public static void printJsonMessage(String prefix, Object obj) {
+        System.out.println(prefix + JsonUtil.JsonFormart(JSON.toJSONString(obj)));
+    }
+
+}

+ 37 - 0
DataSourceAspect.java

@@ -0,0 +1,37 @@
+package com.happy.myDataSource;
+
+import org.apache.commons.lang3.StringUtils;
+import org.aspectj.lang.JoinPoint;
+
+public class DataSourceAspect {
+	/**
+	 * 在进入service前执行
+	 * 
+	 * @param point
+	 *            切面对象
+	 */
+	public void before(JoinPoint point) {
+		// 获取当前执行的方法名
+		String methodName = point.getSignature().getName();
+		if (isSlave(methodName)) {
+			// 标记为读库
+			DynamicDataSourceHolder.markSlave();
+		} else {
+			// 标记为写库
+			DynamicDataSourceHolder.markMaster();
+		}
+
+	}
+
+	/**
+	 * 判断是否为读库
+	 * 
+	 * @param methodName
+	 * @return
+	 */
+	private boolean isSlave(String methodName) {
+		return StringUtils.startsWithAny(methodName, "query", "find", "get",
+				"comb", "list", "export", "load");
+	}
+
+}

+ 50 - 0
Device.java

@@ -0,0 +1,50 @@
+package com.happy.Model;
+
+public class Device {
+
+    public int id;
+    public String device_code;
+    public String device_campus;
+    public String device_build;
+    public String device_dom;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getDevice_code() {
+        return device_code;
+    }
+
+    public void setDevice_code(String device_code) {
+        this.device_code = device_code;
+    }
+
+    public String getDevice_campus() {
+        return device_campus;
+    }
+
+    public void setDevice_campus(String device_campus) {
+        this.device_campus = device_campus;
+    }
+
+    public String getDevice_build() {
+        return device_build;
+    }
+
+    public void setDevice_build(String device_build) {
+        this.device_build = device_build;
+    }
+
+    public String getDevice_dom() {
+        return device_dom;
+    }
+
+    public void setDevice_dom(String device_dom) {
+        this.device_dom = device_dom;
+    }
+}

+ 12 - 0
DictionaryCompare.java

@@ -0,0 +1,12 @@
+package com.happy.Until.weixin;
+
+import java.util.Comparator;
+
+/**
+ * 按字典序排序
+ */
+class DictionaryCompare implements Comparator<String> {
+	public int compare(String o1, String o2) {
+		return o1.compareTo(o2);
+	}
+}

+ 43 - 0
DynamicDataSourceHolder.java

@@ -0,0 +1,43 @@
+package com.happy.myDataSource;
+
+public class DynamicDataSourceHolder {
+	// 写库数据源key
+	private static final String MASTER = "master";
+	// 读库数据源key
+	private static final String SLAVE = "slave";
+	// 使用ThreadLocal记录当前数据源Key
+	private static final ThreadLocal<String> holder = new ThreadLocal<String>();
+
+	/**
+	 * 设置数据源key
+	 * 
+	 * @param key
+	 */
+	public static void putDataSourceKey(String key) {
+		holder.set(key);
+	}
+
+	/**
+	 * 获取数据源key
+	 * 
+	 * @return
+	 */
+	public static Object getDataSourceKey() {
+		return holder.get();
+	}
+
+	/**
+	 * 标记写库
+	 */
+	public static void markMaster() {
+		putDataSourceKey(MASTER);
+	}
+
+	/**
+	 * 标记读库
+	 */
+	public static void markSlave() {
+		putDataSourceKey(SLAVE);
+	}
+
+}

+ 12 - 0
DynamicDatasource.java

@@ -0,0 +1,12 @@
+package com.happy.myDataSource;
+
+import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
+
+public class DynamicDatasource extends AbstractRoutingDataSource {
+
+	@Override
+	protected Object determineCurrentLookupKey() {
+		// 使用DynamicDataSourceHolder保证线程的安全,并获得数据源的Key
+		return DynamicDataSourceHolder.getDataSourceKey();
+	}
+}

+ 296 - 0
Elec.java

@@ -0,0 +1,296 @@
+package com.happy.action;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.happy.Model.Recharge;
+import com.happy.Model.Users;
+import com.happy.Model.WeiXinUtil;
+import com.happy.Model.weixin.PayResult;
+import com.happy.Model.weixin.WechatUnifiedOrder;
+import com.happy.Until.HttpUtils;
+import com.happy.Until.ResUtil;
+import com.happy.Until.ResponseUtil;
+import com.happy.Until.weixin.EndPay;
+import com.happy.Until.weixin.JaxbUtil;
+import com.happy.Until.weixin.PayWxUtil;
+import com.happy.Until.weixin.TongYiReturn;
+import com.happy.common.http.HttpsClient;
+import com.happy.service.ConsumeService;
+import com.happy.service.RechargeService;
+import com.happy.service.UserService;
+import com.happy.service.WxMenuService;
+import com.opensymphony.xwork2.ActionSupport;
+import net.sf.json.JSONObject;
+import org.apache.struts2.ServletActionContext;
+import org.apache.struts2.interceptor.ServletRequestAware;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.BufferedReader;
+import java.io.PrintWriter;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class Elec extends ActionSupport implements ServletRequestAware {
+
+    private HttpServletRequest request;
+    public HttpServletResponse response;
+
+    public String code;
+    public String stu_number;
+    public String re_time;
+
+    @Resource
+    public UserService userService;
+    @Resource
+    public ConsumeService consumeService;
+    @Resource
+    public RechargeService rechargeService;
+    @Resource
+    public WxMenuService wxMenuService;
+
+    public HttpServletRequest getRequest() {
+        return request;
+    }
+
+    public void setRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public void setServletRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public HttpServletResponse getResponse() {
+        return response;
+    }
+
+    public void setResponse(HttpServletResponse response) {
+        this.response = response;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public String getRe_time() {
+        return re_time;
+    }
+
+    public void setRe_time(String re_time) {
+        this.re_time = re_time;
+    }
+
+    public String Pay() throws Exception {
+        HttpSession session = request.getSession();
+        Gson gson=new Gson();
+        JSONObject resultJson = new JSONObject();
+        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
+                "appid="+ WeiXinUtil.appid_elc +
+                "&secret="+ WeiXinUtil.screct_elc +
+                "&js_code="+code+
+                "&grant_type=authorization_code";
+        if (code==null){
+            resultJson.put("mess", "code不能为空");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        String jsons = HttpsClient.sendPost(url, "");
+        HashMap<String, String> userMap = gson.fromJson(jsons.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
+        String open_id = "";
+        try{
+            open_id = userMap.get("openid").toString();
+
+        }catch (Exception e){
+            resultJson.put("mess", "code超时");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        List<Users> u = userService.queryByopenid(open_id);  // 查找是不是会员,不是会员不能充值
+        String num = request.getParameter("num");
+        session.setAttribute("num", num); // 存入金额session中
+        if (u != null  ) {
+            String ip = request.getParameter("ip");
+            double money = Double.parseDouble(request.getParameter("num"));
+            int a = (int) (money * 100);
+            WechatUnifiedOrder w = new WechatUnifiedOrder();
+            w.setAppid(WeiXinUtil.appid);
+            w.setAttach("chuanghai");
+            w.setBody("chuanghai");
+            w.setMch_id(WeiXinUtil.account_elc);
+            w.setNonce_str(PayWxUtil.getNonceStr());// 随机支付串
+            w.setNotify_url(WeiXinUtil.ip + "elpayResulet.action");// 支付结果回调地址
+            w.setOpenid(open_id);
+            w.setOut_trade_no("" + new Date().getTime());
+            w.setSpbill_create_ip(ip);
+            w.setTotal_fee(a);
+            w.setTrade_type("JSAPI");
+            Map<String, String> params = new HashMap<String, String>();
+            params.put("attach", w.getAttach());
+            params.put("appid", w.getAppid());
+            params.put("mch_id", w.getMch_id());
+            params.put("nonce_str", w.getNonce_str());
+            params.put("body", w.getBody());
+            params.put("out_trade_no", w.getOut_trade_no());
+            params.put("total_fee", w.getTotal_fee() + "");
+            params.put("spbill_create_ip", w.getSpbill_create_ip());
+            params.put("notify_url", w.getNotify_url());
+            params.put("trade_type", w.getTrade_type());
+            params.put("openid", w.getOpenid());
+            w.setSign(PayWxUtil.getSign(params, WeiXinUtil.APIid_elc));
+            params.put("sign", w.getSign());
+            String retXml = JaxbUtil.getRequestXml(params);
+            String msg = HttpUtils.post("https://api.mch.weixin.qq.com/pay/unifiedorder", retXml);
+            System.out.println("msg: "+ msg);
+            if (msg.indexOf("FAIL") > -1) {
+                JSONObject json = new JSONObject();
+                json.put("pay", "error");
+                ResponseUtil.write(json, ServletActionContext.getResponse());
+                return null;
+            } else {
+                JaxbUtil requestBinder = new JaxbUtil(TongYiReturn.class, JaxbUtil.CollectionWrapper.class);
+                TongYiReturn to = requestBinder.fromXml(msg);
+                if (to.getReturn_code().equals("SUCCESS") && to.getResult_code().equals("SUCCESS")) {
+                    EndPay pay = new EndPay();
+                    pay.setAppId(WeiXinUtil.appid_elc);
+                    pay.setSignType("MD5");
+                    pay.setTimeStamp(System.currentTimeMillis() / 1000 + "");
+                    pay.setPrepay_id(to.getPrepay_id());
+                    pay.setNonceStr(PayWxUtil.getNonceStr());
+                    Map<String, String> requestMap = new HashMap<String, String>();
+                    requestMap.put("appId", pay.getAppId());
+                    requestMap.put("timeStamp", pay.getTimeStamp());
+                    requestMap.put("nonceStr", pay.getNonceStr());
+                    requestMap.put("package", "prepay_id=" + pay.getPrepay_id());
+                    requestMap.put("signType", "MD5");
+                    pay.setPaySign(PayWxUtil.getSign(requestMap, WeiXinUtil.APIid_elc));
+                    // requestMap.put("sign",pay.getPaySign());
+                    // String ret = JaxbUtil.getRequestXml(requestMap);
+                    // System.out.println(ret);
+                    JSONObject json = new JSONObject();
+                    json.put("pay", pay);
+                    if (session.getAttribute("p_biao") != null) { // 说明时从打转盘页面进来的,支付完成后继续调到转盘页面
+                        json.put("p_biao", 1);
+                        session.removeAttribute("p_biao");
+                    } else {
+                        json.put("p_biao", 0);
+                    }
+                    ResUtil.write(json, ServletActionContext.getResponse());
+                }
+            }
+        } else { // 说明不是会员
+            JSONObject json = new JSONObject();
+            json.put("pay", 1);
+            ResUtil.write(json, ServletActionContext.getResponse());
+        }
+
+        return null;
+    }
+
+    // 第五步:支付页面用户输完密码后微信会把支付结果回调到这里,我们根据需要存储支付记录,和执行不同的方法
+    public String payResulet() throws Exception { // 微信支付结果通知
+//		System.out.println("进来了");
+        BufferedReader reader = null;// BufferedReader 字符输入流
+
+        reader = request.getReader();
+        String line = "";
+        String xmlString = null;
+        StringBuffer inputString = new StringBuffer();
+
+        while ((line = reader.readLine()) != null) {
+            inputString.append(line);
+        }
+        xmlString = inputString.toString();
+        request.getReader().close();
+
+        JaxbUtil requestBinder = new JaxbUtil(PayResult.class, PayResult.class);
+        PayResult result = requestBinder.fromXml(xmlString);// Xml到Java,用fromXML()方法
+
+        if (result.getResult_code().equals("SUCCESS")) { // 交易成功,支付结果转换为对象
+            String account = result.getTransaction_id();// 微信支付订单号
+
+            System.out.println("支付成功了");
+            System.out.println("result=" + result.toString());
+
+            Recharge pays = rechargeService.findPayByNo(account);// 根据 微信支付订单号 查找支付记录信息
+
+            if (pays != null) { // 有交易记录 发送成功消息给商家
+                String returnMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
+                HttpServletResponse response = ServletActionContext.getResponse();
+                response.setContentType("text/html;charset=utf-8");
+                PrintWriter out = response.getWriter();
+                out.println(returnMsg);
+                out.flush();
+                out.close();
+//				System.out.println("pay不为空");
+            } else { // 交易记录开始记录
+//				if(openid.equals(result.getOpenid()) && num == result.getTotal_fee() / 100){		//支付成功
+                // 获得交易支付成功用户的信息
+                Recharge pay1 = new Recharge();
+                List<Users> u = userService.queryByopenid(result.getOpenid());  // 查找充值的会员信息
+                pay1.setAccount((double) result.getTotal_fee() / 100);
+                System.out.println("金额:"+ result.getTotal_fee());
+                pay1.setUser_name(u.get(0).getUser_name());
+                pay1.setStu_number(u.get(0).getStu_number());
+                pay1.setCard_number(u.get(0).getCard_number());
+                pay1.setOrder_num(new String(account.getBytes("utf-8")));
+                SimpleDateFormat simp = new SimpleDateFormat("yyyyMMddHHmmss");
+                SimpleDateFormat simp1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+
+                Date date = simp.parse(result.getTime_end());
+                String time = simp1.format(date);
+                pay1.setRe_time(time); // 支付结束时间
+
+                System.out.println("金额:"+pay1.getAccount());
+                rechargeService.insertRecharge2(pay1);
+
+                // userService.update2((double) result.getTotal_fee() / 10, u.getId());
+                String returnMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
+                HttpServletResponse response = ServletActionContext.getResponse();
+                response.setContentType("text/html;charset=utf-8");
+                PrintWriter out = response.getWriter();
+                out.println(returnMsg);
+                out.flush();
+                out.close(); // 发送成功消息给商家
+//				}
+                // }
+            }
+        }
+        return null;
+    }
+
+    public String queyRecordEle() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        if (stu_number!=null && re_time!=null) {
+            List<Recharge> record = rechargeService.queryRecordByStu(stu_number, re_time);
+            if (record!=null) {
+                resultJson.put("mess", "返回成功");
+                resultJson.put("data", record);
+                ResUtil.write(resultJson, ServletActionContext.getResponse());
+            }
+            resultJson.put("mess", "未查到记录");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        resultJson.put("mess", "学号不能为空");
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+}

+ 18 - 0
ElecDao.java

@@ -0,0 +1,18 @@
+package com.happy.dao;
+
+import com.happy.Model.Build_elec;
+
+import java.util.List;
+
+public interface ElecDao {
+
+    public List<Build_elec> querySchool();
+
+    public List<Build_elec> queryBuild(String school);
+
+    public List<Build_elec> queryFloors(String school, String build);
+
+    public List<Build_elec> queryDom(String school, String build, String floors);
+
+    public List<Build_elec> queryUser_id(String school, String dom);
+}

+ 87 - 0
ElecDaoImpl.java

@@ -0,0 +1,87 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.Build_elec;
+import com.happy.Model.Consume;
+import com.happy.dao.ElecDao;
+import org.apache.commons.fileupload.util.LimitedInputStream;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository("ElecDao")
+public class ElecDaoImpl implements ElecDao {
+
+    @Autowired
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+        return namedParameterJdbcTemplate;
+    }
+
+    public void setNamedParameterJdbcTemplate(
+            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+    }
+
+    public List<Build_elec> querySchool(){
+        String sql = "select distinct school as school from `build_elec`;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryBuild(String school){
+        String sql = "select distinct build as build from `build_elec` where school=:school;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("school", school);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryFloors(String school, String build){
+        String sql = "select distinct floors as floors from `build_elec` where school=:school and build=:build;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("school", school);
+        sps.addValue("build", build);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryDom(String school, String build, String floors){
+        String sql = "select distinct dom as dom from `build_elec` where school=:school and build=:build and floors=:floors;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("school", school);
+        sps.addValue("build", build);
+        sps.addValue("floors", floors);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public List<Build_elec> queryUser_id(String school, String dom){
+        String sql = "select * from `build_elec` where school=:school and dom=:dom;";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("school", school);
+        sps.addValue("dom", dom);
+        List<Build_elec> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Build_elec>(Build_elec.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+}

+ 18 - 0
ElecService.java

@@ -0,0 +1,18 @@
+package com.happy.service;
+
+import com.happy.Model.Build_elec;
+
+import java.util.List;
+
+public interface ElecService {
+
+    public List<Build_elec> querySchool();
+
+    public List<Build_elec> queryBuild(String school);
+
+    public List<Build_elec> queryFloors(String school, String build);
+
+    public List<Build_elec> queryDom(String school, String build, String floors);
+
+    public List<Build_elec> queryUser_id(String school, String dom);
+}

+ 44 - 0
ElecServiceImpl.java

@@ -0,0 +1,44 @@
+package com.happy.service.impl;
+
+import com.happy.Model.Build_elec;
+import com.happy.dao.ElecDao;
+import com.happy.service.ElecService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+
+@Service("ElecService")
+public class ElecServiceImpl implements ElecService {
+
+    @Autowired
+    public ElecDao elecDao;
+
+    public ElecDao getElecDao() {
+        return elecDao;
+    }
+
+    public void setElecDao(ElecDao elecDao) {
+        this.elecDao = elecDao;
+    }
+
+    public List<Build_elec> querySchool(){
+        return elecDao.querySchool();
+    }
+
+    public List<Build_elec> queryBuild(String school){
+        return elecDao.queryBuild(school);
+    }
+
+    public List<Build_elec> queryFloors(String school, String build){
+        return elecDao.queryFloors(school, build);
+    }
+
+    public List<Build_elec> queryDom(String school, String build, String floors){
+        return elecDao.queryDom(school, build, floors);
+    }
+
+    public List<Build_elec> queryUser_id(String school, String dom){
+        return elecDao.queryUser_id(school, dom);
+    }
+}

+ 51 - 0
EndPay.java

@@ -0,0 +1,51 @@
+package com.happy.Until.weixin;
+/**
+ * 最后调用接口传的数据实体类;
+ * @author QT-666
+ *
+ */
+public class EndPay {
+      private String appId;//商户注册具有支付权限的公众号成功后即可获得
+      private String timeStamp;//当前的时间,其他详见时间戳规则
+      private String nonceStr;//随机字符串,不长于32位。推荐随机数生成算法
+      private String prepay_id;//统一下单接口返回的prepay_id参数值,提交格式如:prepay_id=***
+      private String signType;//签名算法,暂支持MD5
+      private String paySign;//签名,详见签名生成算法
+	public String getAppId() {
+		return appId;
+	}
+	public void setAppId(String appId) {
+		this.appId = appId;
+	}
+	public String getTimeStamp() {
+		return timeStamp;
+	}
+	public void setTimeStamp(String timeStamp) {
+		this.timeStamp = timeStamp;
+	}
+	public String getNonceStr() {
+		return nonceStr;
+	}
+	public void setNonceStr(String nonceStr) {
+		this.nonceStr = nonceStr;
+	}
+	public String getPrepay_id() {
+		return prepay_id;
+	}
+	public void setPrepay_id(String prepay_id) {
+		this.prepay_id = prepay_id;
+	}
+	public String getSignType() {
+		return signType;
+	}
+	public void setSignType(String signType) {
+		this.signType = signType;
+	}
+	public String getPaySign() {
+		return paySign;
+	}
+	public void setPaySign(String paySign) {
+		this.paySign = paySign;
+	}
+      
+}

+ 18 - 0
GloablExceptionHandler.java

@@ -0,0 +1,18 @@
+package com.happy.interceptor;
+
+import com.alibaba.fastjson.JSONObject;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+@ControllerAdvice
+public class GloablExceptionHandler {
+
+    @ResponseBody
+    @ExceptionHandler(Exception.class)
+    public Object handleException(Exception e) {
+        String msg = e.getMessage();
+        JSONObject jsonObject = JSONObject.parseObject(msg);
+        return jsonObject;
+    }
+}

+ 34 - 0
Globals.java

@@ -0,0 +1,34 @@
+package testExport;
+
+
+/**
+ * 全局变量定义
+ */
+public interface Globals {
+
+    /**
+     * 运营商标识
+     */
+    String OPERATOR_ID = "000000002";
+    /**
+     * 运营商秘钥
+     */
+    String OPERATOR_SECRET = "SBC88d0ItR3w6oCTY";
+    /**
+     * 运营商数据秘钥
+     */
+    String DATA_SECRET = "Epc3hhs0imtVhPSu";
+    /**
+     * 数据秘钥初始化向量
+     */
+    String DATA_SECRET_IV = "r57m1sr8Tg2E302L";
+    /**
+     * 签名秘钥
+     */
+    String SIGN_KEY = "ikAhygeGCRnEdhjgBKf";
+    /**
+     * 请求地址前缀
+     */
+    String URL_PREFIX = "http://183.129.139.222:10022/ems-share-api";
+
+}

+ 350 - 0
HttpClientHelper.java

@@ -0,0 +1,350 @@
+package com.happy.Unitil_elc;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpHost;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.config.SocketConfig;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.message.BasicHeader;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.protocol.HTTP;
+import org.apache.http.ssl.SSLContexts;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLContext;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+
+public class HttpClientHelper {
+
+
+    private static final Logger logger = LoggerFactory.getLogger(HttpClientHelper.class);
+    private static PoolingHttpClientConnectionManager poolConnManager = null;
+    private int maxTotalPool = 200;
+    private int maxConPerRoute = 20;
+    private int socketTimeout = 100000;
+    private int connectionRequestTimeout = 90000;
+    private int connectTimeout = 90000;
+
+    // 代理信息
+    public static String proxy_ip;
+    public static int proxy_port;
+
+    private static HttpClientHelper httpClientHelper = null;
+
+    private HttpClientHelper() {
+        init();
+    }
+
+    private static synchronized void syncInit() {
+        if (httpClientHelper == null) {
+            httpClientHelper = new HttpClientHelper();
+        }
+    }
+
+    public static HttpClientHelper getInstance(String proxyIp, Integer proxyPort) {
+        proxy_port = proxyPort;
+        proxy_ip = proxyIp;
+        if (httpClientHelper == null) {
+            syncInit();
+        }
+        return httpClientHelper;
+    }
+
+    public static HttpClientHelper getInstance() {
+        if (httpClientHelper == null) {
+            syncInit();
+        }
+        return httpClientHelper;
+    }
+
+    public PoolingHttpClientConnectionManager getConnManager() {
+        PoolingHttpClientConnectionManager cm = null;
+        try {
+            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
+            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
+            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http",
+                    PlainConnectionSocketFactory.getSocketFactory()).register("https",
+                    sslsf).build();
+            cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
+            // 将最大连接数增加到200
+            cm.setMaxTotal(maxTotalPool);
+            // 将每个路由基础的连接增加到20
+            cm.setDefaultMaxPerRoute(maxConPerRoute);
+        } catch (Exception e) {
+            logger.error("InterfacePhpUtilManager init Exception" + e.toString());
+        }
+        return cm;
+    }
+
+    public void init() {
+        try {
+            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
+            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE);
+            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http",
+                    PlainConnectionSocketFactory.getSocketFactory()).register("https",
+                    sslsf).build();
+            poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
+            // Increase max total connection to 200
+            poolConnManager.setMaxTotal(maxTotalPool);
+            // Increase default max connection per route to 20
+            poolConnManager.setDefaultMaxPerRoute(maxConPerRoute);
+            SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(socketTimeout).build();
+            poolConnManager.setDefaultSocketConfig(socketConfig);
+        } catch (Exception e) {
+            logger.error("InterfacePhpUtilManager init Exception" + e.toString());
+        }
+    }
+
+    public CloseableHttpClient getConnection() {
+        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout).setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
+        HttpClientBuilder httpClientBuilder = HttpClients.custom();
+        httpClientBuilder.setConnectionManager(poolConnManager).setDefaultRequestConfig(requestConfig);// set proxy
+        if (!StringUtil.isEmpty(proxy_ip) && proxy_port > 0) {
+            HttpHost proxy = new HttpHost(proxy_ip, proxy_port);
+            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
+            httpClientBuilder.setRoutePlanner(routePlanner);
+        }
+
+        CloseableHttpClient httpClient = httpClientBuilder.build();
+        if (poolConnManager != null && poolConnManager.getTotalStats() != null) {
+            logger.info("now client pool " + poolConnManager.getTotalStats().toString());
+        }
+        return httpClient;
+    }
+
+    /**
+     * 发送 GET 请求(HTTP),不带输入数据
+     */
+    public String doGet(String url) {
+        return doGet(url, new HashMap<String,String>());
+    }
+
+    /**
+     * 发送 GET 请求(HTTP),K-V形式
+     */
+    public String doGet(String url, Map<String, String> params) {
+        String apiUrl = url;
+        StringBuffer param = new StringBuffer();
+        int i = 0;
+        for (String key : params.keySet()) {
+            if (i == 0) {
+                param.append("?");
+            } else {
+                param.append("&");
+            }
+            param.append(key).append("=").append(params.get(key));
+            i++;
+        }
+        apiUrl += param;
+        logger.info(apiUrl);
+        String result = null;
+        CloseableHttpClient httpClient = getConnection();
+        CloseableHttpResponse response = null;
+        HttpGet httpPost = null;
+        try {
+            httpPost = new HttpGet(apiUrl);
+            response = httpClient.execute(httpPost);
+            int status = response.getStatusLine().getStatusCode();
+            logger.info("http request url : " + url + " status : " + status);
+
+            if (status >= 200 && status < 300) {
+                HttpEntity entity = response.getEntity();
+                if (entity != null) {
+                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
+                    logger.info("Request result : " + result);
+                }
+            }
+            EntityUtils.consume(response.getEntity());
+            response.close();
+            return result;
+
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            httpPost.releaseConnection();
+            if (response != null) {
+                try {
+                    EntityUtils.consume(response.getEntity());
+                    response.close();
+                } catch (IOException e) {
+                    logger.error(e.getMessage(), e);
+                }
+            }
+        }
+        return result;
+    }
+
+    public String doPost(String url) {
+        return doPost(url, new HashMap<String, String>());
+    }
+
+    /**
+     * 发送 POST json
+     *
+     * @param url 接口URL
+     */
+    public String doPostJson(String url, String jsonstr) {
+        String result = null;
+        HttpPost httpPost = new HttpPost(url);
+        CloseableHttpClient httpClient = getConnection();
+        CloseableHttpResponse response = null;
+        try {
+
+            StringEntity se = new StringEntity(jsonstr, Charset.forName("UTF-8"));
+            se.setContentType("text/json");
+            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
+            httpPost.setEntity(se);
+            response = httpClient.execute(httpPost);
+            int status = response.getStatusLine().getStatusCode();
+            logger.info("http request url : " + url + " status : " + status);
+            if (status >= 200 && status < 300) {
+                HttpEntity entity = response.getEntity();
+                if (entity != null) {
+                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
+                    logger.info("Request result : " + result);
+                }
+            }
+            EntityUtils.consume(response.getEntity());
+            response.close();
+            return result;
+
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            httpPost.releaseConnection();
+            if (response != null) {
+                try {
+                    EntityUtils.consume(response.getEntity());
+                    response.close();
+                } catch (IOException e) {
+                    logger.error(e.getMessage(), e);
+                }
+            }
+        }
+        return result;
+    }
+
+    /**
+     * 发送 POST 请求(HTTP),K-V形式
+     *
+     * @param url    接口URL
+     * @param params 参数map
+     * @return
+     */
+    public String doPost(String url, Map<String, String> params) {
+        String result = null;
+        HttpPost httpPost = new HttpPost(url);
+        CloseableHttpClient httpClient = getConnection();
+        CloseableHttpResponse response = null;
+        try {
+            List<NameValuePair> pairList = new ArrayList<>(params.size());
+            for (Map.Entry<String, String> entry : params.entrySet()) {
+                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
+                pairList.add(pair);
+            }
+            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
+            response = httpClient.execute(httpPost);
+            int status = response.getStatusLine().getStatusCode();
+            logger.info("http request url : " + url + " status : " + status);
+            if (status >= 200 && status < 300) {
+                HttpEntity entity = response.getEntity();
+                if (entity != null) {
+                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
+                    logger.info("Request result : " + result);
+                }
+            }
+            EntityUtils.consume(response.getEntity());
+            response.close();
+            return result;
+
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            httpPost.releaseConnection();
+            if (response != null) {
+                try {
+                    EntityUtils.consume(response.getEntity());
+                    response.close();
+                } catch (IOException e) {
+                    logger.error(e.getMessage(), e);
+                }
+            }
+        }
+        return result;
+    }
+    /**
+     * 发送 POST 请求(HTTP),K-V形式
+     *
+     * @param url    接口URL
+     * @param params 参数map
+     * @return
+     */
+    public String doPost(String url, Map<String, String> params, String token) {
+        String result = null;
+        HttpPost httpPost = new HttpPost(url);
+        CloseableHttpClient httpClient = getConnection();
+        CloseableHttpResponse response = null;
+        try {
+            List<NameValuePair> pairList = new ArrayList<>(params.size());
+            for (Map.Entry<String, String> entry : params.entrySet()) {
+                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
+                pairList.add(pair);
+            }
+            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
+            httpPost.addHeader("token", token);
+            response = httpClient.execute(httpPost);
+            int status = response.getStatusLine().getStatusCode();
+            logger.info("http request url : " + url + " status : " + status);
+            if (status >= 200 && status < 300) {
+                HttpEntity entity = response.getEntity();
+                if (entity != null) {
+                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
+                    logger.info("Request result : " + result);
+                }
+            }
+            EntityUtils.consume(response.getEntity());
+            response.close();
+            return result;
+
+        } catch (IOException e) {
+            logger.error(e.getMessage(), e);
+        } finally {
+            httpPost.releaseConnection();
+            if (response != null) {
+                try {
+                    EntityUtils.consume(response.getEntity());
+                    response.close();
+                } catch (IOException e) {
+                    logger.error(e.getMessage(), e);
+                }
+            }
+        }
+        return result;
+    }
+
+}

+ 200 - 0
HttpUtils.java

@@ -0,0 +1,200 @@
+package com.happy.Until;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import org.apache.http.HttpEntity;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * http post 提交 和 get请求
+ * 
+ * @author QT-666
+ * 
+ */
+public class HttpUtils {
+	private static RequestConfig requestConfig = RequestConfig.custom()
+			.setSocketTimeout(15000).setConnectTimeout(15000)
+			.setConnectionRequestTimeout(15000).build();
+
+	public static String get(String url, Map<String, String> params) {
+		CloseableHttpClient httpClient = null;
+		HttpGet httpGet = null;
+		String re = "";
+		try {
+			httpClient = HttpClients.createDefault();
+			RequestConfig requestConfig = RequestConfig.custom()
+					.setSocketTimeout(20000).setConnectTimeout(20000).build();
+			String ps = "";
+			for (String pKey : params.keySet()) {
+				if (!"".equals(ps)) {
+					ps = ps + "&";
+				}
+				ps = pKey + "=" + params.get(pKey);
+			}
+			if (!"".equals(ps)) {
+				url = url + "?" + ps;
+			}
+			httpGet = new HttpGet(url);
+			httpGet.setConfig(requestConfig);
+			CloseableHttpResponse response = httpClient.execute(httpGet);
+			HttpEntity httpEntity = response.getEntity();
+			re = EntityUtils.toString(httpEntity, "utf-8");
+		} catch (ClientProtocolException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				if (httpGet != null) {
+					httpGet.releaseConnection();
+				}
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return re;
+	}
+
+	/**
+	 * 发送http post请求
+	 * 
+	 * @param
+	 *
+	 * @param
+	 *
+	 */
+	public static String post(String url, Map<String, String> params) throws IOException {
+		CloseableHttpClient httpClient = null;
+		HttpPost httpPost = null;
+		String re = "";
+		try {
+			httpClient = HttpClients.createDefault();
+			RequestConfig requestConfig = RequestConfig.custom()
+					.setSocketTimeout(20000).setConnectTimeout(20000).build();
+			httpPost = new HttpPost(url);
+			httpPost.setConfig(requestConfig);
+			List<NameValuePair> ps = new ArrayList<NameValuePair>();
+			for (String pKey : params.keySet()) {
+				ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
+			}
+			httpPost.setEntity(new UrlEncodedFormEntity(ps));
+			CloseableHttpResponse response = httpClient.execute(httpPost);
+			HttpEntity httpEntity = response.getEntity();
+			re = EntityUtils.toString(httpEntity, "utf-8");
+		} catch (ClientProtocolException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				if (httpPost != null) {
+					httpPost.releaseConnection();
+				}
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return re;
+	}
+
+	/**
+	 * 发送post请求Https,参数是字符串
+	 *
+	 * @param httpPost
+	 * @return
+	 */
+	public static String post(String url, String body) throws Exception {
+		String str = "";
+		CloseableHttpClient httpClient = null;
+		HttpPost httpPost = null;
+		try {
+			httpClient = HttpClients.createDefault();
+			RequestConfig requestConfig = RequestConfig.custom()
+					.setSocketTimeout(20000).setConnectTimeout(20000).build();
+			httpPost = new HttpPost(url);
+			httpPost.setConfig(requestConfig);
+			httpPost.setEntity(new StringEntity(body, "utf-8"));
+			CloseableHttpResponse response = httpClient.execute(httpPost);
+			HttpEntity httpEntity = response.getEntity();
+			str = EntityUtils.toString(httpEntity, "utf-8");
+
+		} catch (ClientProtocolException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				if (httpPost != null) {
+					httpPost.releaseConnection();
+				}
+				if (httpClient != null) {
+					httpClient.close();
+				}
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return new String(str.getBytes("iso-8859-1"));
+	}
+
+
+
+	public static String get(String strURL) throws Exception {
+		URL url = new URL(strURL);
+		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
+		httpConn.setRequestMethod("GET");
+		httpConn.connect();
+
+		BufferedReader reader = new BufferedReader(new InputStreamReader(
+				httpConn.getInputStream(), "utf-8"));
+		String line;
+		StringBuffer buffer = new StringBuffer();
+		while ((line = reader.readLine()) != null) {
+			buffer.append(line);
+		}
+		reader.close();
+		httpConn.disconnect();
+
+		return buffer.toString();
+	}
+
+	public static void main(String[] args) throws Exception {
+		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
+		String time = df.format(new Date());
+		Map<String, String> req = new HashMap<>();
+		req.put("operator_id", "000000002");
+		req.put("operator_secret", "SBC88d0ItR3w6oCTY");
+		req.put("data_secret", "Epc3hhs0imtVhPSu");
+		req.put("data_secret_iv", "r57m1sr8Tg2E302L");
+		req.put("sign_key", "ikAhygeGCRnEdhjgBKf");
+		req.put("timeStamp", time);
+		req.put("seq", "0001");
+		String msg = post("http://183.129.139.222:10022/ems-share-api/queryToken", req);
+		System.out.println("aaa: "+msg);
+	}
+}

+ 377 - 0
HttpsClient.java

@@ -0,0 +1,377 @@
+package com.happy.common.http;
+
+import com.alibaba.fastjson.JSONObject;
+import com.happy.common.wx.WxConfig;
+import com.happy.common.wx.WxConstants;
+import com.happy.common.wx.WxUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * HttpsClient类
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public class HttpsClient {
+
+    /**
+     * GET请求方式
+     */
+    public static final String METHOD_GET = "GET";
+    /**
+     * POST请求方式
+     */
+    public static final String METHOD_POST = "POST";
+    /**
+     * 连接超时时间
+     */
+    private static Integer CONNECTION_TIMEOUT = WxConfig.connectionTimeout;
+    /**
+     * 请求超时时间
+     */
+    private static Integer READ_TIMEOUT = WxConfig.readTimeout;
+
+    /**
+     * 发起https请求
+     * @param requestUrl 请求地址
+     * @param requestMethod 请求方式(Get或者post)
+     * @param postData 提交数据
+     * @return JSONObject
+     */
+    public static JSONObject httpsRequestReturnJSONObject(String requestUrl, String requestMethod, String postData) throws Exception{
+        JSONObject  jsonObject = JSONObject.parseObject(HttpsClient.httpsRequestReturnString(requestUrl,requestMethod,postData));
+        System.out.println("jsonObjectDate:  " + jsonObject);
+        return jsonObject;
+    }
+
+
+    /**
+     * 发起https请求
+     * @param requestUrl 请求地址
+     * @param requestMethod 请求方式(Get或者post)
+     * @param postData 提交数据
+     * @return String
+     */
+    public static String httpsRequestReturnString(String requestUrl, String requestMethod, String postData) throws Exception{
+        String response;
+        HttpsURLConnection httpsUrlConnection = null;
+        try{
+            //创建https请求证书
+            TrustManager[] tm={new MyX509TrustManager()};
+            //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
+            SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
+            sslContext.init(null, tm, new java.security.SecureRandom());
+            SSLSocketFactory ssf=sslContext.getSocketFactory();
+
+            // 创建URL对象
+            URL url= new URL(requestUrl);
+            // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
+            httpsUrlConnection=(HttpsURLConnection)url.openConnection();
+            //设置ssl证书
+            httpsUrlConnection.setSSLSocketFactory(ssf);
+
+            //设置header信息
+            httpsUrlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+            //设置User-Agent信息
+            httpsUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
+            //设置可接受信息
+            httpsUrlConnection.setDoOutput(true);
+            //设置可输入信息
+            httpsUrlConnection.setDoInput(true);
+            //不使用缓存
+            httpsUrlConnection.setUseCaches(false);
+            //设置请求方式(GET/POST)
+            httpsUrlConnection.setRequestMethod(requestMethod);
+            //设置连接超时时间
+            if (CONNECTION_TIMEOUT > 0) {
+                httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
+            } else {
+                //默认10秒超时
+                httpsUrlConnection.setConnectTimeout(10000);
+            }
+            //设置请求超时
+            if (READ_TIMEOUT > 0) {
+                httpsUrlConnection.setReadTimeout(READ_TIMEOUT);
+            } else {
+                //默认10秒超时
+                httpsUrlConnection.setReadTimeout(10000);
+            }
+            //设置编码
+            httpsUrlConnection.setRequestProperty("Charsert", WxConstants.DEFAULT_CHARSET);
+
+            //判断是否需要提交数据
+            if(StringUtils.equals(requestMethod,HttpsClient.METHOD_POST) && StringUtils.isNotBlank(postData)){
+                //讲参数转换为字节提交
+                byte[] bytes = postData.getBytes(WxConstants.DEFAULT_CHARSET);
+                //设置头信息
+                httpsUrlConnection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
+                //开始连接
+                httpsUrlConnection.connect();
+                //防止中文乱码
+                OutputStream outputStream=httpsUrlConnection.getOutputStream();
+                outputStream.write(postData.getBytes(WxConstants.DEFAULT_CHARSET));
+                outputStream.flush();
+                outputStream.close();
+            }else{
+                //开始连接
+                httpsUrlConnection.connect();
+            }
+            response = WxUtil.getStreamString(httpsUrlConnection.getInputStream());
+        }catch (Exception e){
+            throw new Exception();
+        }finally {
+            if (httpsUrlConnection != null) {
+                // 关闭连接
+                httpsUrlConnection.disconnect();
+            }
+        }
+        return response;
+    }
+
+
+    public static void get(String url, Map<String, String> params){
+        CloseableHttpClient httpClient = null;
+        HttpGet httpGet = null;
+        try {
+            httpClient = HttpClients.createDefault();
+            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
+            String ps = "";
+            for (String pKey : params.keySet()) {
+                if(!"".equals(ps)){
+                    ps = ps + "&";
+                }
+                ps = pKey+"="+params.get(pKey);
+            }
+            if(!"".equals(ps)){
+                url = url + "?" + ps;
+            }
+            httpGet = new HttpGet(url);
+            httpGet.setConfig(requestConfig);
+            CloseableHttpResponse response = httpClient.execute(httpGet);
+            HttpEntity httpEntity = response.getEntity();
+            System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
+        } catch (ClientProtocolException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }finally{
+            try {
+                if(httpGet!=null){
+                    httpGet.releaseConnection();
+                }
+                if(httpClient!=null){
+                    httpClient.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    public static String get(String strURL) throws Exception{
+
+        URL url = new URL(strURL);
+        HttpURLConnection httpConn = (HttpURLConnection)
+                url.openConnection();
+        httpConn.setRequestMethod("GET");
+        httpConn.connect();
+        System.out.println("bbb: "+httpConn.getResponseCode());
+        BufferedReader reader = new BufferedReader(new InputStreamReader(
+                httpConn.getInputStream(),"utf-8"));
+        String line;
+        StringBuffer buffer = new StringBuffer();
+        while ((line = reader.readLine()) != null) {
+            buffer.append(line);
+        }
+        reader.close();
+        httpConn.disconnect();
+
+        return buffer.toString();
+    }
+
+    /**
+     * 发送 post请求
+     * @param
+     * @param
+     */
+    public static void post(String url, Map<String, String> params){
+        CloseableHttpClient httpClient = null;
+        HttpPost httpPost = null;
+        try {
+            httpClient = HttpClients.createDefault();
+            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
+            httpPost = new HttpPost(url);
+            httpPost.setConfig(requestConfig);
+            List<NameValuePair> ps = new ArrayList<NameValuePair>();
+            for (String pKey : params.keySet()) {
+                ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
+            }
+            httpPost.setEntity(new UrlEncodedFormEntity(ps));
+            CloseableHttpResponse response = httpClient.execute(httpPost);
+            HttpEntity httpEntity = response.getEntity();
+            System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
+        } catch (ClientProtocolException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        }finally{
+            try {
+                if(httpPost!=null){
+                    httpPost.releaseConnection();
+                }
+                if(httpClient!=null){
+                    httpClient.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
+    //url表示请求链接,param表示json格式的请求参数		//自定义菜单创建访问方式
+    public static String sendPost(String url, String param) {
+        PrintWriter out = null;
+        BufferedReader in = null;
+        String result = "";
+        try {
+            URL realUrl = new URL(url);
+            // 打开和URL之间的连接
+            URLConnection conn = realUrl.openConnection();
+            // 设置通用的请求属性 注意Authorization生成
+            // conn.setRequestProperty("Content-Type",
+            // "application/x-www-form-urlencoded");
+            // 发送POST请求必须设置如下两行
+            conn.setDoOutput(true);
+            conn.setDoInput(true);
+            // 获取URLConnection对象对应的输出流
+            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
+            // 发送请求参数
+            out.print("&"+param);
+            // flush输出流的缓冲
+            out.flush();
+            // 定义BufferedReader输入流来读取URL的响应
+            in = new BufferedReader(
+                    new InputStreamReader(conn.getInputStream(),"utf-8"));
+            String line;
+            while ((line = in.readLine()) != null) {
+                result += line;
+            }
+        } catch (Exception e) {
+            System.out.println("发送 请求出现异常!" + e);
+            e.printStackTrace();
+        }
+        // 使用finally块来关闭输出流、输入流
+        finally {
+            try {
+                if (out != null) {
+                    out.close();
+                }
+                if (in != null) {
+                    in.close();
+                }
+            } catch (IOException ex) {
+                ex.printStackTrace();
+            }
+        }
+        return result;
+    }
+
+
+    //url表示请求链接,param表示json格式的请求参数		//自定义菜单创建访问方式
+    public static String sendPost2(String url, String param) {
+        PrintWriter out = null;
+        BufferedReader in = null;
+        String result = "";
+        try {
+            HttpsURLConnection httpsUrlConnection = null;
+            //创建https请求证书
+            TrustManager[] tm={new MyX509TrustManager()};
+            //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
+            SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
+            sslContext.init(null, tm, new java.security.SecureRandom());
+            SSLSocketFactory ssf=sslContext.getSocketFactory();
+            // 创建URL对象
+            URL realUrl= new URL(url);
+            // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象,
+            // 打开和URL之间的连接
+            httpsUrlConnection=(HttpsURLConnection)realUrl.openConnection();
+            //设置ssl证书
+            httpsUrlConnection.setSSLSocketFactory(ssf);
+            // 设置通用的请求属性 注意Authorization生成
+            // conn.setRequestProperty("Content-Type",
+            // "application/x-www-form-urlencoded");
+            // 发送POST请求必须设置如下两行
+            httpsUrlConnection.setRequestMethod("POST");
+            httpsUrlConnection.setDoOutput(true);
+            httpsUrlConnection.setDoInput(true);
+            // 获取URLConnection对象对应的输出流
+            out = new PrintWriter(new OutputStreamWriter(httpsUrlConnection.getOutputStream(),"utf-8"));
+            // 发送请求参数
+            out.print("&"+param);
+            // flush输出流的缓冲
+            out.flush();
+            if (httpsUrlConnection.getResponseCode()==200) {
+                // 定义BufferedReader输入流来读取URL的响应
+                in = new BufferedReader(
+                        new InputStreamReader(httpsUrlConnection.getInputStream(), "utf-8"));
+                String line;
+                while ((line = in.readLine()) != null) {
+                    result += line;
+                }
+            }else {
+                result = "获取输入流异常!";
+            }
+        } catch (Exception e) {
+            System.out.println("发送 请求出现异常!" + e);
+            e.printStackTrace();
+        }
+        // 使用finally块来关闭输出流、输入流
+        finally {
+            try {
+                if (out != null) {
+                    out.close();
+                }
+                if (in != null) {
+                    in.close();
+                }
+            } catch (IOException ex) {
+                ex.printStackTrace();
+            }
+        }
+        return result;
+    }
+
+    public static void main(String[] args) {
+        Map<String, String> req = new HashMap<>();
+        req.put("operator_id", "000000002");
+        req.put("operator_secret", "SBC88d0ItR3w6oCTY");
+        req.put("data_secret", "Epc3hhs0imtVhPSu");
+        req.put("data_secret_iv", "r57m1sr8Tg2E302L");
+        req.put("sign_key", "ikAhygeGCRnEdhjgBKf");
+
+    }
+}

+ 23 - 0
InterceptorConfig.java

@@ -0,0 +1,23 @@
+package com.happy.config;
+
+import com.happy.interceptor.AuthenticationInterceptor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * @author yp
+ */
+@Configuration
+public class InterceptorConfig implements WebMvcConfigurer {
+    @Override
+    public void addInterceptors(InterceptorRegistry registry) {
+        registry.addInterceptor(authenticationInterceptor())
+                .addPathPatterns("/**");    // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
+    }
+    @Bean
+    public AuthenticationInterceptor authenticationInterceptor() {
+        return new AuthenticationInterceptor();
+    }
+}

+ 164 - 0
JaxbUtil.java

@@ -0,0 +1,164 @@
+package com.happy.Until.weixin;
+
+import org.apache.commons.lang.StringUtils;
+
+import javax.xml.bind.*;
+import javax.xml.bind.annotation.XmlAnyElement;
+import javax.xml.namespace.QName;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+/** 
+ * 使用Jaxb2.0实现XML<->Java Object的Binder. 
+ *  
+ * 特别支持Root对象是List的情形. 
+ *  
+ * @author 
+ */  
+public class JaxbUtil {  
+    // 多线程安全的Context.  
+    private JAXBContext jaxbContext;  
+  
+    /** 
+     * @param types 
+     *            所有需要序列化的Root对象的类型. 
+     */  
+    public JaxbUtil(Class<?>... types) {  
+        try {  
+            jaxbContext = JAXBContext.newInstance(types);  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * Java Object->Xml. 
+     */  
+    public String toXml(Object root, String encoding) {  
+        try {  
+            StringWriter writer = new StringWriter();  
+            createMarshaller(encoding).marshal(root, writer);  
+            return writer.toString();  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * Java Object->Xml, 特别支持对Root Element是Collection的情形. 
+     */  
+    @SuppressWarnings("unchecked")  
+    public String toXml(Collection root, String rootName, String encoding) {  
+        try {  
+            CollectionWrapper wrapper = new CollectionWrapper();  
+            wrapper.collection = root;  
+  
+            JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(  
+                    new QName(rootName), CollectionWrapper.class, wrapper);  
+  
+            StringWriter writer = new StringWriter();  
+            createMarshaller(encoding).marshal(wrapperElement, writer);  
+  
+            return writer.toString();  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * Xml->Java Object. 
+     */  
+    @SuppressWarnings("unchecked")  
+    public <T> T fromXml(String xml) {  
+        try {  
+            StringReader reader = new StringReader(xml);  
+            return (T) createUnmarshaller().unmarshal(reader);  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * Xml->Java Object, 支持大小写敏感或不敏感. 
+     */  
+    @SuppressWarnings("unchecked")  
+    public <T> T fromXml(String xml, boolean caseSensitive) {  
+        try {  
+            String fromXml = xml;  
+            if (!caseSensitive)  
+                fromXml = xml.toLowerCase();  
+            StringReader reader = new StringReader(fromXml);  
+            return (T) createUnmarshaller().unmarshal(reader);  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * 创建Marshaller, 设定encoding(可为Null). 
+     */  
+    public Marshaller createMarshaller(String encoding) {  
+        try {  
+            Marshaller marshaller = jaxbContext.createMarshaller();  
+  
+            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);  
+  
+            if (StringUtils.isNotBlank(encoding)) {  
+                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);  
+            }  
+            return marshaller;  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * 创建UnMarshaller. 
+     */  
+    public Unmarshaller createUnmarshaller() {  
+        try {  
+            return jaxbContext.createUnmarshaller();  
+        } catch (JAXBException e) {  
+            throw new RuntimeException(e);  
+        }  
+    }  
+  
+    /** 
+     * 封装Root Element 是 Collection的情况. 
+     */  
+    public static class CollectionWrapper {  
+        @SuppressWarnings("unchecked")  
+        @XmlAnyElement  
+        protected Collection collection;  
+    }
+    /**
+     * 把map转换成xml格式
+     * @param params
+     * @return
+     * @throws Exception
+     */
+    public static String getRequestXml(Map<String, String> params) throws Exception{
+        StringBuffer sb = new StringBuffer();
+        sb.append("<xml>");
+        Set<Entry<String, String>> es = params.entrySet();
+        Iterator<Entry<String, String>> it = es.iterator();
+        while (it.hasNext()) {
+            Entry<String, String> entry = (Entry<String, String>) it
+                    .next();
+            String k = (String) entry.getKey();
+            String v = (String) entry.getValue();
+            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)) {
+                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
+            } else {
+                sb.append("<" + k + ">" + v + "</" + k + ">");
+            }
+        }
+        sb.append("</xml>");
+        return new String(sb.toString().toString().getBytes(), "utf-8");
+    }
+} 

+ 56 - 0
JsonUtil.java

@@ -0,0 +1,56 @@
+package com.happy.Unitil_elc;
+
+
+import org.apache.commons.text.StringEscapeUtils;
+
+public class JsonUtil {
+
+    private static String getLevelStr(int level) {
+        StringBuilder levelStr = new StringBuilder();
+        for (int levelI = 0; levelI < level; levelI++) {
+            levelStr.append("\t");
+        }
+        return levelStr.toString();
+    }
+
+    public static String JsonFormart(String s) {
+        int level = 0;
+        //存放格式化的json字符串
+        StringBuilder jsonForMatStr = new StringBuilder();
+        for(int index=0;index<s.length();index++)//将字符串中的字符逐个按行输出
+        {
+            //获取s中的每个字符
+            char c = s.charAt(index);
+//          System.out.println(s.charAt(index));
+
+            //level大于0并且jsonForMatStr中的最后一个字符为\n,jsonForMatStr加入\t
+            if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
+                jsonForMatStr.append(getLevelStr(level));
+//                System.out.println("123"+jsonForMatStr);
+            }
+            //遇到"{"和"["要增加空格和换行,遇到"}"和"]"要减少空格,以对应,遇到","要换行
+            switch (c) {
+                case '{':
+                case '[':
+                    jsonForMatStr.append(c).append("\n");
+                    level++;
+                    break;
+                case ',':
+                    jsonForMatStr.append(c).append("\n");
+                    break;
+                case '}':
+                case ']':
+                    jsonForMatStr.append("\n");
+                    level--;
+                    jsonForMatStr.append(getLevelStr(level));
+                    jsonForMatStr.append(c);
+                    break;
+                default:
+                    jsonForMatStr.append(c);
+                    break;
+            }
+        }
+        return StringEscapeUtils.unescapeJava(jsonForMatStr.toString());
+    }
+}
+

+ 26 - 0
LeyouCorsConfig.java

@@ -0,0 +1,26 @@
+package com.happy.config;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CorsFilter;
+
+@Configuration
+public class LeyouCorsConfig {
+    @Bean
+    public CorsFilter corsFilter() {
+        //1.添加CORS配置信息
+        CorsConfiguration config = new CorsConfiguration();
+        //1) 允许的域(填前台域),不要写*,否则cookie就无法使用了
+        config.addAllowedOrigin("*");
+        config.setAllowCredentials(true);  //2) 是否发送Cookie信息
+        config.addAllowedMethod("*");   //3) 允许的请求方式
+        config.addAllowedHeader("*");  // 4)允许的头信息
+        //2.添加映射路径,我们拦截一切请求
+        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
+        configSource.registerCorsConfiguration("/**", config);
+        //3.返回新的CorsFilter.
+        return new CorsFilter(configSource);
+    }
+}

+ 95 - 0
Login.java

@@ -0,0 +1,95 @@
+package com.happy.Model;
+
+public class Login {
+
+    public Integer id;
+    public String card_number;
+    public String user_name;
+    public String password;
+    public String login_time;
+    public String expire_time;
+    public String access_token;
+    public String open_id;
+    public String code;
+    public String message;
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public String getLogin_time() {
+        return login_time;
+    }
+
+    public void setLogin_time(String login_time) {
+        this.login_time = login_time;
+    }
+
+    public String getExpire_time() {
+        return expire_time;
+    }
+
+    public void setExpire_time(String expire_time) {
+        this.expire_time = expire_time;
+    }
+
+    public String getAccess_token() {
+        return access_token;
+    }
+
+    public void setAccess_token(String access_token) {
+        this.access_token = access_token;
+    }
+
+    public String getOpen_id() {
+        return open_id;
+    }
+
+    public void setOpen_id(String open_id) {
+        this.open_id = open_id;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public void setMessage(String message) {
+        this.message = message;
+    }
+}

+ 52 - 0
LoginFilter.java

@@ -0,0 +1,52 @@
+////
+//// Source code recreated from a .class file by IntelliJ IDEA
+//// (powered by Fernflower decompiler)
+////
+//
+//package com.happy.filter;
+//
+//import javax.servlet.*;
+//import javax.servlet.http.HttpServletRequest;
+//import javax.servlet.http.HttpServletResponse;
+//import javax.servlet.http.HttpSession;
+//import java.io.IOException;
+//import java.util.Enumeration;
+//
+//public class LoginFilter implements Filter {
+//	Enumeration param;
+//
+//	public LoginFilter() {
+//	}
+//
+//	public void init(FilterConfig filterConfig) throws ServletException {
+//		this.param = filterConfig.getInitParameterNames();
+//	}
+//
+//	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+//		HttpServletRequest servletRequest = (HttpServletRequest)request;
+//		HttpServletResponse servletResponse = (HttpServletResponse)response;
+//		HttpSession session = servletRequest.getSession();
+//		String path = servletRequest.getRequestURI();
+//		String isLogin = (String)session.getAttribute("isLogin");
+//		if (path.indexOf("login.jsp") <= -1 && path.indexOf("branduserbrandlist.action") <= -1 && path.indexOf("/weixin/") <= -1 && path.indexOf("/loginlogin.action") <= -1 && path.indexOf("/WxPaylog.action") <= -1 && path.indexOf("register2.jsp") <= -1 && path.indexOf("/WxPayregister2.action") <= -1) {
+//			if (isLogin != null && !"".equals(isLogin)) {
+//				chain.doFilter(request, response);
+//			} else {
+//				StringBuffer fileURL = servletRequest.getRequestURL();
+//				if (fileURL.indexOf(".css") > 0 || fileURL.indexOf(".png") > 0 || fileURL.indexOf(".jpg") > 0 || fileURL.indexOf(".bmp") > 0 || fileURL.indexOf(".gif") > 0 || fileURL.indexOf(".apk") > 0 || fileURL.indexOf(".ipa") > 0 || fileURL.indexOf(".woff") > 0 || fileURL.indexOf(".ttf") > 0 || fileURL.indexOf("image.jsp") > 0) {
+//					chain.doFilter(servletRequest, servletResponse);
+//					return;
+//				}
+//
+//				String contextPath = servletRequest.getContextPath();
+//				servletResponse.sendRedirect(contextPath + "/jsp/login.jsp");
+//			}
+//
+//		} else {
+//			chain.doFilter(servletRequest, servletResponse);
+//		}
+//	}
+//
+//	public void destroy() {
+//	}
+//}

+ 2 - 0
MANIFEST.MF

@@ -0,0 +1,2 @@
+Manifest-Version: 1.0
+

+ 49 - 0
MD5Utils.java

@@ -0,0 +1,49 @@
+package com.happy.Until;
+
+import java.security.MessageDigest;
+
+public class MD5Utils {
+
+    /***
+     * MD5加码 生成32位md5码
+     */
+    public static String toMD5(String inStr){
+        MessageDigest md5 = null;
+        try{
+            md5 = MessageDigest.getInstance("MD5");
+        }catch (Exception e){
+            System.out.println(e.toString());
+            e.printStackTrace();
+            return "";
+        }
+        char[] charArray = inStr.toCharArray();
+        byte[] byteArray = new byte[charArray.length];
+
+        for (int i = 0; i < charArray.length; i++)
+            byteArray[i] = (byte) charArray[i];
+        byte[] md5Bytes = md5.digest(byteArray);
+        StringBuffer hexValue = new StringBuffer();
+        for (int i = 0; i < md5Bytes.length; i++){
+            int val = ((int) md5Bytes[i]) & 0xff;
+            if (val < 16)
+                hexValue.append("0");
+            hexValue.append(Integer.toHexString(val));
+        }
+        return hexValue.toString();
+
+    }
+
+    /**
+     * 加密解密算法 执行一次加密,两次解密
+     */
+    public static String unlock(String inStr){
+
+        char[] a = inStr.toCharArray();
+        for (int i = 0; i < a.length; i++){
+            a[i] = (char) (a[i] ^ 't');
+        }
+        String s = new String(a);
+        return s;
+
+    }
+}

+ 55 - 0
Msg.java

@@ -0,0 +1,55 @@
+package com.happy.redis;
+
+import java.io.Serializable;
+
+public class Msg implements Serializable {
+
+	private static final long serialVersionUID = -948478514538813354L;
+
+	private int id;
+
+	private String money;
+
+	private long sourceUserId;
+
+	private long getUserId;
+
+	public int getId() {
+		return id;
+	}
+
+	public void setId(int id) {
+		this.id = id;
+	}
+
+	public String getMoney() {
+		return money;
+	}
+
+	public void setMoney(String money) {
+		this.money = money;
+	}
+
+	public long getSourceUserId() {
+		return sourceUserId;
+	}
+
+	public void setSourceUserId(long sourceUserId) {
+		this.sourceUserId = sourceUserId;
+	}
+
+	public long getGetUserId() {
+		return getUserId;
+	}
+
+	public void setGetUserId(long getUserId) {
+		this.getUserId = getUserId;
+	}
+
+	@Override
+	public String toString() {
+		return "Msg [id=" + id + ", money=" + money + ", sourceUserId="
+				+ sourceUserId + ", getUserId=" + getUserId + "]";
+	}
+
+}

+ 23 - 0
MyX509TrustManager.java

@@ -0,0 +1,23 @@
+package com.happy.common.http;
+
+import javax.net.ssl.X509TrustManager;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+/**
+ * X509TrustManager用于实现SSL证书的安全校验
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public class MyX509TrustManager implements X509TrustManager {
+    @Override
+    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+
+    @Override
+    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
+
+    @Override
+    public X509Certificate[] getAcceptedIssuers() {
+        return null;
+    }
+}

+ 36 - 0
ObjectUtil.java

@@ -0,0 +1,36 @@
+package com.happy.redis;
+
+import java.io.*;
+
+public class ObjectUtil {
+
+	/**
+	 * 对象转byte[]
+	 * 
+	 * @param obj
+	 * @return
+	 * @throws IOException
+	 */
+	public static byte[] objectToBytes(Object obj) throws Exception {
+		ByteArrayOutputStream bo = new ByteArrayOutputStream();
+		ObjectOutputStream oo = new ObjectOutputStream(bo);
+		oo.writeObject(obj);
+		byte[] bytes = bo.toByteArray();
+		bo.close();
+		oo.close();
+		return bytes;
+	}
+
+	/**
+	 * byte[]转对象
+	 * 
+	 * @param bytes
+	 * @return
+	 * @throws Exception
+	 */
+	public static Object bytesToObject(byte[] bytes) throws Exception {
+		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
+		ObjectInputStream sIn = new ObjectInputStream(in);
+		return sIn.readObject();
+	}
+}

+ 12 - 0
PassToken.java

@@ -0,0 +1,12 @@
+package com.happy.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface PassToken {
+    boolean required() default true;
+}

+ 76 - 0
Pay.java

@@ -0,0 +1,76 @@
+package com.happy.Model.weixin;
+/**
+ * 充值记录实体来
+ * @author QT-666
+ *
+ */
+public class Pay {
+    private int pay_id;//
+    private int user_id;//用户id
+    private String open_id;//用户相对于公众号的唯一id
+    private String user_name;//用户名称
+    private double pay_money;//支付金额
+    private String pay_time;//支付时间
+    private int pay_type;//支付方式(1微信2支付宝
+    private String pay_no;//订单号
+    //private String pay_state;//F:未支付;T:已支付
+
+    private String user_account;//页面显示作用,表里无此字段
+    
+	public String getUser_account() {
+		return user_account;
+	}
+	public void setUser_account(String user_account) {
+		this.user_account = user_account;
+	}
+	public int getPay_id() {
+		return pay_id;
+	}
+	public void setPay_id(int pay_id) {
+		this.pay_id = pay_id;
+	}
+	public int getUser_id() {
+		return user_id;
+	}
+	public void setUser_id(int user_id) {
+		this.user_id = user_id;
+	}
+	public String getOpen_id() {
+		return open_id;
+	}
+	public void setOpen_id(String open_id) {
+		this.open_id = open_id;
+	}
+	public String getUser_name() {
+		return user_name;
+	}
+	public void setUser_name(String user_name) {
+		this.user_name = user_name;
+	}
+	public double getPay_money() {
+		return pay_money;
+	}
+	public void setPay_money(double pay_money) {
+		this.pay_money = pay_money;
+	}
+	public String getPay_time() {
+		return pay_time;
+	}
+	public void setPay_time(String pay_time) {
+		this.pay_time = pay_time;
+	}
+	public int getPay_type() {
+		return pay_type;
+	}
+	public void setPay_type(int pay_type) {
+		this.pay_type = pay_type;
+	}
+	public String getPay_no() {
+		return pay_no;
+	}
+	public void setPay_no(String pay_no) {
+		this.pay_no = pay_no;
+	}
+    
+    
+}

+ 275 - 0
PayResult.java

@@ -0,0 +1,275 @@
+package com.happy.Model.weixin;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * 微信支付结果返回
+ * 
+ * @author QT-666
+ * 
+ */
+@XmlRootElement(name="xml")
+public class PayResult {
+	private String appid;// 微信分配的公众账号ID(企业号corpid即为此appId)
+	private String attach;//附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用。
+	private String bank_type;// 银行类型,采用字符串类型的银行标识,银行类型见银行列表
+	private String fee_type;// 货币类型,符合ISO4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
+	private String is_subscribe;// 用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效
+	private String mch_id;// 微信支付分配的商户号
+	private String nonce_str;// 随机字符串,不长于32位
+	private String openid;// 用户在商户appid下的唯一标识
+	private String out_trade_no;// 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@
+								// ,且在同一个商户号下唯一。
+	private String result_code;// SUCCESS/FAIL
+	private String return_code;// 此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断
+	private String sign;// 签名,详见签名算法
+	private String sub_mch_id;//
+	private String time_end;// 支付完成时间,格式为yyyyMMddHHmmss,如2009年12月25日9点10分10秒表示为20091225091010。其他详见时间规则
+	private int total_fee;// 订单总金额,单位为分
+	private String trade_type;// JSAPI、NATIVE、APP
+	private String transaction_id;// 微信支付订单号
+	private int cash_fee;// 现金金额
+	
+	private String device_info; //微信支付分配的终端设备号,
+    private String sign_type;//签名类型,目前支持HMAC-SHA256和MD5,默认为MD5
+    private String settlement_total_fee ;//应结订单金额=订单金额-非充值代金券金额,应结订单金额<=订单金额。 
+    private String cash_fee_type;//货币类型,符合ISO4217标准的三位字母代码,默认人民币:CNY,其他值列表详见货币类型
+    private String  coupon_fee;//代金券金额<=订单金额,订单金额-代金券金额=现金支付金额,详见支付金额
+    private String coupon_count;//代金券使用数量
+    private String coupon_type_$n;// CASH--充值代金券 NO_CASH---非充值代金券 仅在使用了免充值代金券时有返回(取值:CASH、NO_CASH)。$n为下标,从0开始编号,举例:coupon_type_0
+    private String coupon_id_$n;//代金券ID,$n为下标,从0开始编号
+    private String coupon_fee_$n;//单个代金券支付金额,$n为下标,从0开始编号
+    
+    
+
+	public String getDevice_info() {
+		return device_info;
+	}
+
+	public void setDevice_info(String device_info) {
+		this.device_info = device_info;
+	}
+
+	public String getSign_type() {
+		return sign_type;
+	}
+
+	public void setSign_type(String sign_type) {
+		this.sign_type = sign_type;
+	}
+
+	public String getSettlement_total_fee() {
+		return settlement_total_fee;
+	}
+
+	public void setSettlement_total_fee(String settlement_total_fee) {
+		this.settlement_total_fee = settlement_total_fee;
+	}
+
+	public String getCash_fee_type() {
+		return cash_fee_type;
+	}
+
+	public void setCash_fee_type(String cash_fee_type) {
+		this.cash_fee_type = cash_fee_type;
+	}
+
+	public String getCoupon_fee() {
+		return coupon_fee;
+	}
+
+	public void setCoupon_fee(String coupon_fee) {
+		this.coupon_fee = coupon_fee;
+	}
+
+	public String getCoupon_count() {
+		return coupon_count;
+	}
+
+	public void setCoupon_count(String coupon_count) {
+		this.coupon_count = coupon_count;
+	}
+
+	public String getCoupon_type_$n() {
+		return coupon_type_$n;
+	}
+
+	public void setCoupon_type_$n(String coupon_type_$n) {
+		this.coupon_type_$n = coupon_type_$n;
+	}
+
+	public String getCoupon_id_$n() {
+		return coupon_id_$n;
+	}
+
+	public void setCoupon_id_$n(String coupon_id_$n) {
+		this.coupon_id_$n = coupon_id_$n;
+	}
+
+	public String getCoupon_fee_$n() {
+		return coupon_fee_$n;
+	}
+
+	public void setCoupon_fee_$n(String coupon_fee_$n) {
+		this.coupon_fee_$n = coupon_fee_$n;
+	}
+
+	public String getAppid() {
+		return appid;
+	}
+
+	public void setAppid(String appid) {
+		this.appid = appid;
+	}
+
+	public String getAttach() {
+		return attach;
+	}
+
+	public void setAttach(String attach) {
+		this.attach = attach;
+	}
+
+	public String getBank_type() {
+		return bank_type;
+	}
+
+	public void setBank_type(String bank_type) {
+		this.bank_type = bank_type;
+	}
+
+	public String getFee_type() {
+		return fee_type;
+	}
+
+	public void setFee_type(String fee_type) {
+		this.fee_type = fee_type;
+	}
+
+	public String getIs_subscribe() {
+		return is_subscribe;
+	}
+
+	public void setIs_subscribe(String is_subscribe) {
+		this.is_subscribe = is_subscribe;
+	}
+
+	public String getMch_id() {
+		return mch_id;
+	}
+
+	public void setMch_id(String mch_id) {
+		this.mch_id = mch_id;
+	}
+
+	public String getNonce_str() {
+		return nonce_str;
+	}
+
+	public void setNonce_str(String nonce_str) {
+		this.nonce_str = nonce_str;
+	}
+
+	public String getOpenid() {
+		return openid;
+	}
+
+	public void setOpenid(String openid) {
+		this.openid = openid;
+	}
+
+	public String getOut_trade_no() {
+		return out_trade_no;
+	}
+
+	public void setOut_trade_no(String out_trade_no) {
+		this.out_trade_no = out_trade_no;
+	}
+
+	public String getResult_code() {
+		return result_code;
+	}
+
+	public void setResult_code(String result_code) {
+		this.result_code = result_code;
+	}
+
+	public String getReturn_code() {
+		return return_code;
+	}
+
+	public void setReturn_code(String return_code) {
+		this.return_code = return_code;
+	}
+
+	public String getSign() {
+		return sign;
+	}
+
+	public void setSign(String sign) {
+		this.sign = sign;
+	}
+
+	public String getSub_mch_id() {
+		return sub_mch_id;
+	}
+
+	public void setSub_mch_id(String sub_mch_id) {
+		this.sub_mch_id = sub_mch_id;
+	}
+
+	public String getTime_end() {
+		return time_end;
+	}
+
+	public void setTime_end(String time_end) {
+		this.time_end = time_end;
+	}
+
+	public int getTotal_fee() {
+		return total_fee;
+	}
+
+	public void setTotal_fee(int total_fee) {
+		this.total_fee = total_fee;
+	}
+
+	public String getTrade_type() {
+		return trade_type;
+	}
+
+	public void setTrade_type(String trade_type) {
+		this.trade_type = trade_type;
+	}
+
+	public String getTransaction_id() {
+		return transaction_id;
+	}
+
+	public void setTransaction_id(String transaction_id) {
+		this.transaction_id = transaction_id;
+	}
+
+	public int getCash_fee() {
+		return cash_fee;
+	}
+
+	public void setCash_fee(int cash_fee) {
+		this.cash_fee = cash_fee;
+	}
+
+	@Override
+	public String toString() {
+		return "PayResult [appid=" + appid + ", attach=" + attach
+				+ ", bank_type=" + bank_type + ", fee_type=" + fee_type
+				+ ", is_subscribe=" + is_subscribe + ", mch_id=" + mch_id
+				+ ", nonce_str=" + nonce_str + ", openid=" + openid
+				+ ", out_trade_no=" + out_trade_no + ", result_code="
+				+ result_code + ", return_code=" + return_code + ", sign="
+				+ sign + ", sub_mch_id=" + sub_mch_id + ", time_end="
+				+ time_end + ", total_fee=" + total_fee + ", trade_type="
+				+ trade_type + ", transaction_id=" + transaction_id
+				+ ", cash_fee=" + cash_fee ;
+	}
+   
+}

+ 128 - 0
PayWxUtil.java

@@ -0,0 +1,128 @@
+package com.happy.Until.weixin;
+
+import org.apache.commons.codec.digest.DigestUtils;
+
+import java.security.MessageDigest;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * Created by Song on 2016/11/8. mail: 1147649695@qq.com 微信支付相关工具类
+ */
+public class PayWxUtil {
+	// 上一次订单请求日期
+	private static Date preDay = new Date();
+	// 当前订单日期
+	private static Date curDay = new Date();
+	// 用于记录已产生的订单号
+	private static Set<Long> numPoul = new HashSet<Long>();
+
+	/**
+	 * 获得签名
+	 * 
+	 * @param params
+	 *            待编码参数,参数值为空不传入
+	 * @param key
+	 *            key设置路径:微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
+	 * @return
+	 */
+	public static String getSign(Map<String, String> params, String key)
+			throws Exception {
+		List<String> list = new ArrayList<String>(params.keySet());
+		Collections.sort(list, new DictionaryCompare());
+		StringBuffer sb = new StringBuffer();
+		for (String keyVal : list) {
+			if (params.get(keyVal) != null) {
+				sb.append(keyVal + "=" + params.get(keyVal) + "&");
+			}
+		}
+		sb.append("key=" + key);
+		return DigestUtils
+				.md5Hex(new String(sb.toString().getBytes(), "utf-8"))
+				.toUpperCase();
+	}
+
+	/**
+	 * 获得随机字符串
+	 * 
+	 * @return
+	 */
+	public static String getNonceStr() {
+		Random random = new Random();
+		long val = random.nextLong();
+		String res = DigestUtils.md5Hex(val + "yzx").toUpperCase();
+		if (32 < res.length())
+			return res.substring(0, 32);
+		else
+			return res;
+	}
+
+	/**
+	 * 获取订单号 商户订单号(每个订单号必须唯一) 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。
+	 * 
+	 * @param mchId
+	 * @return
+	 */
+	public static String getMchBillno(String mchId) {
+		Random random = new Random();
+		long val = random.nextLong() % 10000000000L;// 获得0-9999999999内的数字
+		curDay = new Date();
+		// 隔天清空
+		if (curDay.after(preDay))
+			numPoul.clear();
+		while (numPoul.contains(val)) {
+			val = random.nextLong() % 10000000000L;
+		}
+		numPoul.add(val);
+		preDay = curDay;
+		// 按要求,日期格式化输出
+		DateFormat df = new SimpleDateFormat("yyyymmdd");
+		return mchId + df.format(curDay) + format(val + "", 10);
+	}
+
+	/**
+	 * 将字符串str按长度在前面添0补齐
+	 * 
+	 * @param str
+	 * @param length
+	 * @return
+	 */
+	private static String format(String str, int length) {
+		String pre = "0000000000";
+		int len = str.length();
+		if (10 <= len)
+			return str.substring(0, 10);
+		else
+			return pre.substring(0, 10 - len).concat(str);
+	}
+
+	// SHA1加密方法,jssdk签名算法
+	public static String getSha1(String str) {
+		if (str == null || str.length() == 0) {
+			return null;
+		}
+		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+				'a', 'b', 'c', 'd', 'e', 'f' };
+		try {
+			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
+			mdTemp.update(str.getBytes("UTF-8"));
+
+			byte[] md = mdTemp.digest();
+			int j = md.length;
+			char buf[] = new char[j * 2];
+			int k = 0;
+			for (int i = 0; i < j; i++) {
+				byte byte0 = md[i];
+				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
+				buf[k++] = hexDigits[byte0 & 0xf];
+			}
+			return new String(buf);
+		} catch (Exception e) {
+			// TODO: handle exception
+			return null;
+		}
+	}
+
+}
+

+ 43 - 0
Price.java

@@ -0,0 +1,43 @@
+package com.happy.Model;
+
+import java.math.BigDecimal;
+
+public class Price {
+
+    public int id;
+    public String name;
+    public double price;
+    public int state;
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public double getPrice() {
+        return price;
+    }
+
+    public void setPrice(double price) {
+        this.price = price;
+    }
+
+    public int getState() {
+        return state;
+    }
+
+    public void setState(int state) {
+        this.state = state;
+    }
+}

+ 34 - 0
QueryUrlEnum.java

@@ -0,0 +1,34 @@
+package com.happy.Model;
+
+public enum QueryUrlEnum {
+
+    ACCOUNT_REGISTER("accountRegister","用户注册"),
+    ACCOUNT_RECHARGE("accountRecharge","账户充值"),
+    ACCOUNT_MODIFY("accountModify","用户信息修改"),
+    ACCOUNT_INFO("queryAccountInfo","账户信息(余额等信息)"),
+    HISTORY_CUMULANT("queryHistoryCumulantInfo","历史记录"),
+    LAST_HISTORY("queryLastHistoryElectricityInfo","最新一条记录"),
+    METER_REAL_INFO("queryRealElectricityInfo","电表实时信息"),
+    POWER_MONTH_BILL("queryMonthlyPowerBillInfo","电费月账单"),
+    QUERY_TOKEN("queryToken","获取token"),
+    REMOTE_DISCONNECT("remoteDisconnect","拉合闸"),
+    USER_INFO("queryUserAccountInfo","用户信息(用户名、联系人、手机等)"),
+    WATER_MONTH_BILL("queryMonthlyWaterBillInfo","水费月账单"),
+    LAST_HISTORY_CUMULANT("queryLastHistoryCumulantInfo","最近一条历史数据"),
+    QUERY_BUILDING_USED("buildingEnergyConsumption/queryBuildingUsed","查询建筑日/小时用量数据"),
+    QUERY_BUILDING("buildingEnergyConsumption/queryBuilding","查询建筑信息"),
+    QUERY_DATACENTER("buildingEnergyConsumption/queryDataCenter","查询数据中心信息")
+    ;
+
+    String url;
+    String dsc;
+
+    QueryUrlEnum(String url, String dsc) {
+        this.url = url;
+        this.dsc = dsc;
+    }
+
+    public String getUrl() {
+        return url;
+    }
+}

+ 79 - 0
Recharge.java

@@ -0,0 +1,79 @@
+package com.happy.Model;
+
+import java.math.BigDecimal;
+
+public class Recharge {
+
+    public int id;
+    public String order_num;
+    public String card_number;
+    public String user_name;
+    public double account;
+    public String re_time;
+    public int state;
+    public String stu_number;
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getOrder_num() {
+        return order_num;
+    }
+
+    public void setOrder_num(String order_num) {
+        this.order_num = order_num;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public double getAccount() {
+        return account;
+    }
+
+    public void setAccount(double account) {
+        this.account = account;
+    }
+
+    public String getRe_time() {
+        return re_time;
+    }
+
+    public void setRe_time(String re_time) {
+        this.re_time = re_time;
+    }
+
+    public int getState() {
+        return state;
+    }
+
+    public void setState(int state) {
+        this.state = state;
+    }
+}

+ 19 - 0
RechargeDao.java

@@ -0,0 +1,19 @@
+package com.happy.dao;
+
+
+import com.happy.Model.Recharge;
+
+import java.util.List;
+
+public interface RechargeDao {
+
+    public List<Recharge> queryByStu(String stu_number, String re_time);
+
+    public int insertRecharge(Recharge recharge);
+
+    public int insertRecharge2(Recharge recharge);
+
+    public Recharge findPayByNo(String order_num);
+
+    public List<Recharge> queryRecordByStu(String stu_number, String re_time);
+}

+ 107 - 0
RechargeDaoImpl.java

@@ -0,0 +1,107 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.Consume;
+import com.happy.Model.Recharge;
+import com.happy.dao.ConsumeDao;
+import com.happy.dao.RechargeDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository("RechargeDao")
+public class RechargeDaoImpl implements RechargeDao {
+
+    @Autowired
+    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+    public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+        return namedParameterJdbcTemplate;
+    }
+
+    public void setNamedParameterJdbcTemplate(
+            NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+    }
+
+    public List<Recharge> queryByStu(String stu_number, String re_time){
+        String sql="select * from `recharge` where stu_number=:stu_number and re_time like '" + re_time + "%' order by id desc";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", stu_number);
+        List<Recharge> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Recharge>(Recharge.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+    public int insertRecharge(Recharge recharge){
+        String sql = "insert into recharge(order_num, card_number, user_name, account, re_time, state, stu_number) values(:order_num, :card_number, :user_name, :account, :re_time, :state, :stu_number)";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", recharge.getOrder_num());
+        sps.addValue("card_number", recharge.getCard_number());
+        sps.addValue("user_name", recharge.getUser_name());
+        sps.addValue("account", recharge.getAccount());
+        sps.addValue("re_time", recharge.getRe_time());
+        sps.addValue("state", recharge.getState());
+        sps.addValue("stu_number", recharge.getStu_number());
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    public int insertRecharge2(Recharge recharge){
+        String sql = "insert into `recharge_elc`(order_num, card_number, user_name, account, re_time, state, stu_number) values(:order_num, :card_number, :user_name, :account, :re_time, :state, :stu_number)";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", recharge.getOrder_num());
+        sps.addValue("card_number", recharge.getCard_number());
+        sps.addValue("user_name", recharge.getUser_name());
+        sps.addValue("account", recharge.getAccount());
+        sps.addValue("re_time", recharge.getRe_time());
+        sps.addValue("state", recharge.getState());
+        sps.addValue("stu_number", recharge.getStu_number());
+        int num = 0;
+        try{
+            num = namedParameterJdbcTemplate.update(sql, sps);
+        }
+        catch(Exception e){
+            e.printStackTrace();
+        }
+        return num;
+    }
+
+    //根据订单号查找支付记录信息
+    public Recharge findPayByNo(String order_num) {
+        String sql = "select * from recharge where order_num=:order_num";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("order_num", order_num);
+        Recharge recharge = null;
+        try{
+            recharge = namedParameterJdbcTemplate.queryForObject(sql, sps, new BeanPropertyRowMapper<Recharge>(Recharge.class));
+        }
+        catch(Exception e){
+            recharge = null;
+        }
+        return recharge;
+    }
+
+    public List<Recharge> queryRecordByStu(String stu_number, String re_time){
+        String sql="select * from recharge_elc where stu_number=:stu_number and re_time like '"+ re_time +"%' order by id desc";
+        MapSqlParameterSource sps = new MapSqlParameterSource();
+        sps.addValue("stu_number", stu_number);
+        List<Recharge> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Recharge>(Recharge.class));
+        if(list != null && list.size() >0){
+            return list;
+        }
+        return null;
+    }
+
+}

+ 20 - 0
RechargeService.java

@@ -0,0 +1,20 @@
+package com.happy.service;
+
+import com.happy.Model.Recharge;
+import com.happy.dao.RechargeDao;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+public interface RechargeService {
+
+    public List<Recharge> queryByStu(String stu_number, String re_time);
+
+    public int insertRecharge(Recharge recharge);
+
+    public int insertRecharge2(Recharge recharge);
+
+    public Recharge findPayByNo(String order_num);
+
+    public List<Recharge> queryRecordByStu(String stu_number, String re_time);
+}

+ 36 - 0
RechargeServiceImpl.java

@@ -0,0 +1,36 @@
+package com.happy.service.impl;
+
+import com.happy.Model.Recharge;
+import com.happy.dao.RechargeDao;
+import com.happy.service.RechargeService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+@Service("RechargeService")
+public class RechargeServiceImpl implements RechargeService {
+
+    @Resource
+    public RechargeDao rechargeDao;
+
+    public List<Recharge> queryByStu(String stu_number, String re_time){
+        return rechargeDao.queryByStu(stu_number, re_time);
+    }
+
+    public int insertRecharge(Recharge recharge){
+        return rechargeDao.insertRecharge(recharge);
+    }
+
+    public int insertRecharge2(Recharge recharge){
+        return rechargeDao.insertRecharge2(recharge);
+    }
+
+    public Recharge findPayByNo(String order_num){
+        return rechargeDao.findPayByNo(order_num);
+    }
+
+    public List<Recharge> queryRecordByStu(String stu_number, String re_time){
+        return rechargeDao.queryRecordByStu(stu_number, re_time);
+    }
+}

+ 134 - 0
RedPacketAlgorithm.java

@@ -0,0 +1,134 @@
+package com.happy.redis;
+
+import java.util.Random;
+
+public class RedPacketAlgorithm {
+	static Random random = new Random();
+	static {
+		random.setSeed(System.currentTimeMillis());
+	}
+
+	public static void main(String[] args) {
+		long max = 20;
+		long min = 1;
+
+		long[] result = generate(100, 10, max, min);
+		long total = 0;
+		for (int i = 0; i < result.length; i++) {
+			total += result[i];
+		}
+		// 检查生成的红包的总额是否正确
+		// System.out.println("total:" + total);
+
+		// 统计每个钱数的红包数量,检查是否接近正态分布
+		int count[] = new int[(int) max + 1];
+		for (int i = 0; i < result.length; i++) {
+			count[(int) result[i]] += 1;
+		}
+
+		// for (int i = 0; i < count.length; i++) {
+		// System.out.println("" + i + "  " + count[i]);
+		// }
+	}
+
+	/**
+	 * 生产min和max之间的随机数,但是概率不是平均的,从min到max方向概率逐渐加大。
+	 * 先平方,然后产生一个平方值范围内的随机数,再开方,这样就产生了一种“膨胀”再“收缩”的效果。
+	 * 
+	 * @param min
+	 * @param max
+	 * @return
+	 */
+	static long xRandom(long min, long max) {
+		return sqrt(nextLong(sqr(max - min)));
+	}
+
+	/**
+	 * 
+	 * @param total
+	 *            红包总额
+	 * @param count
+	 *            红包个数
+	 * @param max
+	 *            每个小红包的最大额
+	 * @param min
+	 *            每个小红包的最小额
+	 * @return 存放生成的每个小红包的值的数组
+	 */
+	public static long[] generate(long total, int count, long max, long min) {
+
+		if (count * max < total) {
+			// System.out.println("最大红包钱数 * 红包个数 < 总钱数");
+			System.exit(-1);
+		}
+
+		long[] result = new long[count];
+
+		long average = total / count;
+
+		long a = average - min;
+		long b = max - min;
+
+		//
+		// 这样的随机数的概率实际改变了,产生大数的可能性要比产生小数的概率要小。
+		// 这样就实现了大部分红包的值在平均数附近。大红包和小红包比较少。
+		long range1 = sqr(average - min);
+		long range2 = sqr(max - average);
+
+		for (int i = 0; i < result.length; i++) {
+			// 因为小红包的数量通常是要比大红包的数量要多的,因为这里的概率要调换过来。
+			// 当随机数>平均值,则产生小红包
+			// 当随机数<平均值,则产生大红包
+			if (nextLong(min, max) > average) {
+				// 在平均线上减钱
+				// long temp = min + sqrt(nextLong(range1));
+				long temp = min + xRandom(min, average);
+				result[i] = temp;
+				total -= temp;
+			} else {
+				// 在平均线上加钱
+				// long temp = max - sqrt(nextLong(range2));
+				long temp = max - xRandom(average, max);
+				result[i] = temp;
+				total -= temp;
+			}
+		}
+		// 如果还有余钱,则尝试加到小红包里,如果加不进去,则尝试下一个。
+		while (total > 0) {
+			for (int i = 0; i < result.length; i++) {
+				if (total > 0 && result[i] < max) {
+					result[i]++;
+					total--;
+				}
+			}
+		}
+		// 如果钱是负数了,还得从已生成的小红包中抽取回来
+		while (total < 0) {
+			for (int i = 0; i < result.length; i++) {
+				if (total < 0 && result[i] > min) {
+					result[i]--;
+					total++;
+				}
+			}
+		}
+		return result;
+	}
+
+	static long sqrt(long n) {
+		// 改进为查表?
+		return (long) Math.sqrt(n);
+	}
+
+	static long sqr(long n) {
+		// 查表快,还是直接算快?
+		return n * n;
+	}
+
+	static long nextLong(long n) {
+		return random.nextInt((int) n);
+	}
+
+	static long nextLong(long min, long max) {
+		return random.nextInt((int) (max - min + 1)) + min;
+	}
+}

+ 582 - 0
RedisUtil.java

@@ -0,0 +1,582 @@
+package com.happy.redis;
+
+import redis.clients.jedis.Jedis;
+import redis.clients.jedis.JedisPool;
+import redis.clients.jedis.JedisPoolConfig;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Redis连接池
+ * 
+ * @author AK
+ * 
+ */
+public final class RedisUtil {
+	// Redis服务器IP
+	private static String IP = "127.0.0.1";
+	// Redis的端口号
+	private static int PORT = 6379;
+	// 访问密码
+	private static String AUTH = "Ytw-2015#Ehsan";
+	// 可用连接实例的最大数目,默认值为8;
+	// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
+	private static int MAX_ACTIVE = 1024;
+	// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
+	private static int MAX_IDLE = 200;
+	// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
+	private static long MAX_WAIT = 10000;
+	// 最大延迟时间
+	private static int TIMEOUT = 10000;
+	// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
+	private static boolean TEST_ON_BORROW = true;
+
+	private static JedisPool jedisPool = null;
+
+	/**
+	 * 初始化Redis连接池
+	 */
+	static {
+		try {
+			JedisPoolConfig config = new JedisPoolConfig();
+			// 控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
+			// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
+			config.setMaxIdle(500);
+			// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
+			config.setMinIdle(2);
+			config.setMaxIdle(10);
+			// 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
+			config.setMaxWaitMillis(1000 * 10);
+			// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
+			config.setTestOnBorrow(true);
+			jedisPool = new JedisPool(config, IP, PORT);
+
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * 获取Jedis实例
+	 * 
+	 * @return
+	 */
+	public synchronized static Jedis getJedis() {
+		try {
+			if (jedisPool != null) {
+				Jedis resource = jedisPool.getResource();
+				return resource;
+			} else {
+				return null;
+			}
+		} catch (Exception e) {
+			e.printStackTrace();
+			return null;
+		}
+	}
+
+	/**
+	 * 释放jedis资源
+	 * 
+	 * @param jedis
+	 */
+	public static void returnResource(final Jedis jedis) {
+		if (jedis != null) {
+			jedisPool.returnResource(jedis);
+		}
+	}
+
+	/**
+	 * 设置数据
+	 * 
+	 * @param key
+	 * @return
+	 */
+	public static String set(String key, String value) {
+		Jedis jedis = null;
+		try {
+			jedis = jedisPool.getResource();
+			jedis.set(key, value);
+		} catch (Exception e) {
+			// 释放redis对象
+			jedisPool.returnBrokenResource(jedis);
+			e.printStackTrace();
+		} finally {
+			// 返还到连接池
+			returnResource(jedis);
+		}
+
+		return value;
+	}
+
+	public static String setBySeconds(String key, int seconds, String value) {
+		Jedis jedis = null;
+		try {
+			jedis = jedisPool.getResource();
+			jedis.setex(key, seconds, value);
+		} catch (Exception e) {
+			// 释放redis对象
+			jedisPool.returnBrokenResource(jedis);
+			e.printStackTrace();
+		} finally {
+			// 返还到连接池
+			returnResource(jedis);
+		}
+
+		return value;
+	}
+
+	/**
+	 * 删除数据
+	 * 
+	 * @param key
+	 * @return
+	 */
+	public boolean del(String key) {
+		Jedis jedis = null;
+
+		try {
+			jedis = jedisPool.getResource();
+			return jedis.del(key) > 0 ? true : false;
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+
+		return false;
+	}
+
+	public String get(String key) {
+		Jedis jedis = null;
+
+		try {
+			jedis = jedisPool.getResource();
+
+			return jedis.get(key);
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+
+		return null;
+	}
+
+	/**
+	 * 存储到redis队列中,插入到表头
+	 * 
+	 * @param key
+	 * @param value
+	 */
+	public void lpush(byte[] key, byte[] value) {
+		Jedis jedis = null;
+		try {
+			jedis = jedisPool.getResource();
+			jedis.lpush(key, value);
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+	}
+
+	/**
+	 * 存储到redis队列中,插入到表尾
+	 * 
+	 * @param key
+	 * @param value
+	 */
+	public void rpush(byte[] key, byte[] value) {
+		Jedis jedis = null;
+
+		try {
+			jedis = jedisPool.getResource();
+			jedis.rpush(key, value);
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+	}
+
+	public byte[] lpop(byte[] key) {
+
+		Jedis jedis = null;
+
+		try {
+			jedis = jedisPool.getResource();
+			return jedis.lpop(key);
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+
+		return null;
+	}
+
+	public byte[] rpop(byte[] key) {
+
+		Jedis jedis = null;
+
+		try {
+			jedis = jedisPool.getResource();
+			return jedis.rpop(key);
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+
+		return null;
+	}
+
+	public Long getLen(byte[] key) {
+		Jedis jedis = null;
+
+		try {
+			jedis = jedisPool.getResource();
+			return jedis.llen(key);
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+
+		return 0L;
+	}
+
+	public List<byte[]> getRedisList(byte[] key) {
+		Jedis jedis = null;
+
+		try {
+			jedis = jedisPool.getResource();
+			return jedis.lrange(key, 0, -1);
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+
+		return null;
+	}
+
+	public boolean isExistUpdate(final String... param) {
+
+		Jedis jedis = null;
+
+		try {
+
+			jedis = jedisPool.getResource();
+
+			String key = param[0];
+			int expire = 20;
+			if (param.length > 1) {
+				expire = Integer.parseInt(param[1]);
+			}
+			long status = jedis.setnx("redis_lock_" + key, "true");
+			// if (status > 0) {
+			jedis.expire("redis_lock_" + key, expire);
+			// }
+
+			return status <= 0 ? true : false;
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+
+		return false;
+
+	}
+
+	public static boolean acquireLock(String lock, String expired) {
+		// 1. 通过SETNX试图获取一个lock
+		boolean success = false;
+		Jedis jedis = null;
+		try {
+
+			jedis = jedisPool.getResource();
+
+			long acquired = jedis.setnx(lock, String.valueOf(expired));
+			// SETNX成功,则成功获取一个锁
+			if (acquired == 1) {
+				success = true;
+			}
+			// SETNX失败,说明锁仍然被其他对象保持,检查其是否已经超时
+			else {
+				success = false;
+			}
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+		return success;
+	}
+
+	public Long unLockRedisKey(final String key) {
+
+		Jedis jedis = null;
+
+		try {
+			jedis = jedisPool.getResource();
+			return jedis.del("redis_lock_" + key);
+		} catch (Throwable e) {
+			e.printStackTrace();
+		} finally {
+			returnResource(jedis);
+		}
+
+		return -1L;
+	}
+
+	/**
+	 * Redis 哈希
+	 */
+	public class RedisHash {
+
+		private String key;
+
+		public RedisHash(String key) {
+			this.key = key;
+		}
+
+		/**
+		 * 获取指定属性值
+		 * 
+		 * @param field
+		 *            属性名
+		 * 
+		 * @return 属性值
+		 */
+		public String get(final String field) {
+
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				return jedis.hget(key, field);
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+
+			return null;
+
+		}
+
+		/**
+		 * 获取指定属性值
+		 * 
+		 * @param fields
+		 *            属性名
+		 * 
+		 * @return 属性值
+		 */
+		public List<String> get(final String... fields) {
+
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				return jedis.hmget(key, fields);
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+
+			return null;
+		}
+
+		/**
+		 * 设置属性
+		 * 
+		 * @param field
+		 *            属性名
+		 * @param value
+		 *            属性值
+		 */
+		public void put(final String field, final String value) {
+
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				jedis.hset(key, field, value);
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+		}
+
+		/**
+		 * 仅当属性名不存在是设置属性
+		 * 
+		 * @param field
+		 *            属性名
+		 * @param value
+		 *            属性值
+		 * 
+		 * @return 0表示属性已存在
+		 */
+		public int setOnlyIfNotExists(final String field, final String value) {
+
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				return jedis.hsetnx(key, field, value).intValue();
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+
+			return -1;
+		}
+
+		/**
+		 * 保存多个属性名和属性值
+		 * 
+		 * @param map
+		 *            属性
+		 */
+		public void putAll(final Map<String, String> map) {
+
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				jedis.hmset(key, map);
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+		}
+
+		/**
+		 * 删除一个或多个属性
+		 * 
+		 * @param fields
+		 *            属性名
+		 * 
+		 * @return 被删除的属性数量
+		 */
+		public int delete(final String... fields) {
+
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				return jedis.hdel(key, fields).intValue();
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+
+			return -1;
+		}
+
+		/**
+		 * 列出所有属性
+		 * 
+		 * @return 所有属性名
+		 */
+		public List<String> keys() {
+
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				return new ArrayList<String>(jedis.hkeys(key));
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+
+			return null;
+		}
+
+		/**
+		 * 读取所有属性值并转换为 Map 对象
+		 * 
+		 * @return 所有属性值
+		 */
+		public Map<String, String> toMap() {
+
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				return jedis.hgetAll(key);
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+
+			return null;
+		}
+
+		/**
+		 * 读取key的长度
+		 * 
+		 * @return 所有属性值
+		 */
+		public Long getLen() {
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				return jedis.hlen(key);
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+
+			return 0L;
+		}
+
+		/**
+		 * 是否存在一个key
+		 * 
+		 * @return 所有属性值
+		 */
+		public Boolean isExist(final String field) {
+
+			Jedis jedis = null;
+
+			try {
+				jedis = jedisPool.getResource();
+				return jedis.hexists(key, field);
+			} catch (Throwable e) {
+				e.printStackTrace();
+			} finally {
+				returnResource(jedis);
+			}
+
+			return false;
+		}
+
+	}
+
+	public RedisHash getRedisHash(String key) {
+		return new RedisHash(key);
+	}
+
+	public static void main(String[] args) {
+		// System.out.println(getJedis().flushAll());
+	}
+
+}

+ 53 - 0
ResUtil.java

@@ -0,0 +1,53 @@
+package com.happy.Until;
+
+import org.apache.poi.ss.usermodel.Workbook;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+
+public class ResUtil {
+
+	public static void write(Object o, HttpServletResponse response)
+			throws Exception {
+		response.setContentType("text/html;charset=utf-8");
+//		response.setHeader("Access-Control-Allow-Origin", "*");
+		PrintWriter out = response.getWriter();
+		out.println(o.toString());
+		out.flush();
+		out.close();
+	}
+
+	public static void write(String o, HttpServletResponse response)
+			throws Exception {
+		response.setContentType("text/html;charset=utf-8");
+		PrintWriter out = response.getWriter();
+		out.println(o.toString());
+		out.flush();
+		out.close();
+	}
+
+	public static void writeJson(HttpServletResponse respone, String result) {
+		respone.setContentType("application/json;charset=utf-8");
+		PrintWriter out;
+		try {
+			out = respone.getWriter();
+			out.print(result);
+			out.flush();
+			out.close();
+		} catch (Exception e) { 
+			// //System.out.println("Comm_Util_writeJson---->" + e);
+		}
+	}
+
+	public static void export(HttpServletResponse response, Workbook wb,
+			String fileName) throws Exception {
+		response.setHeader("Content-Disposition", "attachment;filename="
+				+ new String(fileName.getBytes("utf-8"), "iso8859-1"));
+		response.setContentType("application/ynd.ms-excel;charset=UTF-8");
+		OutputStream out = response.getOutputStream();
+		wb.write(out);
+		out.flush();
+		out.close();
+	}
+}

+ 52 - 0
ResponseUtil.java

@@ -0,0 +1,52 @@
+package com.happy.Until;
+
+import org.apache.poi.ss.usermodel.Workbook;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+
+public class ResponseUtil {
+
+	public static void write(Object o, HttpServletResponse response)
+			throws Exception {
+		response.setContentType("text/html;charset=utf-8");
+		PrintWriter out = response.getWriter();
+		out.println(o.toString());
+		out.flush();
+		out.close();
+	}
+
+	public static void write(String o, HttpServletResponse response)
+			throws Exception {
+		response.setContentType("text/html;charset=utf-8");
+		PrintWriter out = response.getWriter();
+		out.println(o.toString());
+		out.flush();
+		out.close();
+	}
+
+	public static void writeJson(HttpServletResponse respone, String result) {
+		respone.setContentType("application/json;charset=utf-8");
+		PrintWriter out;
+		try {
+			out = respone.getWriter();
+			out.print(result);
+			out.flush();
+			out.close();
+		} catch (Exception e) {
+			// //System.out.println("Comm_Util_writeJson---->" + e);
+		}
+	}
+
+	public static void export(HttpServletResponse response, Workbook wb,
+			String fileName) throws Exception {
+		response.setHeader("Content-Disposition", "attachment;filename="
+				+ new String(fileName.getBytes("utf-8"), "iso8859-1"));
+		response.setContentType("application/ynd.ms-excel;charset=UTF-8");
+		OutputStream out = response.getOutputStream();
+		wb.write(out);
+		out.flush();
+		out.close();
+	}
+}

+ 86 - 0
ResultStatusCode.java

@@ -0,0 +1,86 @@
+package com.happy.constant;
+
+public enum ResultStatusCode {
+	/** OKlockcslock */
+	QUIT(200, "退出成功"),
+	/** OK */
+	OK(200, "OK"),
+	/** 访问超时 */
+	TIME_OUT(130, "访问超时"),
+	/** 参数解析失败 */
+	BAD_REQUEST(400, "参数解析失败"),
+	/** 记录不存在 */
+	NOT_EXIST(404, "记录不存在"),
+	/** 不支持当前请求方法 */
+	METHOD_NOT_ALLOWED(405, "不支持当前请求方法"),
+	/** 服务器运行异常 */
+	SYSTEM_ERR(500, "服务器运行异常"),
+	/** 该用户不存在或密码错误 */
+	NOT_EXIST_USER_OR_ERROR_PWD(10000, "该用户不存在或账号密码错误"),
+	/** 该用户已登录 */
+	LOGINED_IN(10001, "该用户已登录"),
+	LOGINED_IN2(10002, "该用户不存在"),
+	LOGINED_IN3(100021, "该用户登录已失效"),
+	/** 登录异常 */
+	SHIRO_ERROR(10003, "登录异常"),
+	/** 您没有该权限 */
+	UNAUTHO_ERROR(10004, "您没有该权限"),
+	/** 请绑定手机号 */
+	BIND_PHONE(10010, "请绑定手机号"),
+	/** 上传文件异常 */
+	UPLOAD_ERROR(20000, "上传文件异常"),
+	/** 无效的验证码 */
+	INVALID_CAPTCHA(30005, "无效的验证码"),
+	/** 该用户已被冻结 */
+	USER_FROZEN(40000, "该用户已被冻结"),
+	/** 该用户未绑定微信号 */
+	USER_NOT_WX_OAUTH(40004, "该用户未进行微信授权"),
+    /** 该用户未绑定微信号 */
+	USER_NOT_BIND_WX(5000, "该用户未绑定微信号"),
+    /** 该用户成功绑定微信号 */
+    USER_BIND_WX_OK(5005, "该用户成功绑定微信号"),
+	/** 该部门已存在 */
+	DEPARTMENT_EXIT(5006, "该部门已存在"),
+	/** 该用户已存在 */
+	USER_EXIST(6000, "该用户已存在"),
+	/** 该账号已存在 */
+	USERACCOUNT_EXIST(6002, "该账号已存在"),
+	/** 缴费用户信息不存在 */
+	PARTYDUES_USER_NOEXIT(6003, "缴费用户信息不存在"),
+	/** 党费信息不存在 */
+	PARTYDUES_NOEXIT(6004, "费用信息不存在"),
+	/** 党费信息党费已支付 */
+	PARTYDUES_OK(6005, "费用已支付"),
+	/** 党费订单支付失败 */
+	PARTYDUES_ERR(6009, "费用支付失败");
+
+	private int status;
+	private String msg;
+
+	public int getStatus() {
+		return status;
+	}
+
+	public void setStatus(int status) {
+		this.status = status;
+	}
+
+	public String getMsg() {
+		return msg;
+	}
+
+	public void setMsg(String msg) {
+		this.msg = msg;
+	}
+
+	private ResultStatusCode(int code, String msg) {
+		this.status = code;
+		this.msg = msg;
+	}
+
+	@Override
+	public String toString() {
+		return "{\"status\":" + this.status + ",\"msg\":\"" + this.msg + "\",\"data\": null, \"ok\": false}";
+	}
+}
+

+ 103 - 0
ResultUtil.java

@@ -0,0 +1,103 @@
+package com.happy.Until;
+
+import com.happy.constant.ResultStatusCode;
+
+/**
+ * @author yp
+ * @date 2019/10/31 0:02
+ */
+public class ResultUtil {
+    private static final long serialVersionUID = 1L;
+    // 响应状态
+    protected Integer status = 0;
+
+    // 响应消息
+    protected String msg;
+
+    // 响应数据
+    protected Object data;
+
+    public static ResultUtil buildOK() {
+        return new ResultUtil(ResultStatusCode.OK);
+    }
+
+    public static ResultUtil buildOK(Object data) {
+        return ResultUtil.build(ResultStatusCode.OK, data);
+    }
+
+    public static ResultUtil build(ResultStatusCode rsc) {
+        return new ResultUtil(rsc.getStatus(), rsc.getMsg(), null);
+    }
+
+    public static ResultUtil build(ResultStatusCode rsc, Object data) {
+        return new ResultUtil(rsc.getStatus(), rsc.getMsg(), data);
+    }
+
+    public static ResultUtil build(Integer status, String msg, Object data) {
+        return new ResultUtil(status, msg, data);
+    }
+
+    public static ResultUtil ok(Object data) {
+        return new ResultUtil(data);
+    }
+
+    public static ResultUtil ok() {
+        return new ResultUtil(null);
+    }
+
+    public ResultUtil() {
+
+    }
+
+    public static ResultUtil build(Integer status, String msg) {
+        return new ResultUtil(status, msg, null);
+    }
+
+    public ResultUtil(Integer status, String msg, Object data) {
+        this.status = status;
+        this.msg = msg;
+        this.data = data;
+    }
+
+    public ResultUtil(Object data) {
+        this.status = 200;
+        this.msg = "OK";
+        this.data = data;
+    }
+
+    public Boolean isOK() {
+        if (null == this.status) {
+            return false;
+        }
+        return this.status == 200;
+    }
+
+    public Integer getStatus() {
+        return status;
+    }
+
+    public void setStatus(Integer status) {
+        this.status = status;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public void setMsg(String msg) {
+        this.msg = msg;
+    }
+
+    public Object getData() {
+        return data;
+    }
+
+    public void setData(Object data) {
+        this.data = data;
+    }
+
+    @Override
+    public String toString() {
+        return "ResultUtil [status=" + status + ", msg=" + msg + ", data=" + data + "]";
+    }
+}

+ 42 - 0
SHA1.java

@@ -0,0 +1,42 @@
+package com.happy.common.util;
+import java.security.MessageDigest;
+
+/**
+ * 微信SHA1算法
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public final class SHA1 {
+
+    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+
+    /**
+     *  将字节并格式化
+     * @param bytes 原始字节
+     * @return 格式化字节
+     */
+    private static String getFormattedText(byte[] bytes) {
+        int len = bytes.length;
+        StringBuilder buf = new StringBuilder(len * 2);
+        // 把密文转换成十六进制的字符串形式
+        for (int j = 0; j < len; j++) {
+            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
+            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
+        }
+        return buf.toString();
+    }
+
+    public static String encode(String str) {
+        if (str == null) {
+            return null;
+        }
+        try {
+            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
+            messageDigest.update(str.getBytes());
+            return getFormattedText(messageDigest.digest());
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+}

+ 845 - 0
StringUtil.java

@@ -0,0 +1,845 @@
+package com.happy.Unitil_elc;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.math.NumberUtils;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.text.BreakIterator;
+import java.text.DecimalFormat;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+
+public class StringUtil {
+
+    /** 空字符串。 */
+    public static final String   EMPTY_STRING        = "";
+
+    private static final char    QUOTE_ENCODE[]      = "&quot;".toCharArray();
+    private static final char    AMP_ENCODE[]        = "&amp;".toCharArray();
+    private static final char    LT_ENCODE[]         = "&lt;".toCharArray();
+    private static final char    GT_ENCODE[]         = "&gt;".toCharArray();
+    private static final int     DUMP_HEX_CHAR_COUNT = 75;
+    private static MessageDigest digest              = null;
+    // private static final int fillchar = 61;
+    private static Random        randGen             = new Random();
+    private static char          numbersAndLetters[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
+    private static final char    zeroArray[]         = "0000000000000000".toCharArray();
+    private static final char[]  base64Chars         = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
+    private static final char[]  upcaseHexChar       = "0123456789ABCDEF".toCharArray();
+    private static final char[]  lowerHexChar        = "0123456789abcdef".toCharArray();
+
+    private static int[]         hexCharCodes        = new int[256];
+
+    private static int[]         base64Codes         = new int[256];
+    static {
+        for (int i = 0; i < 256; i++)
+            hexCharCodes[i] = base64Codes[i] = -1;
+        for (int i = 0; i < base64Chars.length; i++)
+            base64Codes[base64Chars[i]] = (byte) i;
+        for (int i = 0; i < upcaseHexChar.length; i++)
+            hexCharCodes[upcaseHexChar[i]] = (byte) i;
+        for (int i = 0; i < lowerHexChar.length; i++)
+            hexCharCodes[lowerHexChar[i]] = (byte) i;
+    }
+
+    /**
+     * 如果字符串是<code>null</code>,则返回指定默认字符串,否则返回字符串本身。
+     * 
+     * <pre>
+     * StringUtil.defaultIfNull(null, &quot;default&quot;)  = &quot;default&quot;
+     * StringUtil.defaultIfNull(&quot;&quot;, &quot;default&quot;)    = &quot;&quot;
+     * StringUtil.defaultIfNull(&quot;  &quot;, &quot;default&quot;)  = &quot;  &quot;
+     * StringUtil.defaultIfNull(&quot;bat&quot;, &quot;default&quot;) = &quot;bat&quot;
+     * </pre>
+     * 
+     * @param str 要转换的字符串
+     * @param defaultStr 默认字符串
+     * @return 字符串本身或指定的默认字符串
+     */
+    public static String defaultIfNull(String str, String defaultStr) {
+        return (str == null) ? defaultStr : str;
+    }
+
+    public static boolean isDigits(String str) {
+        if ((str == null) || (str.length() == 0)) {
+            return false;
+        }
+        for (int i = 0; i < str.length(); i++) {
+            if (!Character.isDigit(str.charAt(i))) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    public static boolean isDigits(Object obj) {
+        if (obj == null) return false;
+        String str = obj.toString();
+        return isDigits(str);
+    }
+
+    public static final String escapeHTMLTags(String in) {
+        if (in == null) return null;
+        int i = 0;
+        int last = 0;
+        char input[] = in.toCharArray();
+        int len = input.length;
+        StringBuffer out = new StringBuffer((int) ((double) len * 1.3D));
+        for (; i < len; i++) {
+            char ch = input[i];
+            if (ch > '>') continue;
+            if (ch == '<') {
+                if (i > last) out.append(input, last, i - last);
+                last = i + 1;
+                out.append(LT_ENCODE);
+                continue;
+            }
+            if (ch != '>') continue;
+            if (i > last) out.append(input, last, i - last);
+            last = i + 1;
+            out.append(GT_ENCODE);
+        }
+
+        if (last == 0) return in;
+        if (i > last) out.append(input, last, i - last);
+        return out.toString();
+    }
+
+    public static final synchronized String hash(String data) {
+        if (digest == null) try {
+            digest = MessageDigest.getInstance("MD5");
+        } catch (NoSuchAlgorithmException nsae) {
+            System.err.println("Failed to load the MD5 MessageDigest. We will be unable to function normally.");
+            nsae.printStackTrace();
+        }
+        digest.update(data.getBytes());
+        return encodeHex(digest.digest());
+    }
+
+    public static final String encodeHex(byte bytes[]) {
+        char[] buf = new char[bytes.length * 2];
+        for (int i = 0; i < bytes.length; i++) {
+            int code = bytes[i] & 0xff;
+            buf[2 * i] = upcaseHexChar[code >> 4];
+            buf[2 * i + 1] = upcaseHexChar[code & 0xf];
+        }
+        return new String(buf);
+    }
+
+    public static final String dumpHex(byte bytes[]) {
+        int bytepos, bufpos, linecount = (bytes.length + 15) / 16;
+        char[] buf = new char[linecount * DUMP_HEX_CHAR_COUNT];
+        byte[] bs = new byte[16];
+
+        bytepos = 0;
+        for (int i = 0; i < linecount; i++) {
+            int addr = i * 16;
+            bufpos = i * DUMP_HEX_CHAR_COUNT;
+            buf[bufpos++] = upcaseHexChar[(addr >> 12) & 0xf];
+            buf[bufpos++] = upcaseHexChar[(addr >> 8) & 0xf];
+            buf[bufpos++] = upcaseHexChar[(addr >> 4) & 0xf];
+            buf[bufpos++] = upcaseHexChar[(addr) & 0xf];
+            buf[bufpos++] = ' ';
+            buf[bufpos++] = ' ';
+            for (int j = 0; j < 16; j++, bytepos++) {
+                if (bytepos < bytes.length) {
+                    int code = bytes[bytepos] & 0xff;
+                    bs[j] = bytes[bytepos];
+                    buf[bufpos++] = upcaseHexChar[code >> 4];
+                    buf[bufpos++] = upcaseHexChar[code & 0xf];
+                    if (j == 7) buf[bufpos++] = '-';
+                    else buf[bufpos++] = ' ';
+                } else {
+                    buf[bufpos++] = ' ';
+                    buf[bufpos++] = ' ';
+                    buf[bufpos++] = ' ';
+                    bs[j] = ' ';
+                }
+            }
+            buf[bufpos++] = ' ';
+            buf[bufpos++] = ' ';
+            char[] chs = new String(bs).toCharArray();
+            for (int k = 0; k < chs.length; k++) {
+                char ch = chs[k];
+                if ((ch > '\0') && (ch < ' ')) buf[bufpos++] = '.';
+                else buf[bufpos++] = ch;
+
+            }
+            int endLine = (i + 1) * DUMP_HEX_CHAR_COUNT - 2;
+            for (; bufpos < endLine; bufpos++)
+                buf[bufpos] = ' ';
+            buf[bufpos++] = '\r';
+            buf[bufpos++] = '\n';
+        }
+        return new String(buf);
+    }
+
+    public static final byte[] decodeHex(String hex) {
+        char chars[] = hex.toCharArray();
+        byte bytes[] = new byte[chars.length / 2];
+        int byteCount = 0;
+        for (int i = 0; i < chars.length; i += 2) {
+            byte newByte = 0;
+            newByte |= hexCharCodes[chars[i]];
+            newByte <<= 4;
+            newByte |= hexCharCodes[chars[i + 1]];
+            bytes[byteCount] = newByte;
+            byteCount++;
+        }
+
+        return bytes;
+    }
+
+    public static String encodeBase64(String data) {
+        return encodeBase64(data.getBytes());
+    }
+
+    public static String encodeBase64(byte data[]) {
+        int len = data.length;
+        StringBuffer ret = new StringBuffer((len / 3 + 1) * 4);
+        for (int i = 0; i < len; i++) {
+            int c = data[i] >> 2 & 0x3f;
+            ret.append(base64Chars[c]);
+            c = data[i] << 4 & 0x3f;
+            if (++i < len) c |= data[i] >> 4 & 0xf;
+            ret.append(base64Chars[c]);
+            if (i < len) {
+                c = data[i] << 2 & 0x3f;
+                if (++i < len) c |= data[i] >> 6 & 3;
+                ret.append(base64Chars[c]);
+            } else {
+                i++;
+                ret.append('=');
+            }
+            if (i < len) {
+                c = data[i] & 0x3f;
+                ret.append(base64Chars[c]);
+            } else {
+                ret.append('=');
+            }
+        }
+
+        return ret.toString();
+    }
+
+    public static byte[] decodeBase64(String data) {
+        int len = data.length();
+        byte[] result = new byte[((len * 3) / 4)];
+        int pos = 0;
+        for (int i = 0; i < len; i++) {
+
+            int c = base64Codes[data.charAt(i)];
+            i++;
+            int c1 = base64Codes[data.charAt(i)];
+            c = c << 2 | c1 >> 4 & 3;
+            result[pos++] = (byte) c;
+            if (++i < len) {
+                c = data.charAt(i);
+                if (61 == c) break;
+                c = base64Codes[data.charAt(i)];
+                c1 = c1 << 4 & 0xf0 | c >> 2 & 0xf;
+                result[pos++] = (byte) c1;
+            }
+            if (++i >= len) continue;
+            c1 = data.charAt(i);
+            if (61 == c1) break;
+            c1 = base64Codes[data.charAt(i)];
+            c = c << 6 & 0xc0 | c1;
+            result[pos++] = (byte) c;
+        }
+        if (result.length != pos) {
+            byte[] result2 = new byte[pos];
+            System.arraycopy(result, 0, result2, 0, pos);
+            result = result2;
+        }
+        return result;
+    }
+
+    public static final String[] toLowerCaseWordArray(String text) {
+        if (text == null || text.length() == 0) return new String[0];
+        List<String> wordList = new ArrayList<String>();
+        BreakIterator boundary = BreakIterator.getWordInstance();
+        boundary.setText(text);
+        int start = 0;
+        for (int end = boundary.next(); end != -1; end = boundary.next()) {
+            String tmp = text.substring(start, end).trim();
+            tmp = tmp.replace("+", "");
+            tmp = tmp.replace("/", "");
+            tmp = tmp.replace("\\", "");
+            tmp = tmp.replace("#", "");
+            tmp = tmp.replace("*", "");
+            tmp = tmp.replace(")", "");
+            tmp = tmp.replace("(", "");
+            tmp = tmp.replace("&", "");
+            if (tmp.length() > 0) wordList.add(tmp);
+            start = end;
+        }
+
+        return (String[]) (String[]) wordList.toArray(new String[wordList.size()]);
+    }
+
+    public static final String createTempTable() {
+        return "temp_" + StringUtil.randomString(10);
+    }
+
+    /**
+     * 产生指定长度的字符串
+     * 
+     * @param length
+     * @return
+     */
+    public static final String randomString(int length) {
+        if (length < 1) {
+            return null;
+        }
+
+        char randBuffer[] = new char[length];
+        for (int i = 0; i < randBuffer.length; i++)
+            randBuffer[i] = numbersAndLetters[randGen.nextInt(numbersAndLetters.length)];
+
+        return new String(randBuffer);
+    }
+
+    public static final String randomNumber(int length) {
+        Long value = Math.abs(randGen.nextLong());
+        String strValue = value.toString();
+        if (strValue.length() > length) {
+            strValue = strValue.substring(0, length);
+        }
+
+        return strValue;
+    }
+
+    public static final String chopAtWord(String string, int length) {
+        if (string == null) return string;
+        char charArray[] = string.toCharArray();
+        int sLength = string.length();
+        if (length < sLength) sLength = length;
+        for (int i = 0; i < sLength - 1; i++) {
+            if (charArray[i] == '\r' && charArray[i + 1] == '\n') return string.substring(0, i + 1);
+            if (charArray[i] == '\n') return string.substring(0, i);
+        }
+
+        if (charArray[sLength - 1] == '\n') return string.substring(0, sLength - 1);
+        if (string.length() < length) return string;
+        for (int i = length - 1; i > 0; i--)
+            if (charArray[i] == ' ') return string.substring(0, i).trim();
+
+        return string.substring(0, length);
+    }
+
+    public static final String escapeForXML(String string) {
+        if (string == null) return null;
+        int i = 0;
+        int last = 0;
+        char input[] = string.toCharArray();
+        int len = input.length;
+        StringBuffer out = new StringBuffer((int) ((double) len * 1.3D));
+        for (; i < len; i++) {
+            char ch = input[i];
+            if (ch > '>') continue;
+            if (ch == '<') {
+                if (i > last) out.append(input, last, i - last);
+                last = i + 1;
+                out.append(LT_ENCODE);
+                continue;
+            }
+            if (ch == '&') {
+                if (i > last) out.append(input, last, i - last);
+                last = i + 1;
+                out.append(AMP_ENCODE);
+                continue;
+            }
+            if (ch != '"') continue;
+            if (i > last) out.append(input, last, i - last);
+            last = i + 1;
+            out.append(QUOTE_ENCODE);
+        }
+
+        if (last == 0) return string;
+        if (i > last) out.append(input, last, i - last);
+        return out.toString();
+    }
+
+    public static final String unescapeFromXML(String string) {
+        string = string.replace("&lt;", "<");
+        string = string.replace("&gt;", ">");
+        string = string.replace("&quot;", "\"");
+        return string.replace("&amp;", "&");
+    }
+
+    public static final String zeroPadString(String string, int length) {
+        if (string == null || string.length() > length) {
+            return string;
+        } else {
+            StringBuffer buf = new StringBuffer(length);
+            buf.append(zeroArray, 0, length - string.length()).append(string);
+            return buf.toString();
+        }
+    }
+
+    public static final String zeroAppendString(String string, int length) {
+        if (string == null || string.length() > length) {
+            return string;
+        } else {
+            StringBuffer buf = new StringBuffer(length);
+            buf.append(string).append(zeroArray, 0, length - string.length());
+            return buf.toString();
+        }
+    }
+
+    public static final String charPadString(String string, int length, char append) {
+        if (string == null || string.length() > length) {
+            return string;
+        } else {
+            char[] charArray = new char[length - string.length()];
+            for (int i = 0; i < charArray.length; i++) {
+                charArray[i] = append;
+            }
+            StringBuffer buf = new StringBuffer(length);
+            buf.append(charArray, 0, charArray.length).append(string);
+            return buf.toString();
+        }
+    }
+
+    public static final String charAppendString(String string, int length, char append) {
+        if (string == null || string.length() > length) {
+            return string;
+        } else {
+            char[] charArray = new char[length - string.length()];
+            for (int i = 0; i < charArray.length; i++) {
+                charArray[i] = append;
+            }
+            StringBuffer buf = new StringBuffer(length);
+            buf.append(string).append(charArray, 0, charArray.length);
+            return buf.toString();
+        }
+    }
+
+    public static final String dateToMillis(Date date) {
+        return zeroPadString(Long.toString(date.getTime()), 15);
+    }
+
+    public static final String collectionToString(Collection<Object> c, String split) {
+        StringBuilder ret = new StringBuilder();
+        List<Object> a;
+        if (c == null) return null;
+        if (split == null) return null;
+        a = new ArrayList<Object>(c);
+        try {
+            for (int i = 0; i < a.size(); i++) {
+                String t = (String) a.get(i);
+                if (i == a.size() - 1) {
+                    ret.append(t);
+                } else {
+                    ret.append(t).append(split);
+
+                }
+            }
+
+            return ret.toString();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        return null;
+    }
+
+    public static String encodeUrlString(String str) {
+        String strret = null;
+        if (str == null) return str;
+        try {
+            strret = URLEncoder.encode(str, "GBK");
+        } catch (Exception e) {
+            e.printStackTrace(System.err);
+            return null;
+        }
+        return strret;
+    }
+
+    public static String decodeUrlString(String str) {
+        String strret = null;
+        if (str == null) return str;
+        try {
+            strret = URLDecoder.decode(str, "GBK");
+        } catch (Exception e) {
+            e.printStackTrace(System.err);
+            return null;
+        }
+        return strret;
+    }
+
+    public static String join(Object list[], String separator) {
+        int listSize = list.length;
+        int bufSize = listSize == 0 ? 0 : (list[0].toString().length() + separator.length()) * listSize;
+        StringBuffer buf = new StringBuffer(bufSize);
+        for (int i = 0; i < listSize; i++) {
+            if (i > 0) buf.append(separator);
+            buf.append(list[i]);
+        }
+
+        return buf.toString();
+    }
+
+    public static String join(Iterator<?> iterator, String separator) {
+        StringBuffer buf = new StringBuffer();
+        do {
+            if (!iterator.hasNext()) break;
+            buf.append(iterator.next());
+            if (iterator.hasNext()) buf.append(separator);
+        } while (true);
+        return buf.toString();
+    }
+
+    public static boolean isEmpty(String param) {
+        return param == null || "".equals(param) || "".equals(param.trim()) || "null".equals(param) || "\"null\"".equals(param) || "undefined".equals(param) || "[]".equals(param);
+    }
+
+    public static boolean isNotEmpty(String param) {
+        return !isEmpty(param);
+    }
+
+    public static int getDecimalplace(String factor) {
+        int pointPos = factor.indexOf(".");
+        int onePos = factor.indexOf("1");
+        int precision = onePos - pointPos;
+        return precision > 0 ? precision : 0;
+    }
+
+    /**
+     * 对字符串做定长处理,超过长度,截取,长度不够补在前方补齐
+     * 
+     * @param str
+     * @param len
+     * @param appendStr 补齐的字符,
+     * @return
+     */
+    public static String AddjustLength(String str, int len, String appendStr) {
+        if (str == null) {
+            return null;
+        }
+        if (str.length() == len) {
+            return str;
+        } else if (str.length() < len) {
+            StringBuffer buf = new StringBuffer(len);
+            for (int i = 0; i < len - str.length(); i++) {
+                buf.append(appendStr);
+            }
+            buf.append(str);
+            if (buf.length() > len) {
+                return buf.substring(buf.length() - len);
+            } else {
+                return buf.toString();
+            }
+        } else {
+            return str.substring(str.length() - len, str.length());
+        }
+    }
+
+    /**
+     * 比较separator分隔的2个字符串是否相等
+     * 
+     * @param str1
+     * @param str2
+     * @param separator 字符串分隔符
+     * @return
+     */
+    public static boolean isEquals(String str1, String str2, String separator) {
+        if (StringUtils.isEmpty(str1) && StringUtils.isEmpty(str2)) {
+            return false;
+        }
+        String[] str1Array = StringUtils.split(str1, separator);
+        String[] str2Array = StringUtils.split(str2, separator);
+
+        if (str1Array.length != str2Array.length) {
+            return false;
+        }
+
+        List<String> refList = new ArrayList<String>();
+        for (String refStr : str1Array) {
+            refList.add(refStr);
+        }
+
+        for (String desStr : str2Array) {
+            if (!refList.contains(desStr)) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * 转换字符串分隔的字符串为Integer数组
+     * 
+     * @param values
+     * @param spare
+     * @return
+     */
+    public static List<Integer> parseIntList(String values, String spare) {
+        List<Integer> list = new ArrayList<Integer>();
+        String[] valueArray = StringUtils.split(values, spare);
+        if (valueArray != null) {
+            for (String value : valueArray) {
+                if (NumberUtils.isDigits(value)) {
+                    list.add(NumberUtils.toInt(value));
+                }
+            }
+        }
+        return list;
+
+    }
+
+    public static double parseDouble(String src) {
+        if (!isEmpty(src)) {
+            return Double.parseDouble(src);
+        }
+        return 0;
+    }
+
+    public static int parseInt(String src) {
+        if (!isEmpty(src)) {
+            return Integer.parseInt(src);
+        }
+        return 0;
+    }
+
+    public static long parseLong(String src) {
+        if (!isEmpty(src)) {
+            return Long.parseLong(src);
+        }
+        return 0;
+    }
+
+    public static String format(String number, int decimalDigits) {
+        if (!StringUtil.isEmpty(number) && NumberUtils.isDigits(number)) {
+            return StringUtil.format(Double.parseDouble(number), decimalDigits);
+        } else {
+            return number;
+        }
+    }
+
+    public static String trim(String src) {
+        return src == null ? "" : src.trim();
+    }
+
+    /**
+     * 数字格式化函数
+     * 
+     * @param number : 格式化前的数字;
+     * @param decimalDigits : 小数位数;
+     * @return: 字符串;
+     */
+    public static String format(double number, int decimalDigits) {
+        if (number == 0d) {
+            number = 0d;
+        }
+
+        boolean flag = false;
+        if (decimalDigits < 0) {
+            // 小数位数不能小于0.
+            return "";
+        }
+
+        String pattern = "##################";
+        if (decimalDigits > 0) {
+            flag = true;
+            pattern += ".";
+            for (int i = 0; i < decimalDigits; i++) {
+                pattern += "0";
+            }
+        }
+
+        DecimalFormat df = new DecimalFormat(pattern);
+        if (number <= -1d) {
+            return df.format(number);
+        } else if (number > -1d && number < 0d) {
+            return "-0" + df.format(number).substring(1);
+        } else if (number >= 0d && number < 1d) {
+            if (flag) {
+                String temp = df.format(number);
+                if (StringUtil.isNotEmpty(temp) && temp.substring(0, 1).equals(".")) {
+                    return "0" + df.format(number);
+                } else {
+                    return temp;
+                }
+            } else {
+                return df.format(number);
+            }
+        } else {
+            return df.format(number);
+        }
+    }
+
+    public static Integer toInteger(Object object) {
+        if (object == null) {
+            return 0;
+        }
+        return Integer.valueOf(object.toString());
+    }
+
+    public static Short toShort(Object object) {
+        if (object == null) {
+            return null;
+        }
+        return Short.valueOf(object.toString());
+    }
+
+    public static String objectToString(Object obj) {
+        if (obj == null) {
+            return null;
+        } else {
+            return obj.toString();
+        }
+    }
+
+    /**
+     * 字串逆排
+     * 
+     * @return
+     */
+    public static String revert(String src) {
+        if (isEmpty(src)) return "";
+        StringBuffer result = new StringBuffer();
+        for (int i = src.length() - 1; i >= 0; i--) {
+            result.append(src.charAt(i));
+        }
+        return result.toString();
+    }
+
+    public static boolean isValidateString(String path) {
+        if (StringUtil.isEmpty(path)) {
+            return false;
+        } else {
+            return true;
+        }
+    }
+
+    public static String encodingUtf8(String src) throws UnsupportedEncodingException {
+        if (isEmpty(src)) return "";
+        return new String(src.getBytes("ISO-8859-1"), "UTF-8");
+    }
+
+    public static String encodingJson(String src) throws UnsupportedEncodingException {
+        if (isEmpty(src)) return "";
+        int pos = src.indexOf("\\u");
+        StringBuffer sb = new StringBuffer();
+        while (pos >= 0 && (pos + 6 <= src.length())) {
+            sb.append(src.substring(0, pos));
+            String temp = src.substring(pos + 2, pos + 6);
+            sb.append((char) Integer.parseInt(temp, 16));// 将\u6d4b\u8bd5
+                                                         // 格式的文字转为
+                                                         // 正常的string编码
+                                                         // “测试”(因为Ext.encode(array)的方法解析出来是jsonarray格式)
+            src = src.substring(pos + 6);
+            pos = src.indexOf("\\u");
+        }
+        sb.append(src);
+        return sb.toString();
+    }
+
+    /**
+     * 正则
+     */
+    public static String replaceBlank(String str) {
+        String dest = "";
+        if (str != null) {
+            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
+            Matcher m = p.matcher(str);
+            dest = m.replaceAll("");
+        }
+        return dest;
+    }
+
+    /**
+     * 不定参数校验空
+     * 
+     * @param args
+     * @return
+     */
+    public static boolean isNull(String... args) {
+        for (String arg : args) {
+            if (StringUtils.isEmpty(arg)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 不定参数校验数字
+     * 
+     * @param args
+     * @return
+     */
+    public static boolean isNotNumber(String... args) {
+        for (String arg : args) {
+            if (!NumberUtils.isDigits(arg)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * 不定参数校验数字
+     * 
+     * @param args
+     * @return
+     */
+    public static boolean isNotDigits(String... args) {
+        for (String arg : args) {
+            if (!NumberUtils.isDigits(arg)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * toString增加判空
+     */
+    public static String toString(Object obj) {
+        if(obj == null) {
+            return "";
+        }
+        return obj.toString();
+    }
+
+    /**
+     * @param value:十进制字字符
+     * @param radix:目标进制
+     * @param length:目标长度
+     * @param pad:前补的字符
+     * @return
+     */
+    public static String numStr2PadString(String value, int radix, int length, String pad) {
+        if (value == null) return charPad("", length, pad);
+        // Integer temp = NumberUtils.toInt(value);
+        String result = Integer.toString(NumberUtils.toInt(value), radix);
+        return AddjustLength(result, length, pad);
+    }
+
+    public static String charPad(String value, int length, String pad) {
+        if (value == null || value.length() > length) return value;
+        String padString = "";
+        for (int i = 0; i < (length - value.length()); i++) {
+            padString += pad;
+        }
+        return padString + value;
+    }
+
+    public static void main(String[] args) {
+        System.out.println("operator_secret: " + randomString(17));
+        System.out.println("data_secret: " + randomString(16));
+        System.out.println("data_secret_iv: " + randomString(16));
+        System.out.println("sign_secret: " + randomString(19));
+
+    }
+}

+ 21 - 0
Test.java

@@ -0,0 +1,21 @@
+package testExport;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.List;
+
+public class Test {
+
+    public static void main(String[] args) {
+        List<String> dateList = new ArrayList<>();
+        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
+        for (int i=0;i>-12;i--){
+            Calendar calendar = Calendar.getInstance();
+            calendar.add(Calendar.MONTH,i);
+            dateList.add(simpleDateFormat.format(calendar.getTime()));
+        }
+        System.out.println(dateList);
+    }
+
+}

+ 21 - 0
TokenUtil.java

@@ -0,0 +1,21 @@
+package com.happy.Until;
+
+import org.apache.commons.lang.StringUtils;
+
+import javax.servlet.http.HttpServletRequest;
+
+public class TokenUtil {
+    /**
+     * 获取请求的token
+     */
+    public static String getRequestToken(HttpServletRequest httpRequest) {
+
+        //从header中获取token
+        String token = httpRequest.getHeader("token");
+        //如果header中不存在token,则从参数中获取token
+        if (StringUtils.isBlank(token)) {
+            token = httpRequest.getParameter("token");
+        }
+        return token;
+    }
+}

+ 84 - 0
TongYiReturn.java

@@ -0,0 +1,84 @@
+package com.happy.Until.weixin;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * 调用统一下单接口返回的数据实体类
+ * @author QT-666
+ *
+ */
+@XmlRootElement(name="xml")
+public class TongYiReturn {
+    private String return_code; //
+    private String return_msg;  // 
+    private String appid;       // 调用接口提交的公众账号ID
+    private String mch_id;      // 调用接口提交的商户号
+    private String nonce_str;   //微信返回的随机字符串
+    private String sign;        //微信返回的签名值,详见签名算法
+    private String prepay_id;   //微信生成的预支付会话标识,用于后续接口调用中使用,该值有效期为2小时
+    private String result_code; //SUCCESS/FAIL
+    private String trade_type;  //交易类型,取值为:JSAPI,NATIVE,APP等,说明详见参数规定
+	public String getReturn_code() {
+		return return_code;
+	}
+	public void setReturn_code(String return_code) {
+		this.return_code = return_code;
+	}
+	public String getReturn_msg() {
+		return return_msg;
+	}
+	public void setReturn_msg(String return_msg) {
+		this.return_msg = return_msg;
+	}
+	public String getAppid() {
+		return appid;
+	}
+	public void setAppid(String appid) {
+		this.appid = appid;
+	}
+	public String getMch_id() {
+		return mch_id;
+	}
+	public void setMch_id(String mch_id) {
+		this.mch_id = mch_id;
+	}
+	public String getNonce_str() {
+		return nonce_str;
+	}
+	public void setNonce_str(String nonce_str) {
+		this.nonce_str = nonce_str;
+	}
+	public String getSign() {
+		return sign;
+	}
+	public void setSign(String sign) {
+		this.sign = sign;
+	}
+	public String getPrepay_id() {
+		return prepay_id;
+	}
+	public void setPrepay_id(String prepay_id) {
+		this.prepay_id = prepay_id;
+	}
+	public String getResult_code() {
+		return result_code;
+	}
+	public void setResult_code(String result_code) {
+		this.result_code = result_code;
+	}
+	public String getTrade_type() {
+		return trade_type;
+	}
+	public void setTrade_type(String trade_type) {
+		this.trade_type = trade_type;
+	}
+	@Override
+	public String toString() {
+		return "TongYiReturn [return_code=" + return_code + ", return_msg="
+				+ return_msg + ", appid=" + appid + ", mch_id=" + mch_id
+				+ ", nonce_str=" + nonce_str + ", sign=" + sign
+				+ ", prepay_id=" + prepay_id + ", result_code=" + result_code
+				+ ", trade_type=" + trade_type + "]";
+	}
+    
+}

+ 163 - 0
User.java

@@ -0,0 +1,163 @@
+package com.happy.action;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+import com.happy.Until.ResUtil;
+import com.happy.service.UserService;
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.opensymphony.xwork2.ActionSupport;
+import net.sf.json.JSONObject;
+import org.apache.struts2.ServletActionContext;
+import org.apache.struts2.interceptor.ServletRequestAware;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.util.HashMap;
+import java.util.List;
+
+public class User extends ActionSupport implements ServletRequestAware {
+
+    private HttpServletRequest request;
+
+    public HttpServletResponse response;
+
+    @Resource
+    private UserService userService;
+
+    public String card_number;
+
+    public String password;
+
+    public String user;
+
+    public HttpServletRequest getRequest() {
+        return request;
+    }
+
+    public void setRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public void setServletRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public HttpServletResponse getResponse() {
+        return response;
+    }
+
+    public void setResponse(HttpServletResponse response) {
+        this.response = response;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getPassword() {
+        return password;
+    }
+
+    public void setPassword(String password) {
+        this.password = password;
+    }
+
+    public UserService getUserService() {
+        return userService;
+    }
+
+    public void setUserService(UserService userService) {
+        this.userService = userService;
+    }
+
+    public String getUser() {
+        return user;
+    }
+
+    public void setUser(String user) {
+        this.user = user;
+    }
+
+    public String log() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        List<Login> login = userService.log(card_number, password);
+        if (login == null) {
+            resultJson.put("info", "信息错误!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        } else {
+            String access_token = userService.createToken(login.get(0));
+            resultJson.put("access_token", access_token);
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        return null;
+    }
+
+    public String list(){
+        return "list";
+    }
+
+
+//    public String stu_info() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        if(user != null) {
+//            Gson gson=new Gson();
+//            HashMap<String, Object> userMap = gson.fromJson(user.toString(), new TypeToken<HashMap<String, Object>>(){}.getType());
+//            String nb = userMap.get("card_number").toString();
+//            List<Users> use = userService.selectByStu(nb);
+//            if(use == null) {
+//                Users users = new Users();
+//                System.out.println(userMap);
+//                users.setCard_number(userMap.get("card_number").toString());
+//                users.setUser_name(userMap.get("name").toString());
+//                users.setUser_phone(userMap.get("telephone").toString());
+//                users.setCampus(userMap.get("campus").toString());
+//                users.setBuild(userMap.get("dorm_number").toString());
+//                users.setDom(userMap.get("dorm_number").toString());
+//                users.setId_card(userMap.get("id_card").toString());
+//                userService.insertUser(users);
+//                resultJson.put("mess", "绑定成功!");
+//                resultJson.put("info", users);
+//                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            }else {
+//                resultJson.put("erro", "请不要重复绑定!");
+//                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            }
+//        }else{
+//            resultJson.put("erro", "未获取到数据!");
+//            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        }
+//        return null;
+//    }
+//
+//    public String get_stu() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        List<Users> use = userService.selectByCard(card_number);
+//        if (use == null){
+//            resultJson.put("info", "未查询到绑定信息");
+//        }else {
+//            resultJson.put("info", use);
+//        }
+//        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        return null;
+//    }
+//
+//    public String del_stu() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        int num = userService.delUser(card_number);
+//        if (num > 0) {
+//            resultJson.put("mess", "删除成功");
+//        }else {
+//            resultJson.put("mess", "删除异常");
+//        }
+//        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        return null;
+//    }
+}

+ 25 - 0
UserDao.java

@@ -0,0 +1,25 @@
+package com.happy.dao;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+
+import java.util.List;
+
+public interface UserDao {
+
+	public List<Login> log(String card_number, String password);
+
+	public int save(Login login);
+
+	public List<Login> findByToken(String access_token);
+
+	public List<Users> selectByStu(String stu_number);
+
+	public int insertUser(Users users);
+
+	public int delUser(String card_number);
+
+	public int updateOpenid(String openid,String stu_number, String id_card);
+
+	public List<Users> queryByopenid(String openid);
+}

+ 140 - 0
UserDaoImpl.java

@@ -0,0 +1,140 @@
+package com.happy.dao.impl;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+import com.happy.dao.UserDao;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository("userDao")
+public class UserDaoImpl implements UserDao {
+
+	@Autowired
+	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
+
+	public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
+		return namedParameterJdbcTemplate;
+	}
+
+	public void setNamedParameterJdbcTemplate(
+			NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
+		this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
+	}
+
+	public List<Login> log(String card_number, String password){
+		String sql="select * from login where card_number=:card_number and password=:password";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("card_number", card_number);
+		sps.addValue("password", password);
+		List<Login> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Login>(Login.class));
+		if(list != null && list.size() >0){
+			return list;
+		}
+		return null;
+	}
+
+	public int save(Login login){
+        String sql = "update login set login_time=:login_time, expire_time=:expire_time, access_token=:access_token where card_number=:card_number";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("login_time", login.getLogin_time());
+		sps.addValue("expire_time", login.getExpire_time());
+		sps.addValue("access_token", login.getAccess_token());
+		sps.addValue("card_number", login.getCard_number());
+		int num = 0;
+		try{
+			num = namedParameterJdbcTemplate.update(sql, sps);
+		}
+		catch(Exception e){
+			e.printStackTrace();
+		}
+		return num;
+	}
+
+	public List<Login> findByToken(String access_token){
+		String sql = "select * from login where access_token=:access_token";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("access_token", access_token);
+		List<Login> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Login>(Login.class));
+		if(list != null && list.size() >0){
+			return list;
+		}
+		return null;
+	}
+
+	public List<Users> selectByStu(String stu_number){
+		String sql = "select * from users where stu_number=:stu_number";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("stu_number", stu_number);
+		List<Users> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Users>(Users.class));
+		if (list != null && list.size() > 0) {
+			return list;
+		}
+		return null;
+	}
+
+    public int insertUser(Users users){
+		String sql = "insert into users(card_number, user_name, user_phone, campus, build, dom, id_card) values(:card_number, :user_name, :user_phone, :campus, :build, :dom, :id_card)";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("card_number", users.getCard_number());
+		sps.addValue("user_name", users.getUser_name());
+		sps.addValue("user_phone", users.getUser_phone());
+		sps.addValue("campus", users.getCampus());
+		sps.addValue("build", users.getBuild());
+		sps.addValue("dom", users.getDom());
+		sps.addValue("id_card", users.getCard_number());
+		int num = 0;
+		try{
+			num = namedParameterJdbcTemplate.update(sql, sps);
+		}
+		catch(Exception e){
+			e.printStackTrace();
+		}
+		return num;
+	}
+
+	public int delUser(String card_number){
+		String sql = "delete from users where card_number=:card_number";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("card_number", card_number);
+		int num = 0;
+		try{
+			num = namedParameterJdbcTemplate.update(sql, sps);
+		}
+		catch(Exception e){
+			e.printStackTrace();
+		}
+		return num;
+	}
+
+	public int updateOpenid(String openid,String stu_number, String id_card){
+		String sql = "update users set openid=:openid where stu_number=:stu_number and id_card=:id_card";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("openid", openid);
+		sps.addValue("stu_number", stu_number);
+		sps.addValue("id_card", id_card);
+		int num = 0;
+		try{
+			num = namedParameterJdbcTemplate.update(sql, sps);
+		}
+		catch(Exception e){
+			e.printStackTrace();
+		}
+		return num;
+	}
+
+	public List<Users> queryByopenid(String openid){
+		String sql = "select * from users where openid=:openid";
+		MapSqlParameterSource sps = new MapSqlParameterSource();
+		sps.addValue("openid", openid);
+		List<Users> list=namedParameterJdbcTemplate.query(sql, sps,new BeanPropertyRowMapper<Users>(Users.class));
+		if (list != null && list.size() > 0) {
+			return list;
+		}
+		return null;
+	}
+}

+ 12 - 0
UserLoginToken.java

@@ -0,0 +1,12 @@
+package com.happy.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ElementType.METHOD, ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface UserLoginToken {
+    boolean required() default true;
+}

+ 27 - 0
UserService.java

@@ -0,0 +1,27 @@
+package com.happy.service;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+
+import java.util.List;
+
+public interface UserService {
+
+	public List<Login> log(String card_number, String password);
+
+	public int save(Login login);
+
+	public String createToken(Login login);
+
+	public List<Login> findByToken(String access_token);
+
+	public List<Users> selectByStu(String stu_number);
+
+	public int insertUser(Users users);
+
+	public int delUser(String card_number);
+
+	public int updateOpenid(String openid,String stu_number, String id_card);
+
+	public List<Users> queryByopenid(String openid);
+}

+ 76 - 0
UserServiceImpl.java

@@ -0,0 +1,76 @@
+package com.happy.service.impl;
+
+import com.happy.Model.Login;
+import com.happy.Model.Users;
+import com.happy.dao.UserDao;
+import com.happy.service.UserService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.time.LocalDateTime;
+import java.util.List;
+import java.util.UUID;
+
+@Service("userService")
+public class UserServiceImpl implements UserService {
+	@Resource
+	private UserDao userDao;
+
+	public UserDao getUserDao() {
+		return userDao;
+	}
+
+	public void setUserDao(UserDao userDao) {
+		this.userDao = userDao;
+	}
+
+	public List<Login> log(String card_number, String password){
+		return userDao.log(card_number, password);
+	}
+
+	public int save(Login login){
+		return userDao.save(login);
+	}
+
+	//12小时后失效
+	private final static int EXPIRE = 12;
+
+	public String createToken(Login login) {
+		//用UUID生成token
+		String token = UUID.randomUUID().toString();
+		//当前时间
+		LocalDateTime now = LocalDateTime.now();
+		//过期时间
+		LocalDateTime expireTime = now.plusHours(EXPIRE);
+		//保存到数据库
+		login.setLogin_time(now.toString().replace("T", " "));
+		login.setExpire_time(expireTime.toString().replace("T", " "));
+		login.setAccess_token(token);
+		userDao.save(login);
+		return token;
+	}
+
+	public List<Login> findByToken(String access_token){
+		return userDao.findByToken(access_token);
+	}
+
+	public List<Users> selectByStu(String stu_number){
+		return userDao.selectByStu(stu_number);
+	}
+
+	public int insertUser(Users users){
+		return userDao.insertUser(users);
+	}
+
+	public int delUser(String card_number){
+		return userDao.delUser(card_number);
+	}
+
+	public int updateOpenid(String openid,String stu_number,String id_card){
+		return userDao.updateOpenid(openid, stu_number, id_card);
+	}
+
+	public List<Users> queryByopenid(String openid){
+		return userDao.queryByopenid(openid);
+	}
+}

+ 115 - 0
Users.java

@@ -0,0 +1,115 @@
+package com.happy.Model;
+
+import java.math.BigDecimal;
+
+public class Users {
+
+     public Integer id;
+     public String stu_number;
+     public String card_number;
+     public String user_name;
+     public String user_phone;
+     public String user_level;
+     public double balance;
+     public String campus;
+     public String build;
+     public String dom;
+     public String id_card;
+     public String remark;
+
+    public Integer getId() {
+        return id;
+    }
+
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public String getCard_number() {
+        return card_number;
+    }
+
+    public void setCard_number(String card_number) {
+        this.card_number = card_number;
+    }
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public String getUser_phone() {
+        return user_phone;
+    }
+
+    public void setUser_phone(String user_phone) {
+        this.user_phone = user_phone;
+    }
+
+    public String getUser_level() {
+        return user_level;
+    }
+
+    public void setUser_level(String user_level) {
+        this.user_level = user_level;
+    }
+
+    public double getBalance() {
+        return balance;
+    }
+
+    public void setBalance(double balance) {
+        this.balance = balance;
+    }
+
+    public String getCampus() {
+        return campus;
+    }
+
+    public void setCampus(String campus) {
+        this.campus = campus;
+    }
+
+    public String getBuild() {
+        return build;
+    }
+
+    public void setBuild(String build) {
+        this.build = build;
+    }
+
+    public String getDom() {
+        return dom;
+    }
+
+    public void setDom(String dom) {
+        this.dom = dom;
+    }
+
+    public String getId_card() {
+        return id_card;
+    }
+
+    public void setId_card(String id_card) {
+        this.id_card = id_card;
+    }
+
+    public String getRemark() {
+        return remark;
+    }
+
+    public void setRemark(String remark) {
+        this.remark = remark;
+    }
+}

+ 23 - 0
WebMvcConfig.java

@@ -0,0 +1,23 @@
+package com.happy.config;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.CorsRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
+
+/**
+ * @author yp
+ * @date 2020/2/23
+ * 解决跨域问题
+ */
+@Configuration
+public class WebMvcConfig extends WebMvcConfigurerAdapter {
+
+    @Override
+    public void addCorsMappings(CorsRegistry registry) {
+        registry.addMapping("/**")
+                .allowedOrigins("*")
+                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
+                .maxAge(3600)
+                .allowCredentials(true);
+    }
+}

+ 105 - 0
WechatUnifiedOrder.java

@@ -0,0 +1,105 @@
+package com.happy.Model.weixin;
+
+import javax.xml.bind.annotation.XmlRootElement;
+import java.io.Serializable;
+
+/**
+ * 统一下单实体类
+ * @author QT-666
+ *
+ */
+@XmlRootElement(name="xml")
+public class WechatUnifiedOrder implements Serializable{
+	private String appid;   //微信支付分配的公众账号ID(企业号corpid即为此appId)
+	private String mch_id;  //微信支付分配的商户号
+	private String nonce_str;   //随机字符串,长度要求在32位以内。推荐随机数生成算法
+	private String sign;  //通过签名算法计算得出的签名值,详见签名生成算法
+	private String body;   //商品简单描述,该字段请按照规范传递,具体请见参数规定
+	private String out_trade_no;  //	商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*@ ,且在同一个商户号下唯一。详见商户订单号
+	private int total_fee;   //订单总金额,单位为分,详见支付金额
+	private String spbill_create_ip;  //APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。
+	private String notify_url;   //异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。
+	private String trade_type;  //取值如下:JSAPI,NATIVE,APP等,说明详见参数规定
+	private String openid;   //trade_type=JSAPI时(即公众号支付),此参数必传,此参数为微信用户在商户对应appid下的唯一标识
+	private String attach;//数据包
+	
+	public String getAttach() {
+		return attach;
+	}
+	public void setAttach(String attach) {
+		this.attach = attach;
+	}
+	public String getAppid() {
+		return appid;
+	}
+	public void setAppid(String appid) {
+		this.appid = appid;
+	}
+	public String getMch_id() {
+		return mch_id;
+	}
+	public void setMch_id(String mch_id) {
+		this.mch_id = mch_id;
+	}
+	public String getNonce_str() {
+		return nonce_str;
+	}
+	public void setNonce_str(String nonce_str) {
+		this.nonce_str = nonce_str;
+	}
+	public String getSign() {
+		return sign;
+	}
+	public void setSign(String sign) {
+		this.sign = sign;
+	}
+	public String getBody() {
+		return body;
+	}
+	public void setBody(String body) {
+		this.body = body;
+	}
+	public String getOut_trade_no() {
+		return out_trade_no;
+	}
+	public void setOut_trade_no(String out_trade_no) {
+		this.out_trade_no = out_trade_no;
+	}
+
+
+	public int getTotal_fee() {
+		return total_fee;
+	}
+	public void setTotal_fee(int total_fee) {
+		this.total_fee = total_fee;
+	}
+	public String getSpbill_create_ip() {
+		return spbill_create_ip;
+	}
+	public void setSpbill_create_ip(String spbill_create_ip) {
+		this.spbill_create_ip = spbill_create_ip;
+	}
+	public String getNotify_url() {
+		return notify_url;
+	}
+	public void setNotify_url(String notify_url) {
+		this.notify_url = notify_url;
+	}
+	public String getTrade_type() {
+		return trade_type;
+	}
+	public void setTrade_type(String trade_type) {
+		this.trade_type = trade_type;
+	}
+	public String getOpenid() {
+		return openid;
+	}
+	public void setOpenid(String openid) {
+		this.openid = openid;
+	}
+	
+
+	
+	
+
+}

+ 19 - 0
WeiXinUtil.java

@@ -0,0 +1,19 @@
+package com.happy.Model;
+
+public class WeiXinUtil {
+
+    public static String app_key = "5AA49F3E4CACA380";
+    public static String app_secret = "58D34C81D82B35179ED896C4362B0FC0";
+    public static String ocode = "1015730314";
+    public static String ip = "https://jtishfw.ncjti.edu.cn/jxch-smartmp/HotWaters/";
+    // 小程序的热水
+    public static String appid = "wx2fc3f45732fae5d3";
+    public static String screct = "7eee4a49a4470a77f9222995e8511547";
+    public static String APIid = "chuanghaikeji1612274012888888888";
+    public static String account = "1612274012";
+    // 小程序电费
+    public static String appid_elc = "wx2fc3f45732fae5d3";
+    public static String screct_elc = "7eee4a49a4470a77f9222995e8511547";
+    public static String APIid_elc = "chuanghaikeji1612322883333333333";
+    public static String account_elc = "1612322883";
+}

+ 693 - 0
Wp.java

@@ -0,0 +1,693 @@
+package com.happy.action;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+import com.happy.Model.*;
+import com.happy.Model.weixin.Pay;
+import com.happy.Model.weixin.PayResult;
+import com.happy.Model.weixin.WechatUnifiedOrder;
+import com.happy.Until.HttpUtils;
+import com.happy.Until.ResUtil;
+import com.happy.Until.ResponseUtil;
+import com.happy.Until.weixin.EndPay;
+import com.happy.Until.weixin.JaxbUtil;
+import com.happy.Until.weixin.PayWxUtil;
+import com.happy.Until.weixin.TongYiReturn;
+import com.happy.common.http.HttpsClient;
+import com.happy.common.wx.WxConfig;
+import com.happy.common.wx.WxConstants;
+import com.happy.common.wx.WxUtil;
+import com.happy.service.ConsumeService;
+import com.happy.service.RechargeService;
+import com.happy.service.UserService;
+import com.happy.service.WxMenuService;
+import com.opensymphony.xwork2.ActionSupport;
+import net.sf.json.JSONObject;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.struts2.ServletActionContext;
+import org.apache.struts2.interceptor.ServletRequestAware;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.BufferedReader;
+import java.io.PrintWriter;
+import java.math.BigDecimal;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class Wp extends ActionSupport implements ServletRequestAware {
+
+    private HttpServletRequest request;
+    public HttpServletResponse response;
+
+    public String code;
+    public String stu_number;
+    public String id_card;
+    public String begin_time;
+    public String collect_code;
+    public String user_name;
+    public String re_time;
+
+    @Resource
+    public UserService userService;
+    @Resource
+    public ConsumeService consumeService;
+    @Resource
+    public RechargeService rechargeService;
+    @Resource
+    public WxMenuService wxMenuService;
+
+    public String getUser_name() {
+        return user_name;
+    }
+
+    public void setUser_name(String user_name) {
+        this.user_name = user_name;
+    }
+
+    public String getCollect_code() {
+        return collect_code;
+    }
+
+    public void setCollect_code(String collect_code) {
+        this.collect_code = collect_code;
+    }
+
+    public String getBegin_time() {
+        return begin_time;
+    }
+
+    public void setBegin_time(String begin_time) {
+        this.begin_time = begin_time;
+    }
+
+    public String getId_card() {
+        return id_card;
+    }
+
+    public void setId_card(String id_card) {
+        this.id_card = id_card;
+    }
+
+    public String getStu_number() {
+        return stu_number;
+    }
+
+    public void setStu_number(String stu_number) {
+        this.stu_number = stu_number;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    public HttpServletRequest getRequest() {
+        return request;
+    }
+
+    public void setRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public void setServletRequest(HttpServletRequest request) {
+        this.request = request;
+    }
+
+    public HttpServletResponse getResponse() {
+        return response;
+    }
+
+    public void setResponse(HttpServletResponse response) {
+        this.response = response;
+    }
+
+    public String getRe_time() {
+        return re_time;
+    }
+
+    public void setRe_time(String re_time) {
+        this.re_time = re_time;
+    }
+
+    public String openid() throws Exception {
+        Gson gson=new Gson();
+        JSONObject resultJson = new JSONObject();
+        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
+                "appid="+ WeiXinUtil.appid +
+                "&secret="+ WeiXinUtil.screct +
+                "&js_code="+code+
+                "&grant_type=authorization_code";
+        if (code==null){
+            resultJson.put("mess", "code不能为空");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        String json = HttpsClient.sendPost(url, "");
+        HashMap<String, String> userMap = gson.fromJson(json.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
+        String openid = "";
+        try {
+            openid = userMap.get("openid").toString();
+        }catch (Exception e){
+            resultJson.put("mess", "openid获取失败");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        System.out.println("openid: "+openid);
+        int num = userService.updateOpenid(openid, stu_number, id_card);
+        if (num > 0){
+            resultJson.put("mess", "绑定成功");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        resultJson.put("mess", "绑定异常");
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+    public String get_stu() throws Exception {
+        Gson gson=new Gson();
+        JSONObject resultJson = new JSONObject();
+        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
+                "appid="+ WeiXinUtil.appid +
+                "&secret="+ WeiXinUtil.screct +
+                "&js_code="+code+
+                "&grant_type=authorization_code";
+        if (code==null){
+            resultJson.put("mess", "code不能为空");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        String json = HttpsClient.sendPost(url, "");
+        HashMap<String, String> userMap = gson.fromJson(json.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
+        String openid = "";
+        try{
+            openid = userMap.get("openid").toString();
+        }catch (Exception e){
+            resultJson.put("mess", "code超时");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        List<Users> use = userService.queryByopenid(openid);
+        if (use == null){
+            resultJson.put("mess", "未查询到用户信息");
+        }else {
+            resultJson.put("mess", "返回成功");
+            resultJson.put("info", use);
+        }
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+    public String queryConsume() throws Exception {
+        JSONObject resultJson = new JSONObject();
+        if (stu_number==null){
+            resultJson.put("mess", "学号异常");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        List<Consume> consumes = consumeService.queryRecordByStu(stu_number, begin_time);
+        if (consumes==null){
+            resultJson.put("mess", "本月无消费记录");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        resultJson.put("mess", "返回成功");
+        resultJson.put("data", consumes);
+        ResUtil.write(resultJson, ServletActionContext.getResponse());
+        return null;
+    }
+
+    // 统一下单生成 第四步,页面传入用户输入金额,ip,生成预支付订单,把微信回调的参数传递给页面,页面就可以调起支付
+    public String Pay() throws Exception {
+        HttpSession session = request.getSession();
+        Gson gson=new Gson();
+        JSONObject resultJson = new JSONObject();
+        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
+                "appid="+ WeiXinUtil.appid +
+                "&secret="+ WeiXinUtil.screct +
+                "&js_code="+code+
+                "&grant_type=authorization_code";
+        if (code==null){
+            resultJson.put("mess", "code不能为空");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        String jsons = HttpsClient.sendPost(url, "");
+        HashMap<String, String> userMap = gson.fromJson(jsons.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
+        String open_id = "";
+        try{
+            open_id = userMap.get("openid").toString();
+
+        }catch (Exception e){
+            resultJson.put("mess", "code超时");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        List<Users> u = userService.queryByopenid(open_id);  // 查找是不是会员,不是会员不能充值
+        String num = request.getParameter("num");
+        session.setAttribute("num", num);// 存入金额session中
+        if (u != null  ) {
+            String ip = request.getParameter("ip");
+            double money = Double.parseDouble(request.getParameter("num"));
+            int a = (int) (money * 100);
+            WechatUnifiedOrder w = new WechatUnifiedOrder();
+            w.setAppid(WeiXinUtil.appid);
+            w.setAttach("chuanghai");
+            w.setBody("chuanghai");
+            w.setMch_id(WeiXinUtil.account);
+            w.setNonce_str(PayWxUtil.getNonceStr());// 随机支付串
+            w.setNotify_url(WeiXinUtil.ip + "wppayResulet.action");// 支付结果回调地址
+            w.setOpenid(open_id);
+            w.setOut_trade_no("" + new Date().getTime());
+            w.setSpbill_create_ip(ip);
+            w.setTotal_fee(a);
+            w.setTrade_type("JSAPI");
+            Map<String, String> params = new HashMap<String, String>();
+            params.put("attach", w.getAttach());
+            params.put("appid", w.getAppid());
+            params.put("mch_id", w.getMch_id());
+            params.put("nonce_str", w.getNonce_str());
+            params.put("body", w.getBody());
+            params.put("out_trade_no", w.getOut_trade_no());
+            params.put("total_fee", w.getTotal_fee() + "");
+            params.put("spbill_create_ip", w.getSpbill_create_ip());
+            params.put("notify_url", w.getNotify_url());
+            params.put("trade_type", w.getTrade_type());
+            params.put("openid", w.getOpenid());
+            w.setSign(PayWxUtil.getSign(params, WeiXinUtil.APIid));
+            params.put("sign", w.getSign());
+            String retXml = JaxbUtil.getRequestXml(params);
+            String msg = HttpUtils.post("https://api.mch.weixin.qq.com/pay/unifiedorder", retXml);
+            System.out.println(444);
+            if (msg.indexOf("FAIL") > -1) {
+                 JSONObject json = new JSONObject();
+                 json.put("pay", "error");
+                 ResponseUtil.write(json, ServletActionContext.getResponse());
+                 return null;
+            } else {
+                JaxbUtil requestBinder = new JaxbUtil(TongYiReturn.class, JaxbUtil.CollectionWrapper.class);
+                TongYiReturn to = requestBinder.fromXml(msg);
+                if (to.getReturn_code().equals("SUCCESS") && to.getResult_code().equals("SUCCESS")) {
+                    EndPay pay = new EndPay();
+                    pay.setAppId(WeiXinUtil.appid);
+                    pay.setSignType("MD5");
+                    pay.setTimeStamp(System.currentTimeMillis() / 1000 + "");
+                    pay.setPrepay_id(to.getPrepay_id());
+                    pay.setNonceStr(PayWxUtil.getNonceStr());
+                    Map<String, String> requestMap = new HashMap<String, String>();
+                    requestMap.put("appId", pay.getAppId());
+                    requestMap.put("timeStamp", pay.getTimeStamp());
+                    requestMap.put("nonceStr", pay.getNonceStr());
+                    requestMap.put("package", "prepay_id=" + pay.getPrepay_id());
+                    requestMap.put("signType", "MD5");
+                    pay.setPaySign(PayWxUtil.getSign(requestMap, WeiXinUtil.APIid));
+                    // requestMap.put("sign",pay.getPaySign());
+                    // String ret = JaxbUtil.getRequestXml(requestMap);
+                    // System.out.println(ret);
+                    JSONObject json = new JSONObject();
+                    json.put("pay", pay);
+                    if (session.getAttribute("p_biao") != null) { // 说明时从打转盘页面进来的,支付完成后继续调到转盘页面
+                        json.put("p_biao", 1);
+                        session.removeAttribute("p_biao");
+                    } else {
+                        json.put("p_biao", 0);
+                    }
+                    ResUtil.write(json, ServletActionContext.getResponse());
+                }
+            }
+        } else { // 说明不是会员
+            JSONObject json = new JSONObject();
+            json.put("pay", 1);
+            ResUtil.write(json, ServletActionContext.getResponse());
+        }
+
+        return null;
+    }
+
+    // 第五步:支付页面用户输完密码后微信会把支付结果回调到这里,我们根据需要存储支付记录,和执行不同的方法
+    public String payResulet() throws Exception { // 微信支付结果通知
+//		System.out.println("进来了");
+        BufferedReader reader = null;// BufferedReader 字符输入流
+
+        reader = request.getReader();
+        String line = "";
+        String xmlString = null;
+        StringBuffer inputString = new StringBuffer();
+
+        while ((line = reader.readLine()) != null) {
+            inputString.append(line);
+        }
+        xmlString = inputString.toString();
+        request.getReader().close();
+
+        JaxbUtil requestBinder = new JaxbUtil(PayResult.class, PayResult.class);
+        PayResult result = requestBinder.fromXml(xmlString);// Xml到Java,用fromXML()方法
+
+        if (result.getResult_code().equals("SUCCESS")) { // 交易成功,支付结果转换为对象
+            String account = result.getTransaction_id();// 微信支付订单号
+
+            System.out.println("支付成功了");
+            System.out.println("result=" + result.toString());
+
+            Recharge pays = rechargeService.findPayByNo(account);// 根据 微信支付订单号 查找支付记录信息
+
+            if (pays != null) { // 有交易记录 发送成功消息给商家
+                String returnMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
+                HttpServletResponse response = ServletActionContext.getResponse();
+                response.setContentType("text/html;charset=utf-8");
+                PrintWriter out = response.getWriter();
+                out.println(returnMsg);
+                out.flush();
+                out.close();
+//				System.out.println("pay不为空");
+            } else { // 交易记录开始记录
+//				if(openid.equals(result.getOpenid()) && num == result.getTotal_fee() / 100){		//支付成功
+                // 获得交易支付成功用户的信息
+                Recharge pay1 = new Recharge();
+                List<Users> u = userService.queryByopenid(result.getOpenid());  // 查找充值的会员信息
+                pay1.setAccount((double) result.getTotal_fee() / 100);
+                System.out.println("金额:"+ result.getTotal_fee());
+                pay1.setUser_name(u.get(0).getUser_name());
+                pay1.setStu_number(u.get(0).getStu_number());
+                pay1.setCard_number(u.get(0).getCard_number());
+                pay1.setOrder_num(new String(account.getBytes("utf-8")));
+                SimpleDateFormat simp = new SimpleDateFormat("yyyyMMddHHmmss");
+                SimpleDateFormat simp1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+
+                Date date = simp.parse(result.getTime_end());
+                String time = simp1.format(date);
+                pay1.setRe_time(time); // 支付结束时间
+
+                System.out.println("金额:"+pay1.getAccount());
+                rechargeService.insertRecharge(pay1);
+                double bal = u.get(0).getBalance() + (double) result.getTotal_fee() / 100;
+                consumeService.updateBalance(u.get(0).getStu_number(), bal);
+
+                // userService.update2((double) result.getTotal_fee() / 10, u.getId());
+                String returnMsg = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
+                HttpServletResponse response = ServletActionContext.getResponse();
+                response.setContentType("text/html;charset=utf-8");
+                PrintWriter out = response.getWriter();
+                out.println(returnMsg);
+                out.flush();
+                out.close(); // 发送成功消息给商家
+//				}
+                // }
+            }
+        }
+        return null;
+    }
+
+    public String start() throws Exception {
+        Gson gson=new Gson();
+        JSONObject resultJson = new JSONObject();
+        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+        String time = df.format(new Date());
+        String dang = WxUtil.mchOrderNo();
+        double basic_amount = 10.00;
+        double residue = 0.00;
+        double use_size = 0.00;
+        if (stu_number == null){
+            resultJson.put("mess", "学号为空");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+            return null;
+        }
+        if(StringUtils.isNotBlank(collect_code)) {
+            String sign = wxMenuService.wxUrl(dang, WxConstants.SING_MD5, collect_code, time);
+            String requestUrl = "https://app.dev.9kbs.com/shopOpenApi/services/deviceAntiScode/getStartCode?apicode=" + WxConfig.apicode
+                    + "&collect_code=" + collect_code + "&order_no=" + dang + "&amount=10&timestamp="
+                    + time + "&sign=" + sign;
+            String json = HttpsClient.sendPost2(requestUrl, "");
+            HashMap<String, Object> userMap = gson.fromJson(json.toString(), new TypeToken<HashMap<String, Object>>(){}.getType());
+            String status = "";
+            try {
+                status = userMap.get("status").toString();
+            }catch (Exception e){
+                resultJson.put("mess", "第三方接口异常");
+                ResUtil.write(resultJson, ServletActionContext.getResponse());
+                return null;
+            }
+            if (status.equals("succ")) {
+                String data = userMap.get("data").toString();
+                HashMap<String, Object> device = gson.fromJson(data.toString(), new TypeToken<HashMap<String, Object>>() {}.getType());
+                String start_code = device.get("start_code").toString();
+                System.out.println("启动码:"+start_code);
+                String collect_data = device.get("collect_data").toString();
+                HashMap<String, Object> money = gson.fromJson(collect_data.toString(), new TypeToken<HashMap<String, Object>>() {}.getType());
+                String device_code = money.get("device_code").toString();
+                String order_no = new BigDecimal(money.get("order_no").toString()).toString();
+                String use_amount = money.get("use_amount").toString();
+                // 根据订单号获取上次消费记录
+                List<Consume> reconsumes = consumeService.queryRecordByOrder(order_no);
+                // 本次消息信息
+                List<Users> user0 = userService.selectByStu(stu_number);
+                // 上次无用户消费
+                if (reconsumes == null){
+                    if (user0 != null) {  // 本次消费信息,余额
+                        Double balance = user0.get(0).getBalance();
+                        if (balance > basic_amount) {
+                            // 保存本次消费信息,但是没有消费金额
+                            Consume cons = new Consume();
+                            cons.setStu_number(stu_number);
+                            cons.setUser_name(user0.get(0).getUser_name());
+                            cons.setOrder_no(dang);
+                            cons.setBegin_time(time);
+                            cons.setStart_code(start_code);
+                            cons.setDevice_code(device_code);
+                            cons.setUse_amount(0.00);
+                            cons.setUse_size(0.00);
+                            int num = consumeService.insertComsume(cons);
+                            if (num > 0) {   // 保存成功
+                                resultJson.put("mess", "启动成功");
+                                resultJson.put("start_code", start_code);
+                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                return null;
+                            }
+                        } else {
+                            resultJson.put("mess", "余额小于10元!请充值");
+                            ResUtil.write(resultJson, ServletActionContext.getResponse());
+                            return null;
+                        }
+                    } else {
+                        resultJson.put("mess", "卡号异常");
+                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+                        return null;
+                    }
+                }else {
+                    // 上次消费卡号
+                    String restu_number = reconsumes.get(0).getStu_number();
+                    // 上次用户信息
+                    List<Users> reusers = userService.selectByStu(restu_number);
+                    if (reusers != null ) {
+                        if (reconsumes.get(0).getState() == 0) {   // 上次消费未结算
+                            Double rebalance = reusers.get(0).getBalance();
+                            double use_amounts = Double.parseDouble(use_amount);
+                            if (rebalance > use_amounts) {
+                                residue = rebalance - use_amounts;
+                                List<Price> ws = consumeService.water_price("热水");
+                                if (ws!=null){
+                                    System.out.println("热水有价");
+                                    use_size = use_amounts/ws.get(0).getPrice();
+                                }
+                                int num1 = consumeService.updateConsume2(order_no, time, use_amounts, use_size, 1);
+                                int num2 = consumeService.updateBalance(restu_number, residue);
+                                // 上次消费扣除完毕
+                                if (num1 > 0 && num2 > 0) {
+                                    // 查询本次用户信息
+                                    System.out.println("学号:"+stu_number);
+                                    List<Users> users2 = userService.selectByStu(stu_number);
+                                    if (users2 != null ) {
+                                        // 保存本次消费记录,但是没有消费金额
+                                        Consume cons = new Consume();
+                                        cons.setCard_number(stu_number);
+                                        cons.setUser_name(user_name);
+                                        cons.setOrder_no(dang);
+                                        cons.setBegin_time(time);
+                                        cons.setStart_code(start_code);
+                                        cons.setDevice_code(device_code);
+                                        cons.setUse_amount(0.00);
+                                        cons.setUse_size(0.00);
+                                        int num = consumeService.insertComsume(cons);
+                                        if (num > 0) {
+                                            double bal = users2.get(0).getBalance();
+                                            if (bal > basic_amount) {
+                                                resultJson.put("mess", "启动成功");
+                                                resultJson.put("start_code", start_code);
+                                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                                return null;
+                                            } else {
+                                                resultJson.put("mess", "余额不足!请充值");
+                                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                                return null;
+                                            }
+                                        } else {
+                                            resultJson.put("mess", "本次订单提交失败!");
+                                            ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                            return null;
+                                        }
+                                    } else {
+                                        resultJson.put("mess", "用户信息异常!");
+                                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                        return null;
+                                    }
+                                } else {
+                                    resultJson.put("mess", "结算失败!请联系管理员");
+                                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                    return null;
+                                }
+                            } else {
+                                resultJson.put("mess", "上次消费用户余额不足!");
+                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                return null;
+                            }
+                        } else {  // 上次消费已结算
+                            // 查询本次用户信息
+                            List<Users> users2 = userService.selectByStu(stu_number);
+                            if (users2 != null ) {
+                                // 保存本次消费记录,但是没有消费金额
+                                Consume cons = new Consume();
+                                cons.setStu_number(stu_number);
+                                cons.setUser_name(users2.get(0).getUser_name());
+                                cons.setOrder_no(dang);
+                                cons.setBegin_time(time);
+                                cons.setStart_code(start_code);
+                                cons.setDevice_code(device_code);
+                                int num = consumeService.insertComsume(cons);
+                                if (num > 0) {
+                                    double bal = users2.get(0).getBalance();
+                                    if (bal > basic_amount) {
+                                        System.out.println("启动码:"+start_code);
+                                        resultJson.put("mess", "启动成功");
+                                        resultJson.put("start_code", start_code);
+                                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                        return null;
+                                    } else {
+                                        resultJson.put("mess", "余额不足!请充值");
+                                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                        return null;
+                                    }
+                                } else {
+                                    resultJson.put("mess", "本次订单提交失败!");
+                                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                    return null;
+                                }
+                            } else {
+                                resultJson.put("mess", "用户信息异常!");
+                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                return null;
+                            }
+                        }
+                    } else {
+                        resultJson.put("mess", "用户信息异常!");
+                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+                        return null;
+                    }
+                }
+
+            }else {
+                resultJson.put("mess", "请求参数错误!");
+                ResUtil.write(resultJson, ServletActionContext.getResponse());
+            }
+        }else {
+            resultJson.put("mess", "收集码获取失败!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        return null;
+    }
+
+    public String consume() throws Exception {
+        Gson gson=new Gson();
+        JSONObject resultJson = new JSONObject();
+        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+        String time = df.format(new Date());
+        String dang = WxUtil.mchOrderNo();
+        double basic_amount = 0.00;
+        double residue = 0.00;
+        double use_size = 0.00;
+        System.out.println(2222);
+        if(StringUtils.isNotBlank(collect_code)) {
+            System.out.println(3333);
+            String sign = wxMenuService.wxUrl("", WxConstants.SING_MD5, collect_code, time);
+            String requestUrl = "https://app.dev.9kbs.com/shopOpenApi/services/deviceAntiScode/getStartCode?apicode=" + WxConfig.apicode
+                    + "&collect_code=" + collect_code + "&order_no=" + "" + "&amount=10&timestamp="
+                    + time + "&sign=" + sign;
+            String json = HttpsClient.sendPost2(requestUrl, "");
+            System.out.println(json);
+            HashMap<String, Object> userMap = gson.fromJson(json.toString(), new TypeToken<HashMap<String, Object>>(){}.getType());
+            String status = userMap.get("status").toString();
+            if (status.equals("succ")) {
+                String data = userMap.get("data").toString();
+                HashMap<String, Object> device = gson.fromJson(data.toString(), new TypeToken<HashMap<String, Object>>() {}.getType());
+                String collect_data = device.get("collect_data").toString();
+                HashMap<String, Object> money = gson.fromJson(collect_data.toString(), new TypeToken<HashMap<String, Object>>() {}.getType());
+                String order_no = new BigDecimal(money.get("order_no").toString()).toString();
+                String use_amount = money.get("use_amount").toString();
+                // 根据订单号获取本次消费记录
+                List<Consume> reconsumes = consumeService.queryRecordByOrder(order_no);
+                // 订单异常
+                if (reconsumes == null){
+                    resultJson.put("mess", "订单异常,请联系管理员!");
+                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+                    return null;
+                }else {
+                    // 上次消费卡号
+                    String restu_number = reconsumes.get(0).getStu_number();
+                    // 本次用户信息
+                    List<Users> reusers = userService.selectByStu(restu_number);
+                    if (reusers != null ) {
+                        if (reconsumes.get(0).getState() == 0) {   // 本次消费未结算
+                            double rebalance = reusers.get(0).getBalance();
+                            double use_amounts = Double.parseDouble(use_amount);
+                            if (rebalance > use_amounts) {
+                                residue = rebalance - use_amounts;
+                                List<Price> ws = consumeService.water_price("热水");
+                                if (ws!=null){
+                                    use_size = use_amounts / ws.get(0).getPrice();
+                                }
+                                int num1 = consumeService.updateConsume2(order_no, time, use_amounts, use_size, 1);
+                                int num2 = consumeService.updateBalance(restu_number, residue);
+                                // 本次消费扣除完毕
+                                if (num1 > 0 && num2 > 0) {
+                                    resultJson.put("mess", "支付成功");
+                                    resultJson.put("use_amount", use_amounts);
+                                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                    return null;
+                                } else {
+                                    resultJson.put("mess", "结算异常!请联系管理员");
+                                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                    return null;
+                                }
+                            } else {
+                                resultJson.put("mess", "上次消费用户余额不足!");
+                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+                                return null;
+                            }
+                        } else {  // 本次消费已结算
+                            resultJson.put("mess", "已支付!请勿重复支付");
+                            ResUtil.write(resultJson, ServletActionContext.getResponse());
+                            return null;
+                        }
+                    } else {
+                        resultJson.put("mess", "用户信息异常!");
+                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+                        return null;
+                    }
+                }
+
+            }else {
+                resultJson.put("mess", "请求参数错误!");
+                ResUtil.write(resultJson, ServletActionContext.getResponse());
+            }
+        }else {
+            resultJson.put("mess", "收集码获取失败!");
+            ResUtil.write(resultJson, ServletActionContext.getResponse());
+        }
+        return null;
+    }
+
+}

+ 53 - 0
WxConfig.java

@@ -0,0 +1,53 @@
+package com.happy.common.wx;
+
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+
+/**
+ * 微信公众号开发配置类
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+@Component
+public class WxConfig {
+
+    /**
+     * 开发者ID
+     */
+    public static String apicode = "CS0001";
+
+
+    /**
+     * 商户号
+     */
+    public static String apikey  = "XMZnRsZe61hEXyYa7JuAtUupJZ2Q5byc";
+
+
+    /**
+     * 统一下单-通知链接
+     */
+    public static String unifiedorderNotifyUrl = "https://app.dev.9kbs.com/";
+
+
+    /**
+     * 连接超时时间
+     */
+    public static Integer connectionTimeout = 15000;
+
+    /**
+     * 连接超时时间
+     */
+    public static Integer readTimeout = 15000;
+
+    //支付map缓存处理
+    private static HashMap<String,String> payMap = new HashMap<String,String>();
+    public static String getPayMap(String key) {
+        return payMap.get(key);
+    }
+    public static void setPayMap(String key,String value) {
+        payMap.put(key,value);
+    }
+
+
+}

+ 53 - 0
WxConstants.java

@@ -0,0 +1,53 @@
+package com.happy.common.wx;
+
+/**
+ * 微信公众号常量类
+ * @author lujunjie
+ * @date   2018/06/28
+ */
+public class WxConstants {
+
+    /**
+     * 默认编码
+     */
+    public static final String DEFAULT_CHARSET = "UTF-8";
+
+    /**
+     * 统一下单-扫描支付
+     */
+    public static String PAY_UNIFIEDORDER = "https://app.dev.9kbs.com/shopOpenApi/services/deviceAntiScode/getStartCode";
+
+    public static String Test = "http://localhost:8088/HotWaters/userget_stu.action";
+
+    public static String Test2 = "http://localhost:8088/HotWaters/userstu_info.action";
+
+    /**
+     * 请求成功返回码
+     */
+    public final static String ERRCODE_OK_CODE = "0";
+    /**
+     * 错误的返回码的Key
+     */
+    public final static String ERRCODE = "errcode";
+
+    /**
+     * 返回状态码
+     */
+    public final static String RETURN_CODE= "return_code";
+
+    /**
+     * access_token 字符串
+     */
+    public final static String ACCESS_TOKEN = "access_token";
+
+    /**
+     * 签名类型 MD5
+     */
+    public final static String SING_MD5 = "MD5";
+
+    /**
+     * 签名类型 HMAC-SHA256
+     */
+    public final static String SING_HMACSHA256 = "HMAC-SHA256";
+
+}

+ 31 - 0
WxMenuService.java

@@ -0,0 +1,31 @@
+package com.happy.service;
+
+import java.util.HashMap;
+
+/**
+ * 微信菜单业务类
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public interface WxMenuService {
+
+
+    /**
+     * 生成支付二维码URL
+     * @param 标价金额(分单位)
+     * @param outTradeNo 商户订单号
+     * @param signType 签名类型
+     * @throws Exception
+     */
+    public String wxUrl(String outTradeNo, String signType, String collect_code, String time) throws Exception;
+
+    public String test(String card_number) throws Exception;
+
+    public String test2(String collect_code) throws Exception;
+
+    public String test3(String card_number) throws Exception;
+
+    public String wxUrl2(String outTradeNo, String signType, String collect_code, String time) throws Exception;
+
+
+}

+ 95 - 0
WxMenuServiceImpl.java

@@ -0,0 +1,95 @@
+package com.happy.service.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.happy.Until.HttpUtils;
+import com.happy.common.http.HttpsClient;
+import com.happy.common.wx.WxConfig;
+import com.happy.common.wx.WxConstants;
+import com.happy.common.wx.WxUtil;
+import com.happy.service.WxMenuService;
+import org.springframework.stereotype.Service;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * 微信菜单实现类类
+ * @author lujunjie
+ * @date   2018/02/16
+ */
+@Service("wxMenuService")
+public class WxMenuServiceImpl implements WxMenuService {
+
+    @Override
+    public String wxUrl(String outTradeNo,
+           String signType, String collect_code, String time) throws Exception {
+        HashMap<String, String> data = new HashMap<String, String>();
+        data.put("apicode", WxConfig.apicode);
+        data.put("apikey", WxConfig.apikey);
+        // 时间戳
+        data.put("timestamp", time);
+        // 订单号
+        data.put("order_no",outTradeNo);
+        // 收集码
+        data.put("collect_code", collect_code);
+        // 签名
+        data.put("sign", WxUtil.getSignature(data, WxConfig.apikey, signType));
+        return WxUtil.getSignature(data, WxConfig.apikey, signType);
+    }
+
+    @Override
+    public String wxUrl2(String outTradeNo,
+                                          String signType, String collect_code, String time) throws Exception {
+        HashMap<String, String> data = new HashMap<String, String>();
+        data.put("apicode", WxConfig.apicode);
+        data.put("apikey", WxConfig.apikey);
+        // 时间戳
+        data.put("timestamp", time);
+        // 订单号
+        data.put("order_no",outTradeNo);
+        // 收集码
+        data.put("collect_code", collect_code);
+        // 签名
+        data.put("sign", WxUtil.getSignature(data, WxConfig.apikey, signType));
+        String requestXML = WxUtil.mapToXml(data);
+        System.out.println(requestXML);
+        String reponseString = HttpsClient.httpsRequestReturnString(WxConstants.PAY_UNIFIEDORDER, HttpsClient.METHOD_POST, requestXML);
+        System.out.println("aa: "+reponseString);
+        return reponseString;
+    }
+
+    @Override
+    public String test(String card_number) throws Exception {
+        HashMap<String, String> data = new HashMap<String, String>();
+        data.put("card_number", "123456");
+        String reponseString = HttpsClient.get(WxConstants.Test);
+        return reponseString;
+    }
+
+    @Override
+    public String test2(String collect_code) throws Exception {
+        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+        String time = df.format(new Date());
+        String dang = WxUtil.mchOrderNo();
+        String sign = wxUrl(dang, WxConstants.SING_MD5, collect_code, time);
+        HashMap<String, String> data = new HashMap<String, String>();
+        data.put("apicode", WxConfig.apicode);
+        data.put("collect_code", collect_code);
+        data.put("order_no", dang);
+        data.put("amount", "10");
+        data.put("timestamp", time);
+        data.put("sign", sign);
+        String reponseString = HttpUtils.post(WxConstants.PAY_UNIFIEDORDER, data);
+        return reponseString;
+    }
+
+    @Override
+    public String test3(String pa) throws Exception {
+        pa = "8888&card_number=123456";
+        String reponseString = HttpsClient.sendPost2(WxConstants.PAY_UNIFIEDORDER, pa);
+        return reponseString;
+
+    }
+}

+ 584 - 0
WxPay.java

@@ -0,0 +1,584 @@
+//package com.happy.action;
+//
+//import com.happy.Model.Consume;
+//import com.happy.Model.Price;
+//import com.happy.Model.Recharge;
+//import com.happy.Model.Users;
+//import com.happy.Until.HttpUtils;
+//import com.happy.Until.ResUtil;
+//import com.google.gson.Gson;
+//import com.google.gson.reflect.TypeToken;
+//import com.happy.common.http.HttpsClient;
+//import com.happy.common.wx.WxConfig;
+//import com.happy.common.wx.WxConstants;
+//import com.happy.common.wx.WxUtil;
+//import com.happy.dao.RechargeDao;
+//import com.happy.service.ConsumeService;
+//import com.happy.service.RechargeService;
+//import com.happy.service.UserService;
+//import com.happy.service.WxMenuService;
+//import com.opensymphony.xwork2.ActionSupport;
+//import net.sf.json.JSON;
+//import net.sf.json.JSONObject;
+//import org.apache.commons.lang3.StringUtils;
+//import org.apache.struts2.ServletActionContext;
+//import org.apache.struts2.interceptor.ServletRequestAware;
+//
+//import javax.annotation.Resource;
+//import javax.servlet.http.HttpServletRequest;
+//import javax.servlet.http.HttpServletResponse;
+//import java.math.BigDecimal;
+//import java.text.SimpleDateFormat;
+//import java.util.*;
+//
+//public class WxPay extends ActionSupport implements ServletRequestAware {
+//
+//    private HttpServletRequest request;
+//    public HttpServletResponse response;
+//    public WxMenuService wxMenuService;
+//
+//    public String user;
+//    public String card_number;
+//    public String collect_code;
+//    public String begin_time;
+//
+//    @Resource
+//    public UserService userService;
+//    @Resource
+//    public ConsumeService consumeService;
+//    @Resource
+//    public RechargeService rechargeService;
+//
+//    public String user_name;
+//    public BigDecimal account;
+//    public String order_id;
+//    public String re_time;
+//    public String amount;
+//    public String user_id;
+//
+//    public String getUser_id() {
+//        return user_id;
+//    }
+//
+//    public void setUser_id(String user_id) {
+//        this.user_id = user_id;
+//    }
+//
+//    public String getAmount() {
+//        return amount;
+//    }
+//
+//    public void setAmount(String amount) {
+//        this.amount = amount;
+//    }
+//
+//    public String getRe_time() {
+//        return re_time;
+//    }
+//
+//    public void setRe_time(String re_time) {
+//        this.re_time = re_time;
+//    }
+//
+//    public String getOrder_id() {
+//        return order_id;
+//    }
+//
+//    public void setOrder_id(String order_id) {
+//        this.order_id = order_id;
+//    }
+//
+//    public BigDecimal getAccount() {
+//        return account;
+//    }
+//
+//    public void setAccount(BigDecimal account) {
+//        this.account = account;
+//    }
+//
+//    public String getBegin_time() {
+//        return begin_time;
+//    }
+//
+//    public void setBegin_time(String begin_time) {
+//        this.begin_time = begin_time;
+//    }
+//
+//    public String getUser_name() {
+//        return user_name;
+//    }
+//
+//    public void setUser_name(String user_name) {
+//        this.user_name = user_name;
+//    }
+//
+//    public String getCollect_code() {
+//        return collect_code;
+//    }
+//
+//    public void setCollect_code(String collect_code) {
+//        this.collect_code = collect_code;
+//    }
+//
+//    public String getCard_number() {
+//        return card_number;
+//    }
+//
+//    public void setCard_number(String card_number) {
+//        this.card_number = card_number;
+//    }
+//
+//    public WxMenuService getWxMenuService() {
+//        return wxMenuService;
+//    }
+//
+//    public void setWxMenuService(WxMenuService wxMenuService) {
+//        this.wxMenuService = wxMenuService;
+//    }
+//
+//    public HttpServletRequest getRequest() {
+//        return request;
+//    }
+//
+//    public void setRequest(HttpServletRequest request) {
+//        this.request = request;
+//    }
+//
+//    public void setServletRequest(HttpServletRequest request) {
+//        this.request = request;
+//    }
+//
+//    public HttpServletResponse getResponse() {
+//        return response;
+//    }
+//
+//    public void setResponse(HttpServletResponse response) {
+//        this.response = response;
+//    }
+//
+//    public String getUser() {
+//        return user;
+//    }
+//
+//    public void setUser(String user) {
+//        this.user = user;
+//    }
+//
+////    public String test() throws Exception {
+////        JSONObject resultJson = new JSONObject();
+////        String ll = wxMenuService.test(card_number);
+////        resultJson.put("ess", ll);
+////        ResUtil.write(resultJson, ServletActionContext.getResponse());
+////        return null;
+////    }
+////
+////    public String test2() throws Exception {
+////        JSONObject resultJson = new JSONObject();
+////        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+////        String time = df.format(new Date());
+////        String dang = WxUtil.mchOrderNo();
+////        String sign = wxMenuService.wxUrl(dang, WxConstants.SING_MD5, collect_code, time);
+////        System.out.println("aa: "+sign);
+////        HashMap<String, String> data = new HashMap<String, String>();
+////        data.put("apicode", WxConfig.apicode);
+////        data.put("collect_code", collect_code);
+////        data.put("order_no", dang);
+////        data.put("amount", "10");
+////        data.put("timestamp", time);
+////        data.put("sign", sign);
+////        JSONObject json = JSONObject.fromObject(data);//将java对象转换为json对象
+////        String str = json.toString();
+////        String reponseString = HttpUtils.post(WxConstants.PAY_UNIFIEDORDER, str);
+////        resultJson.put("ess", reponseString);
+////        ResUtil.write(resultJson, ServletActionContext.getResponse());
+////        return null;
+////    }
+//////
+////    public String test3() throws Exception {
+////        JSONObject resultJson = new JSONObject();
+////        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+////        String time = df.format(new Date());
+////        String dang = WxUtil.mchOrderNo();
+////        String sign = wxMenuService.wxUrl(dang, WxConstants.SING_MD5, collect_code, time);
+////        HashMap<String, String> data = new HashMap<String, String>();
+////        data.put("apicode", WxConfig.apicode);
+////        data.put("collect_code", collect_code);
+////        data.put("order_no", dang);
+////        data.put("amount", "10");
+////        data.put("timestamp", time);
+////        data.put("sign", sign);
+////        String reponseString = HttpUtils.post(WxConstants.PAY_UNIFIEDORDER, data);
+////        resultJson.put("ess", reponseString);
+////        ResUtil.write(resultJson, ServletActionContext.getResponse());
+////        return null;
+////    }
+//
+////    public String start2() throws Exception {
+////        JSONObject resultJson = new JSONObject();
+////        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+////        String time = df.format(new Date());
+////        String dang = WxUtil.mchOrderNo();
+////        if(StringUtils.isNotBlank(collect_code)) {
+////            String sign = wxMenuService.wxUrl(dang, WxConstants.SING_MD5, collect_code, time);
+//////            String requestUrl = "https://app.dev.9kbs.com?apicode=" + WxConfig.apicode
+//////                    + "&collect_code=" + collect_code + "&order_no=" + dang + "&amount=10&timestamp="
+//////                    + time + "&sign=" + sign;
+////            String requestUrl = WxConstants.Test;
+////            String json = HttpsClient.sendPost(requestUrl, "card_number=123456");
+////            if (StringUtils.isNotBlank(json)) {
+////                resultJson.put("mess", json);
+////                ResUtil.write(resultJson, ServletActionContext.getResponse());
+////            } else {
+////                resultJson.put("mess", "获取失败!");
+////                ResUtil.write(resultJson, ServletActionContext.getResponse());
+////            }
+////        }else {
+////            resultJson.put("mess", "收集码获取失败!");
+////            ResUtil.write(resultJson, ServletActionContext.getResponse());
+////        }
+////        return null;
+////    }
+////
+//    public String start3() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+//        String time = df.format(new Date());
+//        String dang = WxUtil.mchOrderNo();
+//        if(StringUtils.isNotBlank(collect_code)) {
+//            String sign = wxMenuService.wxUrl(dang, WxConstants.SING_MD5, collect_code, time);
+//            String url = WxConstants.PAY_UNIFIEDORDER;
+//            String request = "apicode=" + WxConfig.apicode
+//                    + "&collect_code=" + collect_code + "&order_no=" + dang + "&amount=10&timestamp="
+//                    + time + "&sign=" + sign;
+//            String json = HttpUtils.post(url, request);
+//            if (StringUtils.isNotBlank(json)) {
+//                resultJson.put("mess", json);
+//                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            } else {
+//                resultJson.put("mess", "获取失败!");
+//                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            }
+//        }else {
+//            resultJson.put("mess", "收集码获取失败!");
+//            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        }
+//        return null;
+//    }
+//
+//    public String consume() throws Exception {
+//        Gson gson=new Gson();
+//        JSONObject resultJson = new JSONObject();
+//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+//        String time = df.format(new Date());
+//        String dang = WxUtil.mchOrderNo();
+//        BigDecimal basic_amount = new BigDecimal("10");
+//        BigDecimal residue = new BigDecimal("0.00");
+//        BigDecimal use_size = new BigDecimal("0.00");
+//        if(StringUtils.isNotBlank(collect_code)) {
+//            String sign = wxMenuService.wxUrl("", WxConstants.SING_MD5, collect_code, time);
+//            String requestUrl = "https://app.dev.9kbs.com/shopOpenApi/services/deviceAntiScode/getStartCode?apicode=" + WxConfig.apicode
+//                    + "&collect_code=" + collect_code + "&order_no=" + "" + "&amount=10&timestamp="
+//                    + time + "&sign=" + sign;
+//            String json = HttpsClient.sendPost2(requestUrl, "");
+//            System.out.println(json);
+//            HashMap<String, Object> userMap = gson.fromJson(json.toString(), new TypeToken<HashMap<String, Object>>(){}.getType());
+//            String status = userMap.get("status").toString();
+//            if (status.equals("succ")) {
+//                String data = userMap.get("data").toString();
+//                HashMap<String, Object> device = gson.fromJson(data.toString(), new TypeToken<HashMap<String, Object>>() {}.getType());
+//                String collect_data = device.get("collect_data").toString();
+//                HashMap<String, Object> money = gson.fromJson(collect_data.toString(), new TypeToken<HashMap<String, Object>>() {}.getType());
+//                String order_no = new BigDecimal(money.get("order_no").toString()).toString();
+//                String use_amount = money.get("use_amount").toString();
+//                // 根据订单号获取本次消费记录
+//                List<Consume> reconsumes = consumeService.queryRecordByOrder(order_no);
+//                // 订单异常
+//                if (reconsumes == null){
+//                    resultJson.put("mess", "订单异常,请联系管理员!");
+//                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                    return null;
+//                }else {
+//                    // 上次消费卡号
+//                    String recard_number = reconsumes.get(0).getCard_number();
+//                    // 本次用户信息
+//                    List<Users> reusers = userService.selectByCard(recard_number);
+//                    if (reusers != null ) {
+//                        if (reconsumes.get(0).getState() == 0) {   // 本次消费未结算
+//                            BigDecimal rebalance = reusers.get(0).getBalance();
+//                            BigDecimal use_amounts = new BigDecimal(use_amount);
+//                            if (rebalance.compareTo(use_amounts) > 0) {
+//                                residue = rebalance.subtract(use_amounts);
+//                                List<Price> ws = consumeService.water_price("热水");
+//                                if (ws!=null){
+//                                    use_size = use_amounts.divide(ws.get(0).getPrice(), BigDecimal.ROUND_HALF_UP);
+//                                }
+//                                int num1 = consumeService.updateConsume(order_no, time, use_amounts, use_size, 1);
+//                                int num2 = consumeService.updateBalance(recard_number, residue);
+//                                // 本次消费扣除完毕
+//                                if (num1 > 0 && num2 > 0) {
+//                                    resultJson.put("mess", "支付成功!");
+//                                    resultJson.put("use_amount", use_amounts);
+//                                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                    return null;
+//                                } else {
+//                                    resultJson.put("mess", "结算异常!请联系管理员");
+//                                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                    return null;
+//                                }
+//                            } else {
+//                                resultJson.put("mess", "上次消费用户余额不足!");
+//                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                return null;
+//                            }
+//                        } else {  // 本次消费已结算
+//                            resultJson.put("mess", "已支付!请勿重复支付");
+//                            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                            return null;
+//                        }
+//                    } else {
+//                        resultJson.put("mess", "用户信息异常!");
+//                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                        return null;
+//                    }
+//                }
+//
+//            }else {
+//                resultJson.put("mess", "请求参数错误!");
+//                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            }
+//        }else {
+//            resultJson.put("mess", "收集码获取失败!");
+//            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        }
+//        return null;
+//    }
+//
+//
+//    public String start() throws Exception {
+//        Gson gson=new Gson();
+//        JSONObject resultJson = new JSONObject();
+//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+//        String time = df.format(new Date());
+//        String dang = WxUtil.mchOrderNo();
+//        BigDecimal basic_amount = new BigDecimal("10");
+//        BigDecimal residue = new BigDecimal("0.00");
+//        BigDecimal use_size = new BigDecimal("0.00");
+//        if(StringUtils.isNotBlank(collect_code)) {
+//            String sign = wxMenuService.wxUrl(dang, WxConstants.SING_MD5, collect_code, time);
+//            String requestUrl = "https://app.dev.9kbs.com/shopOpenApi/services/deviceAntiScode/getStartCode?apicode=" + WxConfig.apicode
+//                    + "&collect_code=" + collect_code + "&order_no=" + dang + "&amount=10&timestamp="
+//                    + time + "&sign=" + sign;
+//            String json = HttpsClient.sendPost2(requestUrl, "");
+//            HashMap<String, Object> userMap = gson.fromJson(json.toString(), new TypeToken<HashMap<String, Object>>(){}.getType());
+//            String status = userMap.get("status").toString();
+//            if (status.equals("succ")) {
+//                String data = userMap.get("data").toString();
+//                HashMap<String, Object> device = gson.fromJson(data.toString(), new TypeToken<HashMap<String, Object>>() {}.getType());
+//                String start_code = device.get("start_code").toString();
+//                String collect_data = device.get("collect_data").toString();
+//                HashMap<String, Object> money = gson.fromJson(collect_data.toString(), new TypeToken<HashMap<String, Object>>() {}.getType());
+//                String device_code = money.get("device_code").toString();
+//                String order_no = new BigDecimal(money.get("order_no").toString()).toString();
+//                String use_amount = money.get("use_amount").toString();
+//                // 根据订单号获取上次消费记录
+//                List<Consume> reconsumes = consumeService.queryRecordByOrder(order_no);
+//                // 本次消息信息
+//                List<Users> user0 = userService.selectByCard(card_number);
+//                // 上次无用户消费
+//                if (reconsumes == null){
+//                    if (user0 != null) {  // 本次消费信息,余额
+//                        BigDecimal balance = user0.get(0).getBalance();
+//                        if (balance.compareTo(basic_amount) > 0) {
+//                            // 保存本次消费信息,但是没有消费金额
+//                            Consume cons = new Consume();
+//                            cons.setCard_number(card_number);
+//                            cons.setUser_name(user_name);
+//                            cons.setOrder_no(dang);
+//                            cons.setBegin_time(time);
+//                            cons.setStart_code(start_code);
+//                            cons.setDevice_code(device_code);
+//                            int num = consumeService.insertComsume(cons);
+//                            if (num > 0) {   // 保存成功
+//                                resultJson.put("start_code", start_code);
+//                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                return null;
+//                            }
+//                        } else {
+//                            resultJson.put("mess", "余额小于10元!请充值");
+//                            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                            return null;
+//                        }
+//                    } else {
+//                        resultJson.put("mess", "卡号异常");
+//                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                        return null;
+//                    }
+//                }else {
+//                    // 上次消费卡号
+//                    String recard_number = reconsumes.get(0).getCard_number();
+//                    // 上次用户信息
+//                    List<Users> reusers = userService.selectByCard(recard_number);
+//                    if (reusers != null ) {
+//                        if (reconsumes.get(0).getState() == 0) {   // 上次消费未结算
+//                            BigDecimal rebalance = reusers.get(0).getBalance();
+//                            BigDecimal use_amounts = new BigDecimal(use_amount);
+//                            if (rebalance.compareTo(use_amounts) > 0) {
+//                                residue = rebalance.subtract(use_amounts);
+//                                List<Price> ws = consumeService.water_price("热水");
+//                                if (ws!=null){
+//                                    use_size = use_amounts.divide(ws.get(0).getPrice(), BigDecimal.ROUND_HALF_UP);
+//                                }
+//                                int num1 = consumeService.updateConsume(order_no, time, use_amounts, use_size, 1);
+//                                int num2 = consumeService.updateBalance(recard_number, residue);
+//                                // 上次消费扣除完毕
+//                                if (num1 > 0 && num2 > 0) {
+//                                    // 查询本次用户信息
+//                                    List<Users> users2 = userService.selectByCard(card_number);
+//                                    if (users2 != null ) {
+//                                        // 保存本次消费记录,但是没有消费金额
+//                                        Consume cons = new Consume();
+//                                        cons.setCard_number(card_number);
+//                                        cons.setUser_name(user_name);
+//                                        cons.setOrder_no(dang);
+//                                        cons.setBegin_time(time);
+//                                        cons.setStart_code(start_code);
+//                                        cons.setDevice_code(device_code);
+//                                        int num = consumeService.insertComsume(cons);
+//                                        if (num > 0) {
+//                                            BigDecimal bal = users2.get(0).getBalance();
+//                                            if (bal.compareTo(basic_amount) > 0) {
+//                                                resultJson.put("start_code", start_code);
+//                                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                                return null;
+//                                            } else {
+//                                                resultJson.put("mess", "余额不足!请充值");
+//                                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                                return null;
+//                                            }
+//                                        } else {
+//                                            resultJson.put("mess", "本次订单提交失败!");
+//                                            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                            return null;
+//                                        }
+//                                    } else {
+//                                        resultJson.put("mess", "用户信息异常!");
+//                                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                        return null;
+//                                    }
+//                                } else {
+//                                    resultJson.put("mess", "结算失败!请联系管理员");
+//                                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                    return null;
+//                                }
+//                            } else {
+//                                resultJson.put("mess", "上次消费用户余额不足!");
+//                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                return null;
+//                            }
+//                        } else {  // 上次消费已结算
+//                            // 查询本次用户信息
+//                            List<Users> users2 = userService.selectByCard(card_number);
+//                            if (users2 != null ) {
+//                                // 保存本次消费记录,但是没有消费金额
+//                                Consume cons = new Consume();
+//                                cons.setCard_number(card_number);
+//                                cons.setUser_name(user_name);
+//                                cons.setOrder_no(dang);
+//                                cons.setBegin_time(time);
+//                                cons.setStart_code(start_code);
+//                                cons.setDevice_code(device_code);
+//                                int num = consumeService.insertComsume(cons);
+//                                if (num > 0) {
+//                                    BigDecimal bal = users2.get(0).getBalance();
+//                                    if (bal.compareTo(basic_amount) > 0) {
+//                                        resultJson.put("start_code", start_code);
+//                                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                        return null;
+//                                    } else {
+//                                        resultJson.put("mess", "余额不足!请充值");
+//                                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                        return null;
+//                                    }
+//                                } else {
+//                                    resultJson.put("mess", "本次订单提交失败!");
+//                                    ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                    return null;
+//                                }
+//                            } else {
+//                                resultJson.put("mess", "用户信息异常!");
+//                                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                                return null;
+//                            }
+//                        }
+//                    } else {
+//                        resultJson.put("mess", "用户信息异常!");
+//                        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//                        return null;
+//                    }
+//                }
+//
+//            }else {
+//                resultJson.put("mess", "请求参数错误!");
+//                ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            }
+//        }else {
+//            resultJson.put("mess", "收集码获取失败!");
+//            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        }
+//        return null;
+//    }
+//
+//    public String queryConsume() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        if (card_number!=null){
+//            List<Consume> consumes = consumeService.queryRecordByCard(card_number, begin_time);
+//            resultJson.put("mess", consumes);
+//            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        }
+//        return null;
+//    }
+//
+//    public String recharge() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        Enumeration<String> paraNames = request.getParameterNames();
+//        for(Enumeration e=paraNames;e.hasMoreElements();){
+//            String thisName=e.nextElement().toString();
+//            String thisValue=request.getParameter(thisName);
+//            System.out.println(thisName+"--------------"+thisValue);  }
+//        if (user_id == null || amount == null){
+//            resultJson.put("mess", "数据异常");
+//            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            return null;
+//        }
+//        System.out.println("订单号: "+order_id);
+//        BigDecimal acc = new BigDecimal(amount);
+//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
+//        String time = df.format(new Date());
+//        List<Users> users = userService.selectByCard(user_id);
+//        Recharge recharge = new Recharge();
+//        recharge.setRe_time(time);
+//        recharge.setCard_number(user_id);
+//        recharge.setUser_name(users.get(0).getUser_name());
+//        recharge.setAccount(acc.divide(new BigDecimal("100")));
+//        recharge.setOrder_num(order_id);
+//        recharge.setState(1);
+//        rechargeService.insertRecharge(recharge);
+//        System.out.println("余额:"+users.get(0).getBalance());
+//        BigDecimal bal = users.get(0).getBalance().add(acc.divide(new BigDecimal("100")));
+//        consumeService.updateBalance(user_id, bal);
+//        return null;
+//    }
+//
+//    public List<Recharge> queryByCard() throws Exception {
+//        JSONObject resultJson = new JSONObject();
+//        if (card_number == null){
+//            resultJson.put("mess", "卡号异常");
+//            ResUtil.write(resultJson, ServletActionContext.getResponse());
+//            return null;
+//        }
+//        List<Recharge> rechar = rechargeService.queryByCard(card_number, re_time);
+//        resultJson.put("mess", rechar);
+//        ResUtil.write(resultJson, ServletActionContext.getResponse());
+//        return null;
+//    }
+//}

+ 381 - 0
WxUtil.java

@@ -0,0 +1,381 @@
+package com.happy.common.wx;
+
+import com.google.zxing.BarcodeFormat;
+import com.google.zxing.EncodeHintType;
+import com.google.zxing.MultiFormatWriter;
+import com.google.zxing.client.j2se.MatrixToImageWriter;
+import com.google.zxing.common.BitMatrix;
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
+import com.happy.common.util.SHA1;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.*;
+import java.security.MessageDigest;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * 微信公众号接口工具类
+ * @author lujunjie
+ * @date   2018/03/01
+ */
+public class WxUtil {
+
+	/**
+	 * 加密/校验流程如下:
+	 * 1. 将token、timestamp、nonce三个参数进行字典序排序<br>
+	 * 2. 将三个参数字符串拼接成一个字符串进行sha1加密<br>
+	 * 3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信<br>
+	 *
+	 * @param token Token验证密钥
+	 * @param signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数,nonce参数
+	 * @param timestamp 时间戳
+	 * @param nonce 随机数
+	 * @return 验证成功返回:true,失败返回:false
+	 */
+	public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
+		List<String> params = new ArrayList<String>();
+		params.add(token);
+		params.add(timestamp);
+		params.add(nonce);
+		//1. 将token、timestamp、nonce三个参数进行字典序排序
+		Collections.sort(params, new Comparator<String>() {
+			@Override
+			public int compare(String o1, String o2) {
+				return o1.compareTo(o2);
+			}
+		});
+		//2. 将三个参数字符串拼接成一个字符串进行sha1加密
+		String temp = SHA1.encode(params.get(0) + params.get(1) + params.get(2));
+		//3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
+		return temp.equals(signature);
+	}
+
+	/**
+	 * 输入流转化为字符串
+	 * @param inputStream 流
+	 * @return String 字符串
+	 * @throws Exception
+	 */
+	public static String getStreamString(InputStream inputStream) throws Exception{
+		StringBuffer buffer=new StringBuffer();
+		InputStreamReader inputStreamReader = null;
+		BufferedReader bufferedReader = null;
+		try{
+			inputStreamReader=new InputStreamReader(inputStream, WxConstants.DEFAULT_CHARSET);
+			bufferedReader=new BufferedReader(inputStreamReader);
+			String line;
+			while((line=bufferedReader.readLine())!=null){
+				buffer.append(line);
+			}
+		}catch(Exception e){
+			throw new Exception();
+		}finally {
+			if(bufferedReader != null){
+				bufferedReader.close();
+			}
+			if(inputStreamReader != null){
+				inputStreamReader.close();
+			}
+			if(inputStream != null){
+				inputStream.close();
+			}
+		}
+		return buffer.toString();
+	}
+
+	/**
+	 * 获取随机字符串 Nonce Str
+	 * @return String 随机字符串
+	 */
+	public static String getNonceStr() {
+		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
+	}
+
+	/**
+	 * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
+	 * @param data 待签名数据
+	 * @param apikey API密钥
+	 * @return 签名
+	 */
+	public static String getSignature(final Map<String, String> data, String apikey,
+				String signType) throws Exception {
+		Set<String> keySet = data.keySet();
+		String[] keyArray = keySet.toArray(new String[keySet.size()]);
+		Arrays.sort(keyArray);
+		StringBuilder sb = new StringBuilder();
+		sb.append(apikey);
+		sb.append("amount10apicodeCS0001collect_code");
+		sb.append(data.get("collect_code").trim());
+		sb.append("order_no");
+		sb.append(data.get("order_no").trim());
+        sb.append("timestamp");
+        sb.append(data.get("timestamp").trim());
+        sb.append(apikey);
+		System.out.println(sb);
+		if (signType.equals(WxConstants.SING_MD5)) {
+			System.out.println(MD5(sb.toString()).toUpperCase());
+			return MD5(sb.toString()).toLowerCase();
+		}
+		else if (signType.equals(WxConstants.SING_HMACSHA256)) {
+			return HMACSHA256(sb.toString(), apikey);
+		}
+		else {
+			throw new Exception(String.format("Invalid sign_type: %s", signType));
+		}
+	}
+
+	/**
+	 * 生成 MD5
+	 * @param data 待处理数据
+	 * @return MD5结果
+	 */
+	public static String MD5(String data) throws Exception {
+		MessageDigest md = MessageDigest.getInstance("MD5");
+		byte[] array = md.digest(data.getBytes("UTF-8"));
+		StringBuilder sb = new StringBuilder();
+		for (byte item : array) {
+			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
+		}
+		return sb.toString().toUpperCase();
+	}
+
+	/**
+	 * 生成 HMACSHA256
+	 * @param data 待处理数据
+	 * @param key 密钥
+	 * @return 加密结果
+	 * @throws Exception
+	 */
+	public static String HMACSHA256(String data, String key) throws Exception {
+		Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
+		SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
+		sha256_HMAC.init(secret_key);
+		byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
+		StringBuilder sb = new StringBuilder();
+		for (byte item : array) {
+			sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
+		}
+		return sb.toString().toUpperCase();
+	}
+
+	/**
+	 * @param data Map类型数据
+	 * @return XML格式的字符串
+	 * @throws Exception
+	 */
+	public static String mapToXml(Map<String, String> data) throws Exception {
+		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+		DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
+		org.w3c.dom.Document document = documentBuilder.newDocument();
+		org.w3c.dom.Element root = document.createElement("xml");
+		document.appendChild(root);
+		for (String key: data.keySet()) {
+			String value = data.get(key);
+			if (value == null) {
+				value = "";
+			}
+			value = value.trim();
+			org.w3c.dom.Element filed = document.createElement(key);
+			filed.appendChild(document.createTextNode(value));
+			root.appendChild(filed);
+		}
+		TransformerFactory tf = TransformerFactory.newInstance();
+		Transformer transformer = tf.newTransformer();
+		DOMSource source = new DOMSource(document);
+		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+		StringWriter writer = new StringWriter();
+		StreamResult result = new StreamResult(writer);
+		transformer.transform(source, result);
+		String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
+		try {
+			writer.close();
+		}
+		catch (Exception ex) {
+		}
+		return output;
+	}
+
+	/**
+	 * 处理 HTTPS API返回数据,转换成Map对象。return_code为SUCCESS时,验证签名。
+	 * @param xmlStr API返回的XML格式数据
+	 * @return Map类型数据
+	 * @throws Exception
+	 */
+	public static Map<String, String> processResponseXml(String xmlStr,String signType) throws Exception {
+		String RETURN_CODE = WxConstants.RETURN_CODE;
+		String return_code;
+		Map<String, String> respData = xmlToMap(xmlStr);
+		if (respData.containsKey(RETURN_CODE)) {
+			return_code = respData.get(RETURN_CODE);
+		}
+		else {
+			throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
+		}
+
+		if (return_code.equals("FAIL")) {
+			return respData;
+		}
+		else if (return_code.equals("SUCCESS")) {
+			if (isResponseSignatureValid(respData,signType)) {
+				return respData;
+			}
+			else {
+				throw new Exception(String.format("Invalid sign value in XML: %s", xmlStr));
+			}
+		}
+		else {
+			throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
+		}
+	}
+
+
+	/**
+	 * XML格式字符串转换为Map
+	 * @param strXML XML字符串
+	 * @return XML数据转换后的Map
+	 * @throws Exception
+	 */
+	public static Map<String, String> xmlToMap(String strXML) throws Exception {
+		try {
+			Map<String, String> data = new HashMap<String, String>();
+			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+
+			String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
+			documentBuilderFactory.setFeature(FEATURE, true);
+
+			FEATURE = "http://xml.org/sax/features/external-general-entities";
+			documentBuilderFactory.setFeature(FEATURE, false);
+
+			FEATURE = "http://xml.org/sax/features/external-parameter-entities";
+			documentBuilderFactory.setFeature(FEATURE, false);
+
+			FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
+			documentBuilderFactory.setFeature(FEATURE, false);
+
+			documentBuilderFactory.setXIncludeAware(false);
+			documentBuilderFactory.setExpandEntityReferences(false);
+			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
+			InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
+			org.w3c.dom.Document doc = documentBuilder.parse(stream);
+			doc.getDocumentElement().normalize();
+			NodeList nodeList = doc.getDocumentElement().getChildNodes();
+			for (int idx = 0; idx < nodeList.getLength(); ++idx) {
+				Node node = nodeList.item(idx);
+				if (node.getNodeType() == Node.ELEMENT_NODE) {
+					org.w3c.dom.Element element = (org.w3c.dom.Element) node;
+					data.put(element.getNodeName(), element.getTextContent());
+				}
+			}
+			try {
+				stream.close();
+			} catch (Exception ex) {
+				// do nothing
+			}
+			return data;
+		} catch (Exception ex) {
+			throw ex;
+		}
+	}
+
+	/**
+	 * 判断xml数据的sign是否有效,必须包含sign字段,否则返回false。
+	 * @param reqData 向wxpay post的请求数据
+	 * @return 签名是否有效
+	 * @throws Exception
+	 */
+	private static boolean isResponseSignatureValid(final Map<String, String> reqData,String signType) throws Exception {
+		// 返回数据的签名方式和请求中给定的签名方式是一致的
+		return isSignatureValid(reqData,WxConfig.apikey,signType);
+	}
+
+	/**
+	 * 判断签名是否正确,必须包含sign字段,否则返回false。
+	 * @param data Map类型数据
+	 * @param key API密钥
+	 * @param signType 签名方式
+	 * @return 签名是否正确
+	 * @throws Exception
+	 */
+	public static boolean isSignatureValid(Map<String, String> data, String key, String signType) throws Exception {
+		if (!data.containsKey("sign")) {
+			return false;
+		}
+		String sign = data.get("sign");
+		return getSignature(data, key, signType).equals(sign);
+	}
+
+	/**
+	 * 生成支付二维码
+	 * @param response 响应
+	 * @param contents url链接
+	 * @throws Exception
+	 */
+	public static void writerPayImage(HttpServletResponse response, String contents) throws Exception{
+		ServletOutputStream out = response.getOutputStream();
+		try {
+			Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
+			hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
+			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
+			hints.put(EncodeHintType.MARGIN, 0);
+			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE,300,300,hints);
+			MatrixToImageWriter.writeToStream(bitMatrix,"jpg",out);
+		}catch (Exception e){
+			throw new Exception("生成二维码失败!");
+		}finally {
+			if(out != null){
+				out.flush();
+				out.close();
+			}
+		}
+	}
+
+	/**
+	 * 生成商户订单号
+	 * @return String
+	 */
+	public static String mchOrderNo(){
+		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
+		String date = sdf.format(new Date());
+
+		Random random = new Random();
+		String fourRandom = String.valueOf(random.nextInt(10000));
+		int randLength = fourRandom.length();
+		//不足4位继续补充
+		if(randLength<4){
+			for(int remain = 1; remain <= 4 - randLength; remain ++ ){
+				fourRandom += random.nextInt(10)  ;
+			}
+		}
+		return date+fourRandom;
+	}
+
+	/**
+	 * 返回信息给微信
+	 * @param response
+	 * @param content 内容
+	 * @throws Exception
+	 */
+	public static void responsePrint(HttpServletResponse response, String content) throws Exception{
+		response.setCharacterEncoding("UTF-8");
+		response.setContentType("text/xml");
+		response.getWriter().print(content);
+		response.getWriter().flush();
+		response.getWriter().close();
+	}
+
+
+}

+ 211 - 0
applicationContext.xml

@@ -0,0 +1,211 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:p="http://www.springframework.org/schema/p"
+       xmlns:aop="http://www.springframework.org/schema/aop"
+       xmlns:context="http://www.springframework.org/schema/context"
+       xmlns:jee="http://www.springframework.org/schema/jee"
+       xmlns:tx="http://www.springframework.org/schema/tx"
+       xsi:schemaLocation="
+        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
+        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
+        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
+        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
+        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
+
+    <!-- <context:property-placeholder location="classpath:jdbc.properties" /> -->
+    <!-- 设置需要进行Spring注解扫描的类包 -->
+    <context:component-scan base-package="com.happy" />
+
+    <!-- session设置 -->
+    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
+        <property name="maxInactiveIntervalInSeconds" value="3600"></property>
+    </bean>
+
+    <!-- redis连接池 -->
+    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"></bean>
+
+    <!-- redis连接工厂 -->
+    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
+        <property name="hostName" value="106.12.61.111"/>
+        <property name="port" value="6379"/>
+        <property name="password" value="Asd_123!"/>
+        <property name="timeout" value="20000"/>
+        <property name="poolConfig" ref="poolConfig"></property>
+    </bean>
+
+
+    <!-- <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
+         <property name="connectionFactory" ref="connectionFactory"/>
+    </bean> -->
+
+    <!-- 自动加载构建bean
+     <context:component-scan base-package="com.happy.service" />
+     <context:component-scan base-package="com.happy.dao" />   -->
+
+    <!-- 写库数据源 -->
+    <bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
+        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
+        <property name="url" value="jdbc:mysql://106.12.61.111:3306/HotWater?useCursorFetch=true&amp;autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"></property>
+        <property name="username" value="root"></property>
+        <property name="password" value="Asd!688549"></property>
+
+        <!-- 初始化连接大小 -->
+        <property name="initialSize" value="1" />
+        <!-- 连接池最大使用连接数量 -->
+        <property name="maxActive" value="201" />
+        <!-- 连接池最小空闲 -->
+        <property name="minIdle" value="1" />
+
+
+        <!-- 配置获取连接等待超时的时间 -->
+        <property name="maxWait" value="60000" />
+
+        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
+        <property name="timeBetweenEvictionRunsMillis" value="60000" />
+
+        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
+        <property name="minEvictableIdleTimeMillis" value="300000" />
+
+        <property name="validationQuery" value="SELECT 'x'" />
+        <property name="testWhileIdle" value="true" />
+        <property name="testOnBorrow" value="false" />
+        <property name="testOnReturn" value="false" />
+
+
+        <!-- 超过时间限制是否回收 -->
+        <!-- <property name="removeAbandoned" value="true" />  -->
+        <!-- 超时时间;单位为秒。180秒=3分钟 -->
+        <!-- <property name="removeAbandonedTimeout" value="180" /> -->
+        <!-- 关闭abanded连接时输出错误日志 -->
+        <!-- <property name="logAbandoned" value="true" /> -->
+
+
+        <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用) -->
+        <!-- <property name="poolPreparedStatements" value="true" />
+        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />   -->
+
+        <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
+        <property name="filters" value="stat" />
+
+    </bean>
+    <!-- 读库数据源 -->
+    <bean id="slaveDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
+        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
+        <property name="url" value="jdbc:mysql://106.12.61.111:3306/HotWater?useCursorFetch=true&amp;autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"></property>
+        <property name="username" value="root"></property>
+        <property name="password" value="Asd!688549"></property>
+
+        <!-- 初始化连接大小 -->
+        <property name="initialSize" value="1" />
+        <!-- 连接池最大使用连接数量 -->
+        <property name="maxActive" value="201" />
+        <!-- 连接池最小空闲 -->
+        <property name="minIdle" value="1" />
+
+
+        <!-- 配置获取连接等待超时的时间 -->
+        <property name="maxWait" value="60000" />
+
+        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
+        <property name="timeBetweenEvictionRunsMillis" value="60000" />
+
+        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
+        <property name="minEvictableIdleTimeMillis" value="300000" />
+
+        <property name="validationQuery" value="SELECT 'x'" />
+        <property name="testWhileIdle" value="true" />
+        <property name="testOnBorrow" value="false" />
+        <property name="testOnReturn" value="false" />
+
+
+        <!-- 超过时间限制是否回收 -->
+        <!-- <property name="removeAbandoned" value="true" />  -->
+        <!-- 超时时间;单位为秒。180秒=3分钟 -->
+        <!-- <property name="removeAbandonedTimeout" value="180" /> -->
+        <!-- 关闭abanded连接时输出错误日志 -->
+        <!-- <property name="logAbandoned" value="true" /> -->
+
+
+        <!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用) -->
+        <!-- <property name="poolPreparedStatements" value="true" />
+        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />   -->
+
+        <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
+        <property name="filters" value="stat" />
+
+    </bean>
+
+    <!-- 定义数据源,使用自己定义的数据源 -->
+    <bean id="dataSource" class="com.happy.myDataSource.DynamicDatasource">
+        <!-- 设置多个数据源 -->
+        <property name="targetDataSources">
+            <map key-type="java.lang.String">
+                <entry key="master" value-ref="masterDataSource"></entry>
+                <entry key="slave" value-ref="slaveDataSource"></entry>
+            </map>
+        </property>
+        <property name="defaultTargetDataSource" ref="masterDataSource"></property>
+    </bean>
+
+    <!-- 配置Jdbc模板 -->
+    <!--  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
+         <property name="dataSource" ref="dataSource"></property>
+     </bean> -->
+
+    <!-- 配置Jdbc模板 -->
+    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" scope="prototype">
+        <constructor-arg ref="dataSource"></constructor-arg>
+    </bean>
+
+    <!-- 配置事务管理器 -->
+    <bean id="transactionManager" scope="prototype"
+          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
+        <property name="dataSource" ref="dataSource" />
+    </bean>
+
+    <!-- 配置事务通知属性 -->
+    <tx:advice id="txAdvice" transaction-manager="transactionManager" >
+        <!-- 定义事务传播属性 -->
+        <tx:attributes>
+            <tx:method name="insert*" propagation="REQUIRED" />
+            <tx:method name="count*" propagation="REQUIRED" />
+            <tx:method name="update*" propagation="REQUIRED" />
+            <tx:method name="edit*" propagation="REQUIRED" />
+            <tx:method name="save*" propagation="REQUIRED" />
+            <tx:method name="add*" propagation="REQUIRED" />
+            <tx:method name="new*" propagation="REQUIRED" />
+            <tx:method name="set*" propagation="REQUIRED" />
+            <tx:method name="remove*" propagation="REQUIRED" />
+            <tx:method name="delete*" propagation="REQUIRED"/>
+            <tx:method name="change*" propagation="REQUIRED" />
+            <tx:method name="batch*" propagation="REQUIRED" />
+
+            <tx:method name="get*" read-only="true" />
+            <tx:method name="find*" read-only="true" />
+            <tx:method name="load*" read-only="true" />
+            <tx:method name="comb*" read-only="true" />
+            <tx:method name="query*" read-only="true" />
+            <tx:method name="list*" read-only="true" />
+            <tx:method name="export*" read-only="true" />
+
+            <tx:method name="*" propagation="REQUIRED"  />
+        </tx:attributes>
+    </tx:advice>
+
+    <bean id="dataSourceAspect" class="com.happy.myDataSource.DataSourceAspect"></bean>
+
+    <!-- 配置事务切面 -->
+    <aop:config>
+        <!-- 配置切点 -->
+        <aop:pointcut id="serviceOperation"
+                      expression="execution(* com.happy.service.*.*(..))" />
+        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
+
+        <aop:aspect ref="dataSourceAspect" order="-9999">
+            <aop:before method="before" pointcut-ref="serviceOperation"/>
+        </aop:aspect>
+
+    </aop:config>
+
+</beans>

+ 72 - 0
struts.xml

@@ -0,0 +1,72 @@
+<?xml version="1.0" encoding="UTF-8"?>  
+<!DOCTYPE struts PUBLIC  
+    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
+    "http://struts.apache.org/dtds/struts-2.3.dtd">
+
+<struts>
+	<constant name="struts.enable.DynamicMethodInvocation" value="true" />
+	<!-- 修改上传文件的大小 -->
+	<constant name="struts.multipart.maxSize" value="50000000"/>
+	<package name="happy" namespace="/" extends="struts-default">
+
+	<action name="user*" method = "{1}" class="com.happy.action.User">
+		<result name="list">/jsp/list.jsp</result>
+	</action>
+	
+	<action name="wxpay*" method = "{1}" class="com.happy.action.WxPay">
+		
+	</action>
+	<action name="wp*" method = "{1}" class="com.happy.action.Wp">
+
+	</action>
+	<action name="el*" method = "{1}" class="com.happy.action.Elec">
+
+	</action>
+	<action name="build*" method = "{1}" class="com.happy.action.Build">
+
+	</action>
+	<action name="con*" method = "{1}" class="com.happy.action.Config">
+
+	</action>
+	<action name="place*" method = "{1}" class="com.happy.action.PlaceAction">
+	   <result name="info">/jsp/model_info.jsp</result>
+	   <result name="suess">/jsp/place_list.jsp</result>
+	</action>
+
+	</package>
+	<package name="interfaces" namespace="/interfaces" extends="struts-default">
+		<!-- 接口总调度开始 -->
+		<action name="main*" method="{1}" class="com.happy.action.MainAction">
+		</action>
+		<!-- 接口总调度结束 -->
+		<!-- 维修类型接口开始 -->
+		<action name="repairtype*" method="{1}" class="com.happy.action.RepairTypeAction">
+		</action>		
+		<!-- 维修类型接口结束 -->
+		<!-- 产品品牌接口开始 -->
+		<action name="brand*" method="{1}" class="com.happy.action.BrandAction">
+		</action>
+		<!-- 产品品牌接口结束 -->
+		<!-- 产品分类接口开始 -->
+		<action name="classify*" method="{1}" class="com.happy.action.ClassifyAction">
+		</action>
+		<!-- 产品分类接口结束 -->
+		<!-- 产品型号接口开始 -->
+		<action name="model*" method="{1}" class="com.happy.action.ModelAction">
+		</action>
+		<!-- 产品型号接口结束 -->
+		<!-- 工单接口开始 -->
+		<action name="order*" method="{1}" class="com.happy.action.OrderAction">
+		</action>
+		<!-- 工单接口结束 -->
+		<!-- 查看常用信息接口开始 -->
+		<action name="user*" method="{1}" class="com.happy.action.UsersAction">
+		</action>
+		<!-- 查看常用信息接口结束 -->
+		<!-- 查看常用信息接口开始 -->
+		<action name="maintenanceapply*" method="{1}" class="com.happy.action.MaintenanceApplyAction">
+		</action>
+		<!-- 查看常用信息接口结束 -->
+	</package>
+	
+</struts>   

+ 187 - 0
test.json

@@ -0,0 +1,187 @@
+[{
+	"school": "黄家湖校区",
+	"builds": [{
+			"building": "1栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["1101", "1102", "1103", "1104", "1105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["1201", "1202", "1203", "1204", "1205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["1301", "1302", "1303", "1304", "1305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["1401", "1402", "1403", "1404", "1405"]
+				}
+			]
+		},
+		{
+			"building": "2栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["2101", "2102", "2103", "2104", "2105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["2201", "2202", "2203", "2204", "2205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["2301", "2302", "2303", "2304", "2305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["2401", "2402", "2403", "2404", "2405"]
+				}
+			]
+		},
+		{
+			"building": "3栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["3101", "3102", "3103", "3104", "3105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["3201", "3202", "3203", "3204", "3205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["3301", "3302", "3303", "3304", "3305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["3401", "3402", "3403", "3404", "3405"]
+				}
+			]
+		},
+		{
+			"building": "4栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["4101", "4102", "4103", "4104", "4105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["4201", "4202", "4203", "4204", "4205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["4301", "4302", "4303", "4304", "4305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["4401", "4402", "4403", "4404", "4405"]
+				}
+			]
+		},
+		{
+			"building": "5栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["5101", "5102", "5103", "5104", "5105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["5201", "5202", "5203", "5204", "5205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["5301", "5302", "5303", "5304", "5305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["5401", "5402", "5403", "5404", "5405"]
+				}
+			]
+		}
+	]
+}, {
+	"school": "墨轩湖校区",
+	"builds": [{
+			"building": "1栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["1101", "1102", "1103", "1104", "1105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["1201", "1202", "1203", "1204", "1205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["1301", "1302", "1303", "1304", "1305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["1401", "1402", "1403", "1404", "1405"]
+				}
+			]
+		},
+		{
+			"building": "2栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["2101", "2102", "2103", "2104", "2105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["2201", "2202", "2203", "2204", "2205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["2301", "2302", "2303", "2304", "2305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["2401", "2402", "2403", "2404", "2405"]
+				}
+			]
+		},
+		{
+			"building": "3栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["3101", "3102", "3103", "3104", "3105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["3201", "3202", "3203", "3204", "3205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["3301", "3302", "3303", "3304", "3305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["3401", "3402", "3403", "3404", "3405"]
+				}
+			]
+		},
+		{
+			"building": "4栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["4101", "4102", "4103", "4104", "4105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["4201", "4202", "4203", "4204", "4205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["4301", "4302", "4303", "4304", "4305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["4401", "4402", "4403", "4404", "4405"]
+				}
+			]
+		},
+		{
+			"building": "5栋",
+			"floors": [{
+					"floor": "1层",
+					"rooms": ["5101", "5102", "5103", "5104", "5105"]
+				},
+				{
+					"floor": "2层",
+					"rooms": ["5201", "5202", "5203", "5204", "5205"]
+				}, {
+					"floor": "3层",
+					"rooms": ["5301", "5302", "5303", "5304", "5305"]
+				}, {
+					"floor": "4层",
+					"rooms": ["5401", "5402", "5403", "5404", "5405"]
+				}
+			]
+		}
+	]
+}]

+ 40 - 0
test2.java

@@ -0,0 +1,40 @@
+import java.io.File;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Random;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+
+/**
+ * 使用JAVA DOM PARSER:修改 XML 文件
+ *
+ * @author zfc
+ * @date 2017年12月7日 下午8:31:55
+ */
+public class test2 {
+    public static void main(String[] args) {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
+        String date = sdf.format(new Date());
+
+        Random random = new Random();
+        String fourRandom = String.valueOf(random.nextInt(10000));
+        int randLength = fourRandom.length();
+        //不足4位继续补充
+        if(randLength<4){
+            for(int remain = 1; remain <= 4 - randLength; remain ++ ){
+                fourRandom += random.nextInt(10)  ;
+            }
+        }
+        System.out.println(date+fourRandom);
+    }
+}

+ 10 - 0
zc.properties

@@ -0,0 +1,10 @@
+#conf.global.upload.image.dir=/usr/local/apache-tomcat-7.0.69/webapps/HappysSystem/happy/image
+conf.global.upload.image.dir=/usr/local/apache-tomcat-8.0.28/webapps/HappysSystem/happy/image
+#conf.global.upload.image.dir=D\:/apache-tomcat-8.0.28/webapps/HappysSystemhappy/image
+#conf.global.upload.image.dir=/opt/apache-tomcat-8.0.28/webapps/HappysSystem/happy/image
+#conf.global.upload.image.dir=D\:/tomcat7.0/tomcat7.0/apache-tomcat-7.0.52/webapps/CustomerServiceManager/csm/image
+#conf.global.upload.image.dir=D\:/tomcat7.0/tomcat7.0/apache-tomcat-7.0.52/webapps/HappysSystem/happy/image
+#conf.global.upload.image.dir=C\:/tomcat6/webapps/CustomerServiceManager/csm/image
+#conf.global.upload.image.dir=/home/bae/app/CustomerServiceManager/csm/image
+
+conf.global.decrypt.key=123456789012345678901234567890~!