参照上篇文章先用idea创建好springMVC环境,配置好dispatcher-servlet.xml
<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--此文件负责整个mvc中的配置-->
<!--启用spring的一些annotation -->
<context:annotation-config/>
<!-- 配置注解驱动 可以将request参数与绑定到controller参数上 -->
<mvc:annotation-driven/>
<!--静态资源映射-->
<!--本项目把静态资源放在了webapp的statics目录下,资源映射如下-->
<mvc:resources mapping="/css/**" location="/statics/css/"/>
<mvc:resources mapping="/js/**" location="/statics/js/"/>
<mvc:resources mapping="/image/**" location="/statics/images/"/>
<mvc:default-servlet-handler /> <!--这句要加上,要不然可能会访问不到静态资源,具体作用自行百度-->
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP-->
<!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
<bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/views/"/><!--设置JSP文件的目录位置-->
<property name="suffix" value=".jsp"/>
<property name="exposeContextBeansAsAttributes" value="true"/>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="-1"/>
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="false"/>
<!-- 临时目录 -->
<property name="uploadTempDir" value="/statics/documentdir"/>
<!--<property name="maxInMemorySize" value="104857600"/>-->
</bean>
<!-- 自动扫描装配 -->
<context:component-scan base-package="com.bmf"/>
</beans>
和applicationContext.xml
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.bmf"/>
</beans>
jar包配置:
还要配置好公众号信息:
按照要求设置好域名:
开始撰写jsp文件:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>微信扫一扫</title>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/weixin.js"></script>
</head>
<body>
<input id="timestamp" type="hidden" value="${timestamp}" />
<input id="noncestr" type="hidden" value="${nonceStr}" />
<input id="signature" type="hidden" value="${signature}" />
<input id="id_securityCode_input">
<button id="scanQRCode" onclick="getWeixinResult()">扫码</button>
</body>
<script type="text/javascript">
</script>
</html>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
public class HttpRequestUtil {
/**
* 发起http请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
InputStream inputStream=null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//将返回的输入流转换成字符串
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
System.out.println("Weixin server connection timed out");
} catch (Exception e) {
e.printStackTrace();
System.out.println("http request error:{}");
}finally{
try {
if(inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonObject;
}
}
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import net.sf.json.JSONObject;
public class WxJSUtil {
public static void main(String[] args) {
JSONObject json1=getTokenTool("自己的APPID", "你的公众号的开发者密码(AppSecret)");
String access_token=json1.getString("access_token");
System.out.println(json1.toString());
JSONObject json2=getTicketTool(access_token);
String ticket=json2.getString("ticket");
System.out.println(json2.toString());
System.out.println("access_token:"+access_token);
System.out.println("ticket:"+ticket);
};
public static Map<String, String> sign(String url) {
String appId="同上";
String appSecret="同上";
String access_token=getTokenTool(appId, appSecret).getString("access_token");
JSONObject ticketJson=getTicketTool(access_token);
System.out.println(ticketJson.toString());
String jsapi_ticket = ticketJson.getString("ticket");
Map<String, String> ret = new HashMap<String, String>();
//这里的jsapi_ticket是获取的jsapi_ticket。
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
System.out.println("crypt="+crypt.toString());
System.out.println("string1="+string1);
System.out.println("signature="+signature);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
ret.put("url", url);
ret.put("jsapi_ticket", jsapi_ticket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
return ret;
}
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
public static JSONObject getTicketTool(String access_token){
String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
// System.out.println(HttpRequestUtil.httpRequest(url, "GET", ""));
return HttpRequestUtil.httpRequest(url, "GET", "");
}
public static JSONObject getTokenTool(String appId,String appSecret){
String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;
// System.out.println(HttpRequestUtil.httpRequest(url, "GET", ""));
return HttpRequestUtil.httpRequest(url, "GET", "");
}
}
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.bmf.WxJSUtil;
import net.sf.json.JSONObject;
@Controller
@SuppressWarnings("serial")
public class WeixinAction{
/**
* 获取签名算法
*/
@RequestMapping("getSign")
@ResponseBody
public JSONObject getSign(){
JSONObject jsonObject=new JSONObject();
String url="http://你域名/index.jsp";
Map<String, String> ret =WxJSUtil.sign(url);
System.out.println("map="+ret.toString());
jsonObject.put("weixin", ret);
System.out.println("json="+jsonObject.toString());
return jsonObject;
}
}
微信JS-SDK验证参照官方给的demo
提供demo下载:点击下载
备注暂时只能使用微信自带浏览器打开使用
后续更新前端分页展示MySQL数据,以及前端点击下载下载从数据库读取出的数据保存到本地成excle格式。。。。。。