初始化

This commit is contained in:
admin
2022-09-13 16:43:11 +08:00
parent 0e1b7f4561
commit 4e1dece453
30 changed files with 5171 additions and 0 deletions

19
.classpath Normal file
View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="con" path="com.genuitec.runtime.library/com.genuitec.jstl_1.2.2">
<attributes>
<attribute name="org.eclipse.jst.component.dependency" value="WEB-INF/lib"/>
<attribute name="owner.project.facets" value="jst.web.jstl"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v8.0"/>
<classpathentry kind="output" path="WebRoot/WEB-INF/classes"/>
</classpath>

46
.project Normal file
View File

@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>pay</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.genuitec.eclipse.ast.deploy.core.DeploymentBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>

12
.settings/.jsdtscope Normal file
View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="WebRoot"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary/StandardBrowser/html5"/>
<classpathentry kind="output" path=""/>
</classpath>

View File

@@ -0,0 +1,3 @@
eclipse.preferences.version=1
validator.Checked=WebRoot/js,WebRoot/index.html
validator.Unchecked=

View File

@@ -0,0 +1,2 @@
defaultTldInfo=f\=http\://java.sun.com/jsf/core;http\://java.sun.com/jsf/html\=h;http\://struts.apache.org/tags-bean\=bean;http\://java.sun.com/jsp/jstl/fmt\=fmt;bean\=http\://struts.apache.org/tags-bean;nested\=http\://struts.apache.org/tags-nested;http\://java.sun.com/jsp/jstl/sql\=sql;c\=http\://java.sun.com/jsp/jstl/core;fmt\=http\://java.sun.com/jsp/jstl/fmt;http\://struts.apache.org/tags-logic\=logic;http\://java.sun.com/jsp/jstl/xml\=x;http\://java.sun.com/jsp/jstl/core\=c;logic\=http\://struts.apache.org/tags-logic;h\=http\://java.sun.com/jsf/html;http\://struts.apache.org/tags-tiles\=tiles;http\://java.sun.com/jsp/jstl/functions\=fn;tiles\=http\://struts.apache.org/tags-tiles;sql\=http\://java.sun.com/jsp/jstl/sql;http\://struts.apache.org/tags-html\=html;html\=http\://struts.apache.org/tags-html;http\://struts.apache.org/tags-nested\=nested;http\://java.sun.com/jsf/core\=f;fn\=http\://java.sun.com/jsp/jstl/functions;x\=http\://java.sun.com/jsp/jstl/xml
eclipse.preferences.version=1

View File

@@ -0,0 +1,7 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.compliance=1.7
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.7

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="tb">
<wb-resource deploy-path="/" source-path="/WebRoot" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src"/>
<property name="java-output-path" value="/ROOT/WebRoot/WEB-INF/classes"/>
<property name="context-root" value="/pay"/>
</wb-module>
</project-modules>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<runtime name="Apache Tomcat v8.0"/>
<fixed facet="jst.web"/>
<fixed facet="wst.jsdt.web"/>
<fixed facet="java"/>
<installed facet="java" version="1.7"/>
<installed facet="jst.web" version="3.1"/>
<installed facet="jst.web.jstl" version="1.2.2"/>
<installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>

View File

@@ -0,0 +1 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

View File

@@ -0,0 +1 @@
Window

View File

@@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path:

View File

@@ -0,0 +1,21 @@
<?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:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!--
<context:component-scan base-package="sc545.pay.*" />
<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
-->
</beans>

View File

@@ -0,0 +1,2 @@
a=b
c=d

View File

@@ -0,0 +1,57 @@
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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
">
<context:annotation-config />
<!-- 扫描所有的 controller -->
<context:component-scan base-package="sc545.pay" />
<!-- 将静态资源交于默认的servlet处理 -->
<mvc:default-servlet-handler />
<!-- 启动注解驱动 SpringMVC 功能 -->
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" /> <!-- controller 返回的网页地址根目录 -->
<!-- <property name="suffix" value=".jsp" /> -->
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
<!-- 配置静态资源 -->
<mvc:resources location="/" mapping="/**/*.js" />
<mvc:resources location="/" mapping="/**/*.css" />
<mvc:resources location="/assets/" mapping="/assets/**/*" />
<mvc:resources location="/images/" mapping="/images/*"
cache-period="360000" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="sc545.pay.interceptor.testInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
</beans>

47
WebRoot/WEB-INF/web.xml Normal file
View File

@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>pay</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
</servlet>
<welcome-file-list>
<welcome-file>/index.html</welcome-file>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

113
WebRoot/index.html Normal file
View File

@@ -0,0 +1,113 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>顺诚百宝箱</title>
<style>
* {
margin: 10px auto;
text-align: center;
}
</style>
</head>
<body>
<input type="number" name="num" id="num" placeholder="输入金额">
<button onclick="getPayQr()">获取二维码</button>
<div class="imgs"></div>
<script src='/style/jq-weui/lib/jquery-2.1.4.js'></script>
<script>
/**
* 获取支付二维码<br>
* 自动开启轮询,检查支付是否成功
*
* @param {*} n 金额
* @param {*} t 备注
*/
async function getPayQr() {
var n = $('#num').val();
if (n <= 0 || n > 2000) {
alert("金额错误0~2000");
return;
}
let response = await fetch('/pay/createOrder?n=' + n + '&t=test');
let res = eval("(" + await response.text() + ")");
if (res.code == 1) {
var id = res.out_trade_no;
var img = res.qrimg;
var code = res.qrcode;
if (id == null || id.length < 1) {
alert('获取订单失败');
return;
}
if (img == null || img.length < 1) {
alert('获取二维码失败');
return;
}
$('.imgs').html("<img src='data:image/jpg;base64," + img + "'><br><a href='" + code + "'>手机点这里打开支付宝APP</a><br>使用支付宝扫一扫<br><button onclick='selectPay(" + id + ")'>查询支付状态</button> <button onclick='getPayQr()'>刷新二维码</button>");
subscribe(id);
} else alert('遇到错误 ' + res.msg);
}
/**
*轮询检查支付状态
*/
async function subscribe(id) {
let response = await fetch("/pay/queryPay?id=" + id);
if (response.status == 502) {
// 连接超时,重新连接
await subscribe(id);
} else if (response.status != 200) {
// 一个 error —— 让我们显示它
alert(response.statusText);
// 一秒后重新连接
await new Promise(resolve => setTimeout(resolve, 1000));
await subscribe(id);
} else {
// 获取并显示消息
let message = eval("(" + await response.text() + ")");
// 再次调用 subscribe() 以获取下一条消息
if (message.msg == "已支付") {
$('.imgs').html('支付成功<br>');
return okPay();
}
await subscribe(id);
}
}
/**
* 手动查询支付状态
*/
async function selectPay(id) {
let response = await fetch('/pay/queryPay?id=' + id);
let res = eval("(" + await response.text() + ")");
if (response.status == 200 && res.msg == "已支付") {
return okPay();
} else alert(res.msg);
}
/**
* 支付成功后的逻辑处理
*/
function okPay() {
console.log('支付成功后要做的事');
}
</script>
</body>
</html>

View File

@@ -0,0 +1,21 @@
<?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:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!--
<context:component-scan base-package="sc545.pay.*" />
<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
-->
</beans>

2
src/config.properties Normal file
View File

@@ -0,0 +1,2 @@
a=b
c=d

View File

@@ -0,0 +1,82 @@
package sc545.pay.interceptor;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.*;
import org.springframework.web.servlet.HandlerInterceptor;
import sc545.pay.utils.DBUtil;
import sc545.pay.utils.ReadTxt;
import sc545.pay.utils.Utils;
public class testInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
/*************************************拉黑高频访问ip******************************************/
if(!"".equals(ReadTxt.getSetting(null, "拉黑ip.txt", Utils.getIpAddr(request), ""))){
PrintWriter out = response.getWriter();
out.print("<meta name='viewport' content='width=device-width, initial-scale=1.0'>系统检测到高频次访问已被拉黑IP<br>若误封请前往微信公众号【顺诚百宝箱】反馈<br>感谢理解!<br>IP"+Utils.getIpAddr(request));
return false;
}
String ipdate = ReadTxt.getSetting(null, "访问者IP.txt", Utils.getIpAddr(request), "");//获取此ip上次访问时间和已经访问的次数
String[] idt = ipdate.split("_");//分隔
long i=0;//已经访问的次数
if(!"".equals(ipdate)){
if(ipdate.indexOf("_")>0) i=Utils.getNum(idt[1]);
//检查此ip第一次访问到现在过了几秒
Date ds = Utils.string2Date(idt[0], null);
long xc = (new Date().getTime() - ds.getTime())/1000;
if(xc<=30){//30秒超过50次
if(i>50){//拉黑此ip3天
ReadTxt.writeSetting(null,"拉黑ip.txt", Utils.getIpAddr(request), Utils.date2String(new Date(), null));
ReadTxt.delSetting(null, "访问者IP.txt", Utils.getIpAddr(request));
}else{//正常ip
}
}else{//正常ip
ReadTxt.delSetting(null, "访问者IP.txt", Utils.getIpAddr(request));
}
ReadTxt.writeSetting(null,"访问者IP.txt", Utils.getIpAddr(request), idt[0]+"_"+(++i));
}else
ReadTxt.writeSetting(null,"访问者IP.txt", Utils.getIpAddr(request), Utils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss")+"_1");
/*******************************************************************************/
DBUtil db = new DBUtil();
//闭站
String cw = ReadTxt.getSetting(null, "setting.ini", "closeweb", "0");
if("1".equals(cw)) {
String uri = request.getRequestURI();
if(uri.indexOf("/admin")<0){
Utils.outHtml(response.getWriter(), ReadTxt.getSetting(null, "setting.ini", "closewebtxt", "本站暂停访问"), "/*about:blank*/");
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,140 @@
package sc545.pay.main;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sc545.pay.utils.DBUtil;
import sc545.pay.utils.GsonUtils;
import sc545.pay.utils.Utils;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class MainController {
/**
* 获取付款码
* @param param
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/createOrder", produces = "text/html;charset=UTF-8")
public String createOrder(
@RequestParam(required = false, defaultValue = "") String n,
@RequestParam(required = false, defaultValue = "") String t,
HttpServletRequest request,
HttpServletResponse response
) {
double num = Utils.getNumDouble(n);
if(num<0.01||num>2000) return "{\"errcode\":\"-1\",\"msg\":\"0<金额<2000\"}";
core core=new core();
HashMap<String, String> order = core.createOrder(num, t);
return GsonUtils.ObjectToJson(order);
}
/**
* 查询订单
* @param id
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/queryOrder", produces = "text/html;charset=UTF-8")
public String queryOrder(
@RequestParam(required = false, defaultValue = "") String id,
HttpServletRequest request,
HttpServletResponse response
) {
core core=new core();
Map<String, Object> order = core.queryOrder(id);
return GsonUtils.ObjectToJson(order);
}
/**
* 查询支付是否已完成
* @param id
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/queryPay", produces = "text/html;charset=UTF-8")
public String queryPay(
@RequestParam(required = false, defaultValue = "") String id,
HttpServletRequest request,
HttpServletResponse response
) {
core core=new core();
Map<String, Object> order = core.queryOrder(id);
if(order!=null){
if("3".equals(order.get("ostatus")+"")||"4".equals(order.get("ostatus")+"")) return "{\"msg\":\"已支付\"}";
else return "{\"msg\":\"未支付\"}";
}else{
return "{\"msg\":\"未支付\"}";
}
}
/**
* 支付宝通知回调<br>
* 设置中的“应用网关”
* @param param
* @param request
* @param response
*/
@RequestMapping(value = "/alinotify", produces = "text/html;charset=UTF-8")
public void alinotify(
@RequestParam(required = false, defaultValue = "") Map<String, String> param,
HttpServletRequest request,
HttpServletResponse response
) {
DBUtil db = new DBUtil();
core core=new core();
//只有支付成功后,支付宝才会回调应用接口,可直接获取支付宝响应的参数
String order_id = param.get("out_trade_no");
int s =0;
String ss = param.get("trade_status");
if("WAIT_BUYER_PAY".equals(ss)) s=1;
else if("TRADE_CLOSED".equals(ss)) s=2;
else if("TRADE_SUCCESS".equals(ss)) s=3;
else if("TRADE_FINISHED".equals(ss)) s=4;
//检查数据库是否有本数据,有就修改,没有新增
int i = db.execSql("select * from _orders where out_trade_no = ?", new String[]{order_id});
if(i>0) core.updateOrder(order_id);
else{
db.execUpdate("insert into _orders(out_trade_no,trade_no,otitle,onum,ostatus,zfbuser,paynum,getnum,zfbuserid,getbody) "
+ "values("+order_id+",?,?,"+param.get("total_amount")+","+s+",?,"+param.get("buyer_pay_amount")+","+param.get("receipt_amount")+",?,?)", new String[]{param.get("trade_no"),param.get("subject"),param.get("buyer_logon_id"),param.get("buyer_id"),param.toString()});
}
}
}

View File

@@ -0,0 +1,161 @@
package sc545.pay.main;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sc545.pay.utils.DBUtil;
import sc545.pay.utils.ImgUtils;
import sc545.pay.utils.ReadTxt;
import sc545.pay.utils.Utils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
public class core {
AlipayClient client = null;
/**支付宝回调的接口地址*/
private static String aliNotifyUrl = ReadTxt.getSetting(null, "setting.ini", "web", "localhost")+"/pay/alinotify";
public core() {
getConfig();
}
public static void main(String[] args) {
//每天定时清空无订单和超时关闭的数据库数据
core c=new core();
c.queryOrder("1655263616880");
c.updateOrder("1655272489467");
}
/**
* 创建付款订单
*/
public HashMap<String, String> createOrder(double num,String title){
if(num<=0) return null;
HashMap<String, String> rs = new HashMap<>();
AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
String h=new Date().getTime()+Utils.randomNum(10, 99)+"";
AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
model.setOutTradeNo(h);//订单号(保证不重复)
model.setTotalAmount(num+"");//订单金额
model.setSubject(title);//标题(关键字)不可用特殊标点
model.setQrCodeTimeoutExpress("10m");
request.setBizModel(model);
request.setNotifyUrl(aliNotifyUrl);//应用网关(异步通知)
AlipayTradePrecreateResponse response = null;
try {
response = client.execute(request);
} catch (AlipayApiException e) {e.printStackTrace();}
if(response.isSuccess()){
//订单存入数据库
DBUtil db = new DBUtil();
int i = db.execUpdate("insert into _orders(out_trade_no,otitle,onum,qrcode) values("+ response.getOutTradeNo()+",?,"+num+",?)", new String[]{title,response.getQrCode()});
if(i==1){
rs.put("code", "1");
rs.put("qrcode", response.getQrCode());
rs.put("qrimg", ImgUtils.QrImgB64(response.getQrCode(), 300));
rs.put("out_trade_no", response.getOutTradeNo());
}else rs.put("errcode", "-1");
} else {
rs.put("errcode", "-1");
}
return rs;
}
/**查询订单状态*/
public Map<String, Object> queryOrder(String orderId){
if(orderId==null||orderId.trim().length()<1) return null;
DBUtil db = new DBUtil();
//查数据库
//先检查数据库是否有这个数据,若查不到或者等待付款,就去更新订单状态,交易成功和交易结束直接返回,订单关闭就把数据库数据删除
List<Map<String, Object>> rs = db.execQuery("select * from _orders where out_trade_no = ?", new String[]{orderId});
if(rs!=null&&rs.size()>0){
Map<String, Object> o = rs.get(0);
if("0".equals(o.get("ostatus")+"")||"1".equals(o.get("ostatus")+"")){
AlipayTradeQueryResponse r = updateOrder(orderId);
if(r==null) return null;
return queryOrder(orderId);
}
else if("2".equals(o.get("ostatus")+"")) {
db.execUpdate("delete from _orders where out_trade_no = ?", new String[]{orderId});
return null;
}
return o;
}else{
AlipayTradeQueryResponse r = updateOrder(orderId);
if(r==null) return null;
return queryOrder(orderId);
}
}
/**更新订单状态*/
public AlipayTradeQueryResponse updateOrder(String orderId){
if(orderId==null||orderId.trim().length()<1) return null;
DBUtil db = new DBUtil();
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
AlipayTradeQueryModel model = new AlipayTradeQueryModel();
model.setOutTradeNo(orderId);
request.setBizModel(model);
AlipayTradeQueryResponse response = null;
try {
response = client.execute(request);
} catch (AlipayApiException e) {e.printStackTrace();}
int s=0;
if("WAIT_BUYER_PAY".equals( response.getTradeStatus())) s=1;
else if("TRADE_CLOSED".equals( response.getTradeStatus())) s=2;
else if("TRADE_SUCCESS".equals( response.getTradeStatus())) s=3;
else if("TRADE_FINISHED".equals( response.getTradeStatus())) s=4;
//查询不到说明没有付款
if(response.getTradeNo()==null||response.getTradeNo().trim().length()<5){
//db.execUpdate("delete from _orders where out_trade_no = ?", new String[]{orderId});
return null;
}
//更新数据库订单
db.execUpdate("update _orders set trade_no=?,ostatus="+s+",zfbuser=?,paynum="+response.getBuyerPayAmount()+",getnum="+response.getReceiptAmount()+",zfbuserid=?,getbody=? where out_trade_no = ?", new String[]{response.getTradeNo(), response.getBuyerLogonId(),response.getBuyerUserId(),response.getBody(),orderId});
return response;
}
/**
* 接口调用配置
*/
public void getConfig() {
String appid="2021003131621776";
String private_key="MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCZu1LRuq3Ka79zzv9OgAYNYFVEFetjSsrBJ/N34aBYY3BIOLe5dIt7EQNjx1QUNlSsWU7EwW3AFurXK6iWjXOZrJHZKcM9tzZfsuQeeufnpDtAU90zMSJcu17JfBsTXaXHUEBtQ0wjbuQJ+ihQMB5FtYBg3CuCxUtLqS2/g/n/qlW9ZKPTdnyBCro8pd8w1S5op591aiQGqIZ8ufW45ysCCfjZdOYkFmZMMM2Z5DQjtkQiXgX4aiN5VY5UhyEcGHd3kr9AaYPTC1hLZNUpZXsc2lgdOKQNrZ1FOmxJU4RpNJ9DxrbAgxUQIpvKj5/uOtBFaBmK/CYiVvjBRK5qilZFAgMBAAECggEBAIaNl1pr6wq9re9d4MXDdgilJVwXV1QrtTTEk+t8dsyGFFOSGPRgVmibpnzhjOy39Pp4nGHH7xhutpMn6kIDgoehrHIHhJRy1EuElvc6mdl8PEP8YyIYQjwp3ze4wTX9BElkK0+21GA7Aard4gT1aLmYt8mPSyIFLvcFFz6F8/1ZqKzOtv4jXigXjDzmu/cHks7jamHhknFOn3D7rzfUUViP+2J4HEiSaJXdmzU05aA5glJSLSw4366/GFHsy/Zh3d4FwcFuRu7L+X8gx5vlsPm6E9J7LAt0k+rL5XZVjdkR+Svzkou6EIX+vyZGgxPcUzsZj/V+jMumwALkqyyWP4ECgYEA5wbEJE+sx1NpzeF0/mrIDaB72mX51xpxX93zFCDLzGEY8HiJeR/+UodsNRtGn/W4kBXGSqh0nRnnASs12LGUO+uXcODS2AvSCcV2l5Uh3ecDFavTSeZfAX6yLlw6aecxvRbtDPugPhZ2+i1yc5elyGs5nTd8TjWrdEz0IrTx5eUCgYEAqlmRZpprAb4mSwAQ9+tr9ldvf5xezLzwYNmqRK221OpjFX9oi82MkZrnjcHuEIxpz8quc09A9C+IJ7a1RquWWL52wvjPk52Lbs/vKmGE1h7CF/5Dz4bTOCSF5Kp3SN3HjUI852InWX1pUw1WL5ufVK4mopGs1C3d8ifTSbW9qOECgYEAtO1inMFdIblcqiUAV+NOiwV9GZw1XtVRpu+OV9wbXxNH0cPEffylUwLFpo2W8N0iTo0O/xcQRJytggfSIsNnwMmPj5Iy7YnMU2S2rJ3ZqQwrKUSosz5cdzI+3vnRsXCjTl/vA/ToGNfFE8aV1JsV9XCr7Ukv65wyi2Fc7PViYFUCgYEAoXp+JjDCtsg1LGtHqntzv/RqMSFdi96eTnCGwsuYwIPeoQZBaCTU10FrtijbLryroNmUPKIoBFD6VAsSE4eb4UvK8E9DFb8F6WkaYaZHcWF+w5e3WAWKO3IDqhsdL+lrvC/J49xbSK1lJeFCjaaLho3++aP1nLxN47p0wy6QNoECgYBi5tW50hn9Kyx8WTgJZJgAPT4udLtrLhiLZsS2fucyvumUa5AWUvqF3jAn81ty4hsVXiY5/jiMplRDTCvOSkmmwD+55pSENuVXMDIJXyi9YCB5EJseSr5s5K3IziaVgYkIsiGBz3wVpordQAXID4gm53tWcuoZM7R9d7gwFkhnmQ==";
String public_key="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsRU1//mlUZ9h0KP1P0ck/y5lPmDUkgNz9fXhZ9QRK2ZlrwnweYC6abOYauy5/Q2yQEjmWO41DfIUEJcejun2yq0hFJ8vz+BiKzEK7jkaHJfm1+MAQ06Y0QzCsPEgTpLiM/wXHvwezqVRjqvlkv6y9K4H0INyWcMi+1BpM0HWdyVeTDxYAG6grn9k6yLfPrqe0zZmVhRUxxQqkf/opZFjRDPQVpsqWU4kICh6/32J83SMPisvdJ7Ad5DJQnGNR/GCQ4tF2rAX/DEi3xuC6+JjIH+CbGYDQq+ovLNXNIS9se80kNRn0ge9guij91u9+JOF/sSMUrf66aUeMS41pZ3+8QIDAQAB";
String sign_type="RSA2";
client =new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appid,private_key,"json","utf-8",public_key,sign_type);
}
}

View File

@@ -0,0 +1,274 @@
package sc545.pay.utils;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DBUtil {
// 四大金刚
String driver = "com.mysql.jdbc.Driver";// 驱动名称
String url = "jdbc:mysql://"+ReadTxt.getSetting(null, "setting.ini", "MySqlIP","127.0.0.1")+":"+ReadTxt.getSetting(null, "setting.ini", "MySqlPort","3306")+"/"+ReadTxt.getSetting(null, "setting.ini", "MySqlName","test")+"?useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true&autoReconnect=true&useSSL=false";// 连接
String username = ReadTxt.getSetting(null, "setting.ini", "MySqlUserName","root");// 用户名
String password = ReadTxt.getSetting(null, "setting.ini", "MySqlPassWord","cheng355217");// 密码
// 三剑客
Connection con = null;// 连接对象
PreparedStatement pstmt = null;// 语句对象
ResultSet rs = null;// 结果集对象
/**
* 获得连接对象
*
* @return 连接对象
* @throws ClassNotFoundException
* @throws SQLException
*/
public Connection getConnection() {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
/**
* 关闭三剑客
*
* @throws SQLException
*/
public void close(ResultSet rs, PreparedStatement pstmt, Connection con) {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* 执行更新
*
* @param sql
* 传入的预设的 sql语句
* @param params
* 问号参数列表
* @return 影响行数
*/
public int execUpdate(String sql, Object[] params) {
try {
this.getConnection();// 获得连接对象
this.pstmt = this.con.prepareStatement(sql);// 获得预设语句对象
if (params != null) {
// 设置参数列表
for (int i = 0; i < params.length; i++) {
// 因为问号参数的索引是从1开始所以是i+1将所有值都转为字符串形式好让setObject成功运行
this.pstmt.setObject(i + 1, params[i] + "");
}
}
return this.pstmt.executeUpdate(); // 执行更新,并返回影响行数
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
this.close(this.rs, this.pstmt, this.con);
}
return 0;
}
/**
* 执行查询sql,返回记录条数
*
* @param sql
* @param params
* @return
*/
public int execSql(String sql, Object[] params) {
try {
this.getConnection();// 获得连接对象
this.pstmt = this.con.prepareStatement(sql);// 获得预设语句对象
if (params != null) {
// 设置参数列表
for (int i = 0; i < params.length; i++) {
// 因为问号参数的索引是从1开始所以是i+1将所有值都转为字符串形式好让setObject成功运行
this.pstmt.setObject(i + 1, params[i] + "");
}
}
int i = 0;
rs = this.pstmt.executeQuery();
while (rs.next()) {
i++;
}
return i; // 执行更新,并返回影响行数
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
this.close(this.rs, this.pstmt, this.con);
}
return 0;
}
/**
* 执行查询
*
* @param sql
* 传入的预设的 sql语句
* @param params
* 问号参数列表
* @return 查询后的结果
*/
public List<Map<String, Object>> execQuery(String sql, Object[] params) {
try {
this.getConnection();// 获得连接对象
this.pstmt = this.con.prepareStatement(sql);// 获得预设语句对象
if (params != null) {
// 设置参数列表
for (int i = 0; i < params.length; i++) {
// 因为问号参数的索引是从1开始所以是i+1将所有值都转为字符串形式好让setObject成功运行
this.pstmt.setObject(i + 1, params[i] + "");
}
}
// 执行查询
ResultSet rs = pstmt.executeQuery();
List<Map<String, Object>> al = new ArrayList<Map<String, Object>>();
// 获得结果集元数据(元数据就是描述数据的数据,比如把表的列类型列名等作为数据)
ResultSetMetaData rsmd = rs.getMetaData();
// 获得列的总数
int columnCount = rsmd.getColumnCount();
// 遍历结果集
while (rs.next()) {
Map<String, Object> hm = new HashMap<String, Object>();
for (int i = 0; i < columnCount; i++) {
// 根据列索引取得每一列的列名,索引从1开始
String columnName = rsmd.getColumnName(i + 1);
// 根据列名获得列值
Object columnValue = rs.getObject(columnName);
// 将列名作为key列值作为值放入 hm中每个 hm相当于一条记录
hm.put(columnName, columnValue);
}
// 将每个 hm添加到al中, al相当于是整个表每个 hm是里面的一条记录
al.add(hm);
}
return al;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
this.close(this.rs, this.pstmt, this.con);
}
return null;
}
/**
* 搜索统计
*
* @param search
* @return
*/
public boolean searchCount(String search) {
String resid = "0";
List<Map<String, Object>> res = execQuery(
"select id from byx_count where searchstr =?",
new String[] { search });
if (res != null && res.size() > 0) {
resid = res.get(0).get("id").toString();
int i = execUpdate(
"update byx_count set countsum = countsum+1 where id = "
+ resid, null);
return i > 0 ? true : false;
} else {
int i1 = execUpdate(
"insert into byx_count(countsum,searchstr) values(1,?)",
new String[] { search });
return i1 > 0 ? true : false;
}
}
/**
* 获取对象的属性,返回键值对
* @param obj
* @return
*/
public static HashMap<String, Object[]> reflect(Object obj) {
if (obj == null) return null;
Field[] fields = obj.getClass().getDeclaredFields();
String name="";
Object[] value=new Object[fields.length];
for (int j = 0; j < fields.length; j++) {
fields[j].setAccessible(true);
// 字段名
name+="`"+fields[j].getName() + "`,";
// 字段值
if (fields[j].getType().getName().equals(java.lang.String.class.getName())) {//String
try {
value[j]=(fields[j].get(obj));
} catch (Exception e) {e.printStackTrace();
}
} else if (fields[j].getType().getName().equals(java.lang.Long.class.getName()) || fields[j].getType().getName().equals("long")) {//int/long
try {
value[j]=(fields[j].getLong(obj));
} catch (Exception e) {e.printStackTrace();}
}else if (fields[j].getType().getName().equals(java.lang.Float.class.getName()) || fields[j].getType().getName().equals("float")) {//float/double
try {
value[j]=(fields[j].getFloat(obj));
} catch (Exception e) {e.printStackTrace();}
}else{// 其他类型。。。
try {
value[j]=(fields[j].get(obj));
} catch (Exception e) {e.printStackTrace();}
}
}
HashMap<String, Object[]> m=new HashMap<>();
m.put("name", new Object[]{name});
m.put("value", value);
return m;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,140 @@
package sc545.pay.utils;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
public class GsonUtils{
//线程安全的
private static final Gson GSON;
private static final Gson GSON_NULL; // 不过滤空值
static {
GSON = new GsonBuilder().enableComplexMapKeySerialization() //当Map的key为复杂对象时,需要开启该方法
// .serializeNulls() //当字段值为空或null时依然对该字段进行转换
// .excludeFieldsWithoutExposeAnnotation()//打开Export注解但打开了这个注解,副作用,要转换和不转换都要加注解
.setDateFormat("yyyy-MM-dd HH:mm:ss")//序列化日期格式 "yyyy-MM-dd"
// .setPrettyPrinting() //自动格式化换行
.disableHtmlEscaping() //防止特殊字符出现乱码
.create();
GSON_NULL = new GsonBuilder().enableComplexMapKeySerialization() //当Map的key为复杂对象时,需要开启该方法
.serializeNulls() //当字段值为空或null时依然对该字段进行转换
// .excludeFieldsWithoutExposeAnnotation()//打开Export注解但打开了这个注解,副作用,要转换和不转换都要加注解
.setDateFormat("yyyy-MM-dd HH:mm:ss")//序列化日期格式 "yyyy-MM-dd"
// .setPrettyPrinting() //自动格式化换行
.disableHtmlEscaping() //防止特殊字符出现乱码
.create();
}
//获取gson解析器
public static Gson getGson() {
return GSON;
}
//获取gson解析器 有空值 解析
public static Gson getWriteNullGson() {
return GSON_NULL;
}
/**
* 根据对象返回json
*/
public static String ObjectToJson(Object object) {
return GSON.toJson(object);
}
/**
* 将字符串转化对象
*
* @param json 源字符串
* @param classOfT 目标对象类型
* @param <T>
* @return
*/
public static <T> T JsonToObject(String json, Class<T> classOfT) {
return GSON.fromJson(json, classOfT);
}
/**
* 将字符串转化对象
*
* @param json 源字符串
* @param t 目标对象类型
* @param <T>
* @return
*/
public static <T> T JsonToObject(String json, Type t) {
return GSON.fromJson(json, t);
}
/**
* 将json转化为对应的实体对象
* new TypeToken<List<T>>() {}.getType()
* new TypeToken<Map<String, T>>() {}.getType()
* new TypeToken<List<Map<String, T>>>() {}.getType()
*/
public static <T> T JsonToBean(String json, Type typeOfT) {
return GSON.fromJson(json, typeOfT);
}
/**
* 转成list
* @param gsonString
* @param cls
* @return
*/
public static <T> List<T> JsonToList(String gsonString, Class<T> cls) {
return GSON.fromJson(gsonString, new TypeToken<List<T>>() {
}.getType());
}
/**
* 转成list中有map的
* @param gsonString
* @return
*/
public static <T> List<Map<String, T>> JsonToListMaps(String gsonString) {
return GSON.fromJson(gsonString, new TypeToken<List<Map<String, String>>>() {
}.getType());
}
/**
* 转成map
* @param gsonString
* @return
*/
public static <T> Map<String, T> JsonToMaps(String gsonString) {
return GSON.fromJson(gsonString, new TypeToken<Map<String, T>>() {
}.getType());
}
/**
* 获取json字符串中的某个值
* @param str json字符串
* @param key 字段名
* @param errorKey 若可能返回错误码且没有上述key这个字段这里写错误码的字段名否则填null
* @return 若错误码,返回 "_errorKey_错误码字段值"
*/
public static String getJsonValue(String str,String key,String errorKey){
if(str==null) return "";
if(errorKey!=null&&str.indexOf(errorKey)>=0)
return "_"+errorKey+"_"+new JsonParser().parse(str).getAsJsonObject().get(errorKey).getAsString();
else
return new JsonParser().parse(str).getAsJsonObject().get(key).getAsString();
}
}

View File

@@ -0,0 +1,602 @@
package sc545.pay.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
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.conn.ssl.SSLConnectionSocketFactory;
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.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
/**
* 基于 httpclient 4.5版本的 http工具类
*
*
*/
public class HttpUtils {
private static final CloseableHttpClient httpClient;
public static final String CHARSET = "UTF-8";
// 采用静态代码块初始化超时时间配置再根据配置生成默认httpClient对象
static {
//10秒相应超时
RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).setConnectionRequestTimeout(5000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
public static String doGet(String url, Map<String, String> params) {
return doGet(url, params, CHARSET);
}
public static String doGetSSL(String url, Map<String, String> params) {
return doGetSSL(url, params, CHARSET);
}
public static String doPost(String url, Map<String, String> params){
return doPost(url, params, CHARSET);
}
/**
* HTTP Get 获取内容
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doGet(String url, Map<String, String> params, String charset) {
if(charset==null||charset.trim().length()<1) charset="UTF-8";
if (StringUtils.isBlank(url)) {
return null;
}
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
// 将请求参数和url进行拼接
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
response.close();
if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result);
return result;
} catch (Exception e) {
System.out.println("url错误:::"+e.toString());
e.printStackTrace();
}
return null;
}
/**
* HTTP Post 获取内容
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
* @throws IOException
*/
public static String doPost(String url, Map<String, String> params, String charset) {
if(charset==null||charset.trim().length()<1) charset="UTF-8";
if (StringUtils.isBlank(url)) {
return null;
}
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
try {
if (pairs != null && pairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
}
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result);
return result;
} catch (Exception e) {
return "";
} finally {
if (response != null)
try {
response.close();
} catch (IOException e) {}
}
}
/**
* HTTPS Get 获取内容
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doGetSSL(String url, Map<String, String> params, String charset) {
if(charset==null||charset.trim().length()<1) charset="UTF-8";
if (StringUtils.isBlank(url)) {
return null;
}
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpGet = new HttpGet(url);
// https 注意这里获取https内容使用了忽略证书的方式当然还有其他的方式来获取https内容
CloseableHttpClient httpsClient = HttpUtils.createSSLClientDefault();
CloseableHttpResponse response = httpsClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
response.close();
if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 这里创建了忽略整数验证的CloseableHttpClient对象
* @return
*/
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
/**
* 这里创建了忽略整数验证的CloseableHttpClient对象
* @return
*/
public static CloseableHttpClient createSSLClientCookie(CookieStore cookie) {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(cookie).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
/**
* 发送post请求
* @param url 请求地址
* @param json json格式字符串
* @param contentType 这里用 "application/json"
* @return
*/
public static String post(String url, String json, String contentType,String charset) {
if(charset==null||charset.trim().length()<1) charset="UTF-8";
if("json".equals(contentType)) contentType="application/json";
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient client = httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
HttpPost post = new HttpPost(url);
try {
StringEntity s = new StringEntity(json, "utf-8");
if (StringUtils.isBlank(contentType)) {
s.setContentType("application/json");
}
s.setContentType(contentType);
post.setEntity(s);
HttpResponse res = client.execute(post);
HttpEntity entity = res.getEntity();
String str = EntityUtils.toString(entity, charset);
if(!"UTF-8".equals(getEncoding(str))) str=GBKtoUTF8(str);
return str;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static org.apache.http.client.HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLSv1");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception ex) {
return null;
}
}
//正则找出所有
public static String getUrl(String s){
String regex = "http[s]?:\\/\\/([\\w]+\\.)+[\\w]+([\\w./?%&=]*)?";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(s);
String r="";
while(m.find()){
r+=m.group()+",";
}
return r;
}
/**
* 检查url是否可访问
* @param url
* @return
*/
public static boolean ckUrl(String url) {
if (StringUtils.isBlank(url)) {
return false;
}
HttpGet httpGet = new HttpGet(url);
try {
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) return false;
} catch (Exception e) {
String s = e.getMessage();
if("Timeout waiting for connection from pool".equals(s)) return true;
return false;
}
return true;
}
/**检查字符串编码格式*/
public static String getEncoding(String str)
{
String encode;
encode = "UTF-16";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
return encode;
}
}
catch(Exception ex) {}
encode = "ASCII";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
//字符串 str 中仅由数字和英文字母组成,无法识别其编码格式
return "UTF-8";
}
}
catch(Exception ex) {}
encode = "ISO-8859-1";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
return encode;
}
}
catch(Exception ex) {}
encode = "GB2312";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
return encode;
}
}
catch(Exception ex) {}
encode = "UTF-8";
try
{
if(str.equals(new String(str.getBytes(), encode)))
{
return encode;
}
}
catch(Exception ex) {}
/*
*......待完善
*/
return "UTF-8";
}
/**将字符串转换字符编码*/
public static String GBKtoUTF8(String str) {
if("UTF-8".equals(getEncoding(str))) return str;
return getUTF8StringFromGBKString(str);
}
public static String getUTF8StringFromGBKString(String gbkStr) {
try {
return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new InternalError();
}
}
public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
int n = gbkStr.length();
byte[] utfBytes = new byte[3 * n];
int k = 0;
for (int i = 0; i < n; i++) {
int m = gbkStr.charAt(i);
if (m < 128 && m >= 0) {
utfBytes[k++] = (byte) m;
continue;
}
utfBytes[k++] = (byte) (0xe0 | (m >> 12));
utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
}
if (k < utfBytes.length) {
byte[] tmp = new byte[k];
System.arraycopy(utfBytes, 0, tmp, 0, k);
return tmp;
}
return utfBytes;
}
/**
* 带有cookie和header 的post请求
* @param url
* @param params
* @param cookie
* @param header
* @return
*/
public static String doPost2(String url, Map<String, String> params, CookieStore cookie,Map<String, String> header,String charset) {
if(charset==null||charset.trim().length()<1) charset="UTF-8";
if (StringUtils.isBlank(url)) {
return null;
}
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
HttpPost httpPost = new HttpPost(url);
Set<Entry<String, String>> set = header.entrySet();
Iterator<Entry<String, String>> s = set.iterator();
while (s.hasNext()) {
Map.Entry m = (Map.Entry) s.next();
httpPost.addHeader(m.getKey().toString(),m.getValue().toString());
}
CloseableHttpResponse response = null;
try {
if (pairs != null && pairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
}
CloseableHttpClient httpClientc = HttpUtils.createSSLClientCookie(cookie);
response = httpClientc.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result);
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null)
try {
response.close();
} catch (IOException e) {e.printStackTrace();}
}
return null;
}
public static String doGet2(String url, Map<String, String> params, CookieStore cookie,Map<String, String> header,String charset) {
if(charset==null||charset.trim().length()<1) charset="UTF-8";
if (StringUtils.isBlank(url)) {
return null;
}
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpGet = new HttpGet(url);
Set<Entry<String, String>> set = header.entrySet();
Iterator<Entry<String, String>> s = set.iterator();
while (s.hasNext()) {
Map.Entry m = (Map.Entry) s.next();
httpGet.addHeader(m.getKey().toString(),m.getValue().toString());
}
// https 注意这里获取https内容使用了忽略证书的方式当然还有其他的方式来获取https内容
CloseableHttpClient httpsClient = HttpUtils.createSSLClientCookie(cookie);
CloseableHttpResponse response = httpsClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
response.close();
if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,244 @@
package sc545.pay.utils;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import sun.misc.BASE64Encoder;
import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
public class ImgUtils {
public static void main(String[] args) throws Exception {
}
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
/**
* 删除二维码白边
* @param matrix
* @return
*/
public static BitMatrix deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
return resMatrix;
}
/**
* 生成一张二维码图片文件
* @param content 二维码内容
* @param widthHeight 宽高度
* @param path 图片存储路径(不带文件名)
* @return
*/
public static String QrImgFile(String content,int widthHeight,String path) {
try {
String codeName = UUID.randomUUID().toString();// 二维码的图片名
String imageType = "jpg";// 图片类型
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints);
bitMatrix= deleteWhite(bitMatrix);
// BufferedImage imgbuf = toBufferedImage(bitMatrix);
File file1 = new File(path, codeName + "." + imageType);
writeToFile(bitMatrix, imageType, file1);
return path+codeName + "." + imageType;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成一张二维码图片(BufferedImage)
* @param content 二维码内容
* @param widthHeight 宽高度
* @return
*/
public static BufferedImage QrImgBuf(String content,int widthHeight) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints);
bitMatrix= deleteWhite(bitMatrix);
BufferedImage imgbuf = toBufferedImage(bitMatrix);
return imgbuf;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 生成一张二维码图片(base64)<br>
* data:image/jpg;base64,base64_code
* @param content 二维码内容
* @param widthHeight 宽高度
* @return
*/
public static String QrImgB64(String content,int widthHeight) {
try {
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints);
bitMatrix= deleteWhite(bitMatrix);
BufferedImage imgbuf = toBufferedImage(bitMatrix);
ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。
ImageIO.write(imgbuf, "jpg", os);//利用ImageIO类提供的write方法将bi以png图片的数据模式写入流。
byte b[] = os.toByteArray();//从流中获取数据数组。
String str = new BASE64Encoder().encode(b);
return str;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 图片质量压缩
* @param img 文件流
* @param quality 压缩质量 0~1/1为最高质量
* @return
*/
public static BufferedImage rarImgBuf(InputStream img, double quality) {
BufferedImage buf =null;
try {
buf = Thumbnails.of(img).scale(1f).outputQuality(quality).asBufferedImage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return buf;
}
/**
* 图片质量压缩
* @param img 文件地址
* @param quality 压缩质量 0~1/1为最高质量
* @return
*/
public static File rarImgFile(File img, double quality) {
File arg0 = img;
try {
Thumbnails.of(img).scale(1f).outputQuality(quality).toFile(arg0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arg0;
}
/**
* 裁剪图片<br>
* 从左上角开始裁切<br>
* 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例
*
* @param img 图片文件
* @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER
* @param x 裁切x轴范围
* @param y 裁切y轴范围
* @param width 另存图片的宽度
* @param height 另存图片的高度
* @return
*/
public static File cutImgFile(File img,Positions p,int x,int y,int width,int height) {
File arg0 = img;
try {
Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).toFile(arg0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arg0;
}
/**
* 裁剪图片<br>
* 从左上角开始裁切<br>
* 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例
*
* @param img 图片流
* @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER
* @param x 裁切x轴范围
* @param y 裁切y轴范围
* @param width 另存图片的宽度
* @param height 另存图片的高度
* @return
*/
public static BufferedImage cutImgBuf(InputStream img,Positions p,int x,int y,int width,int height) {
BufferedImage buf =null;
try {
buf=Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).asBufferedImage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return buf;
}
}

View File

@@ -0,0 +1,85 @@
package sc545.pay.utils;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailUtils {
private static final String USER = "scboxs@163.com"; // 发件人称号,同邮箱地址
private static final String HOST = "smtp.163.com"; // SMTP服务器地址
private static final String PASSWORD = "FUTSRKZXNDRSFXUW"; // 如果是qq邮箱可以使户端授权码或者登录密码
public static void main(String[] args) {
boolean t = sendMail("1782158860@qq.com", "这是一个测试邮件", "【顺诚百宝箱】测试邮件");
System.out.println(t);
}
/**
*
* @param to 收件人邮箱
* @param text 邮件正文
* @param title 标题
*/
/* 发送验证信息的邮件 */
public static boolean sendMail(String to, String text, String title){
try {
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", HOST);
// 发件人的账号
props.put("mail.user", USER);
//发件人的密码
props.put("mail.password", PASSWORD);
// 构建授权信息用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
message.setDescription("欢迎关注微信公众号【顺诚百宝箱】\n全网VIP视频、聚合全网小说音乐等APP破解软件游戏大额优惠券福利更多功能等你发现");
// 设置收件人
InternetAddress toAddress = new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO, toAddress);
// 设置邮件标题
message.setSubject(title);
// 设置邮件的内容体
message.setContent(text, "text/html;charset=UTF-8");
// 发送邮件
Transport transport = mailSession.getTransport("smtp");
//设置授权码
transport.connect(username,"授权码");
transport.sendMessage(message,message.getAllRecipients());
transport.close();
return true;
}catch (Exception e){
e.printStackTrace();
}
return false;
}
}

View File

@@ -0,0 +1,716 @@
package sc545.pay.utils;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Random;
import javax.servlet.ServletContext;
public class ReadTxt {
public static void main(String[] args) {
//上月新增访客
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
if(month==0){
month=12;
year=year-1;
}
String ms = String.format("%02d", month);
String ys = String.format("%04d", year);
String smm=ys+"-"+ms;
String smck= ReadTxt.getSetting(null, "count.ini",smm, "0");
String a = ReadTxt.getSetting(null, "setting.ini", "pageNullTelTxt","提交需求");
System.out.println(a+smm+"\n"+ms+"\n"+ys);
}
/**
* 按行读取txt文件
*
* @param path
* 文件地址默认D:\\开头)
* @return ArrayList 返回每行数据为一个items的集合
*/
public static ArrayList<String> readFileLine(ServletContext servletContext, String path) {
if(path.indexOf("./")==0)
path =path.substring(1, path.length());
if (servletContext == null) {
if(path.indexOf(":") <= 0&&path.indexOf("/") <0)
path = "D:\\" + path;
} else {
path = servletContext.getRealPath(path);
}
ArrayList<String> strarr = null;
try {
File file = new File(path);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
strarr = new ArrayList<String>();
while ((lineTxt = bufferedReader.readLine()) != null) {
strarr.add(lineTxt);
}
read.close();
} else {
strarr = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strarr;
}
/**
* 按行读取文件
* debug模式
* @param path
* 文件地址默认D:\\开头)
* @return ArrayList 返回每行数据为一个items的集合
*/
public static ArrayList<String> readFileLineDEBUG(String path) {
if(path.indexOf("./")==0)
path =path.substring(1, path.length());
//debug模式下把所有路径改为tomcat下的真实路径
if(path.indexOf("/")==0){
String tomcat_path = "D:/java/Tomcat_8.5.23/webapps/ROOT";
path =tomcat_path+path;
}
ArrayList<String> strarr = null;
try {
File file = new File(path);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
strarr = new ArrayList<String>();
while ((lineTxt = bufferedReader.readLine()) != null) {
strarr.add(lineTxt);
}
read.close();
} else {
strarr = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strarr;
}
/**
* 写入txt文档已存在就修改否则写入末尾,自动加换行 文件格式key=value换行分隔
*
* @param path
* 文件地址默认D:\\开头)
* @param keyname
* 要修改的参数名
* @param content
* 要修改的参数值
*/
public static void writeSetting(ServletContext servletContext, String path, String keyname, String content) {
/**************/
// 如果存在,则追加内容;如果文件不存在,则创建文件
if(path.indexOf("./")==0)
path =path.substring(1, path.length());
if (servletContext == null) {
if(path.indexOf(":") <= 0&&path.indexOf("/") <0)
path = "D:\\" + path;
} else {
path = servletContext.getRealPath(path);
}
try {
File file = new File(path);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
boolean isread = false;// 是否读取到该行并修改
// 将内容全部读出来,存为新的数据流
// 读到要修改的行进行修改存入,否则原样读取存入
StringBuffer buf = new StringBuffer();
while ((lineTxt = bufferedReader.readLine()) != null) {
if (lineTxt.startsWith(keyname + "=")) {
buf.append(keyname + "=" + content + "\r\n");
isread = true;
} else {
buf.append(lineTxt + "\r\n");
}
}
read.close();
if (!isread) {// 没有读取到,写入末尾
buf.append(keyname + "=" + content + "\r\n");
}
// 把新内容覆盖写入文件
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(path),
"UTF-8")));
out.write(buf.toString());
out.flush();
out.close();
} else {// 不存在,创建写入
String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/"));
File file1 = new File(path2);
// 如果文件夹不存在则创建
if (!file1.exists() && !file1.isDirectory()) {
file1.mkdirs();
}
File file2 = new File(path);
if (!file2.exists()) {
file2.createNewFile();
}
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(path),
"UTF-8")));
out.write(keyname + "=" + content + "\r\n");
out.flush();
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**************/
}
/**
* 读取txt配置返回map集合文件格式key=value换行分隔
*
* @param path
* 文件地址默认D:\\开头)
* @return hashmap
*/
public static HashMap<String, String> readSetting(ServletContext servletContext, String path) {
if(path.indexOf("./")==0)
path =path.substring(1, path.length());
if (servletContext == null) {
if(path.indexOf(":") <= 0&&path.indexOf("/") <0)
path = "D:\\" + path;
} else {
path = servletContext.getRealPath(path);
}
HashMap<String, String> strarr = null;
try {
File file = new File(path);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
strarr = new HashMap<String, String>();
while ((lineTxt = bufferedReader.readLine()) != null) {
if(lineTxt.indexOf("#")==0){
continue;
}
String[] arr = new String[2];
if (lineTxt.split("=").length >= 2) {
arr[0] = lineTxt.split("=")[0];
arr[1] = lineTxt.replace(arr[0]+"=", "");
strarr.put(arr[0], arr[1]);
}
}
read.close();
} else {
strarr = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strarr;
}
/**
* 获取配置文件中所有设置属性(含注释)<br>
* map.get("z") 取注释<br>
* map.get("k") 取key<br>
* map.get("v") 取value<br>
*
*
* @param path
* 文件地址默认D:\\开头)
*
* @param t 只取以此字符开头的不限制填null
* @param st 从以此字符开头的行开始读取不限制填null
* @param et 读到以此字符开头的行结束不限制填null
* @return
*/
public static ArrayList<HashMap<String, String>> getSettingAll(ServletContext servletContext, String path,String t,String st,String et) {
if(st==null||st.length()<1) st="";
if(et==null||et.length()<1) et="";
if(t==null||t.length()<1) t="";
if(path.indexOf("./")==0)
path =path.substring(1, path.length());
if (servletContext == null) {
if(path.indexOf(":") <= 0&&path.indexOf("/") <0)
path = "D:\\" + path;
} else {
path = servletContext.getRealPath(path);
}
ArrayList<HashMap<String, String>> list=new ArrayList<>();
try {
File file = new File(path);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
String zs="";//注释文本
while ((lineTxt = bufferedReader.readLine()) != null) {
if((!"".equals(st))||lineTxt.indexOf(st)!=0) continue;
if((!"".equals(et))&&lineTxt.indexOf(et)==0) break;
HashMap<String, String> map = new HashMap<String, String>();
if(lineTxt.indexOf("#")==0){
zs=lineTxt;
continue;
}
String[] arr = new String[2];
if (lineTxt.split("=").length >= 2&&lineTxt.indexOf(t)==0) {
arr[0] = lineTxt.split("=")[0];
arr[1] = lineTxt.replace(arr[0]+"=", "");
map.put("z", zs);
map.put("k", arr[0]);
map.put("v", arr[1]);
list.add(map);
//把注释也加进去
zs="";
}
}
read.close();
} else {
list = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
/**
* 读取txt配置文件的某一项设置值 文件格式key=value换行分隔
*
* @param path
* 文件地址
* @param settingName
* 设置名
* @param nullString
* 设置值为空时默认返回的内容
* @return string
*/
public static String getSetting(ServletContext servletContext, String path, String settingName,String nullString) {
HashMap<String, String> setting = ReadTxt.readSetting(servletContext,path);
String val = setting == null ? nullString : setting.get(settingName);
val = val == null ? "" : val;
return "".equals(val.trim()) ? nullString : val;
}
/**
* 获取所有设置名以[settingName]开头的数据
* */
public static ArrayList<String> getSettingW(ServletContext servletContext, String path, String settingName) {
HashMap<String, String> setting = ReadTxt.readSetting(servletContext,path);
if(setting==null||setting.size()<1) return null;
Iterator<Entry<String, String>> it = setting.entrySet().iterator();
ArrayList<String> rs=new ArrayList<>();
while (it.hasNext()) {
Entry<String, String> en=it.next();
String k = en.getKey();
String v = en.getValue();
if(k.indexOf(settingName)==0){
rs.add(k+"="+v);
}
}
return rs;
}
/**
* 删除某一项设置值 文件格式key=value换行分隔
*
* @param path
* 文件地址
* @param settingName
* 设置名
* @param nullString
* 设置值为空时默认返回的内容
* @return string
*/
public static void delSetting(ServletContext servletContext, String path, String settingName) {
/**************/
// 如果存在,则追加内容;如果文件不存在,则创建文件
if(path.indexOf("./")==0)
path =path.substring(1, path.length());
if (servletContext == null) {
if(path.indexOf(":") <= 0&&path.indexOf("/") <0)
path = "D:\\" + path;
} else {
path = servletContext.getRealPath(path);
}
try {
File file = new File(path);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
// 将内容全部读出来,存为新的数据流
// 读到要修改的行进行修改存入,否则原样读取存入
StringBuffer buf = new StringBuffer();
while ((lineTxt = bufferedReader.readLine()) != null) {
if (lineTxt.startsWith(settingName + "=")) {
} else {
buf.append(lineTxt + "\r\n");
}
}
read.close();
// 把新内容覆盖写入文件
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(path),
"UTF-8")));
out.write(buf.toString());
out.flush();
out.close();
} else {// 不存在,创建
String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/"));
File file1 = new File(path2);
// 如果文件夹不存在则创建
if (!file1.exists() && !file1.isDirectory()) {
file1.mkdirs();
}
File file2 = new File(path);
if (!file2.exists()) {
file2.createNewFile();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**************/
}
/**
* 删除设置名以[settingName]开头的数据
* @param servletContext
* @param path
* @param settingName
*/
public static void delSettingW(ServletContext servletContext, String path, String settingName) {
/**************/
// 如果存在,则追加内容;如果文件不存在,则创建文件
if(path.indexOf("./")==0)
path =path.substring(1, path.length());
if (servletContext == null) {
if(path.indexOf(":") <= 0&&path.indexOf("/") <0)
path = "D:\\" + path;
} else {
path = servletContext.getRealPath(path);
}
try {
File file = new File(path);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
// 将内容全部读出来,存为新的数据流
// 读到要修改的行进行修改存入,否则原样读取存入
StringBuffer buf = new StringBuffer();
while ((lineTxt = bufferedReader.readLine()) != null) {
if (lineTxt.split("=")[0].indexOf(settingName)==0) {
} else {
buf.append(lineTxt + "\r\n");
}
}
read.close();
// 把新内容覆盖写入文件
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(path),
"UTF-8")));
out.write(buf.toString());
out.flush();
out.close();
} else {// 不存在,创建
String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/"));
File file1 = new File(path2);
// 如果文件夹不存在则创建
if (!file1.exists() && !file1.isDirectory()) {
file1.mkdirs();
}
File file2 = new File(path);
if (!file2.exists()) {
file2.createNewFile();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**************/
}
/**
* 删除过期的所有设置值 文件格式key=value换行分隔
* <br>key为检测源
* @param servletContext
* @param path 路径
* @param d 有效天数
*/
public static void delOutDateSetting(ServletContext servletContext, String path, int d) {
/**************/
// 如果存在,则追加内容;如果文件不存在,则创建文件
if(path.indexOf("./")==0)
path =path.substring(1, path.length());
if (servletContext == null) {
if(path.indexOf(":") <= 0&&path.indexOf("/") <0)
path = "D:\\" + path;
} else {
path = servletContext.getRealPath(path);
}
try {
File file = new File(path);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
// 将内容全部读出来,存为新的数据流
// 读到要修改的行进行修改存入,否则原样读取存入
StringBuffer buf = new StringBuffer();
boolean ts=false;
while ((lineTxt = bufferedReader.readLine()) != null) {
if(lineTxt.indexOf("=")>0&&lineTxt.indexOf("#")<0){
String[] ls = lineTxt.split("=");
int has = ls[0].length()-ls[0].replaceAll("-", "").length();
if(has>1){//日期时间
if(Utils.dateout(ls[0], d)){
buf.append(lineTxt + "\r\n");
}else{
ts=true;
}//过期
}else{//月份时间
buf.append(lineTxt + "\r\n");
}
}else{//注释或者不是setting
buf.append(lineTxt + "\r\n");
}
}
read.close();
if(ts){
// 把新内容覆盖写入文件
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(path),
"UTF-8")));
out.write(buf.toString());
out.flush();
out.close();
}
} else {// 不存在,创建
String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/"));
File file1 = new File(path2);
// 如果文件夹不存在则创建
if (!file1.exists() && !file1.isDirectory()) {
file1.mkdirs();
}
File file2 = new File(path);
if (!file2.exists()) {
file2.createNewFile();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**************/
}
/**
* 删除过期的所有设置值 文件格式key=value换行分隔
* <br>value为检测源
* @param servletContext
* @param path 路径
* @param d 有效天数
*/
public static void delOutDateSettingValue(ServletContext servletContext, String path, int d) {
/**************/
// 如果存在,则追加内容;如果文件不存在,则创建文件
if(path.indexOf("./")==0)
path =path.substring(1, path.length());
if (servletContext == null) {
if(path.indexOf(":") <= 0&&path.indexOf("/") <0)
path = "D:\\" + path;
} else {
path = servletContext.getRealPath(path);
}
try {
File file = new File(path);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), "UTF-8");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
// 将内容全部读出来,存为新的数据流
// 读到要修改的行进行修改存入,否则原样读取存入
StringBuffer buf = new StringBuffer();
boolean ts=false;
while ((lineTxt = bufferedReader.readLine()) != null) {
if(lineTxt.indexOf("=")>0&&lineTxt.indexOf("#")<0){
String[] ls = lineTxt.split("=");
int has = ls[1].length()-ls[1].replaceAll("-", "").length();
if(has>1){//日期时间
if(Utils.dateout(ls[1], d)){
buf.append(lineTxt + "\r\n");
}else{
ts=true;
}//过期
}else{//月份时间
buf.append(lineTxt + "\r\n");
}
}else{//注释或者不是setting
buf.append(lineTxt + "\r\n");
}
}
read.close();
if(ts){
// 把新内容覆盖写入文件
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(path),
"UTF-8")));
out.write(buf.toString());
out.flush();
out.close();
}
} else {// 不存在,创建
String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/"));
File file1 = new File(path2);
// 如果文件夹不存在则创建
if (!file1.exists() && !file1.isDirectory()) {
file1.mkdirs();
}
File file2 = new File(path);
if (!file2.exists()) {
file2.createNewFile();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**************/
}
/**
* 将InputStream装换成某种字符编码的String
*
* @param in
* @param encoding
* @return
*/
public static String InputStreamTOString(InputStream in, String encoding) {
int BUFFER_SIZE = 4096;
String res = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1;
try {
while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
outputStream.write(data, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
res = new String(outputStream.toByteArray(), encoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return res;
}
}

File diff suppressed because it is too large Load Diff

57
src/springmvc-servlet.xml Normal file
View File

@@ -0,0 +1,57 @@
<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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
">
<context:annotation-config />
<!-- 扫描所有的 controller -->
<context:component-scan base-package="sc545.pay" />
<!-- 将静态资源交于默认的servlet处理 -->
<mvc:default-servlet-handler />
<!-- 启动注解驱动 SpringMVC 功能 -->
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" /> <!-- controller 返回的网页地址根目录 -->
<!-- <property name="suffix" value=".jsp" /> -->
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
<!-- 配置静态资源 -->
<mvc:resources location="/" mapping="/**/*.js" />
<mvc:resources location="/" mapping="/**/*.css" />
<mvc:resources location="/assets/" mapping="/assets/**/*" />
<mvc:resources location="/images/" mapping="/images/*"
cache-period="360000" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="sc545.pay.interceptor.testInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
</beans>