zoukankan      html  css  js  c++  java
  • 腾讯ISUX网页前端代码分析

    看了一下腾讯ISUX网页,无论是pc端还是移动端,展示都挺好看的,先对其代码进行分析如下:


    1,先看前三行代码

    <!DOCTYPE html>
    <!-- 腾讯 ISUX 是腾讯集团核心、全球最具规模的UX设计团队。我们正在招 UI开发、前端开发、客户端开发。快把简历发到 isux@qq.com 吧! -->
    <html lang="en-US" prefix="og: http://ogp.me/ns#">
    

    第一行,很正常,目前的网页都这么写的,H5的时代了;

    第二行,大公司总要用注释打写广告;

    第三行,lang语言居然是en-US,不解,应该没有什么特殊用意吧;prefix属性,百度了一下,用到了ogp协议,ogp主要是为社交媒体用的;

    2,head

    <head>
        <!-- 这是一个文档兼容模式的定义;Edge 模式告诉 IE 以最高级模式渲染文档,也就是任何 IE 版本都以当前版本所支持的最高级标准模式渲染,避免版本升级造成的影响。简单的说,就是什么版本 IE 就用什么版本的标准模式渲染-->
        <!-- 使用以下代码强制 IE 使用 Chrome Frame 渲染 <meta http-equiv="X-UA-Compatible" content="chrome=1">-->
        <!-- 最佳的兼容模式方案,结合考虑以上两种 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">-->
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <!-- 百度网站认证,可以删除">-->
        <meta name="baidu-site-verification" content="xEBBvSsVmz"/>
        <!-- 关于移动端网页展示的问题 超级详细的解释http://www.cnblogs.com/2050/p/3877280.html">-->
        <meta name="viewport"
              content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <!-- 这个是设置页面的编码格式 不要使用<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />了,已过时-->
        <meta charset="UTF-8"/>
        <title>腾讯ISUX - 社交用户体验设计</title>
        <!-- SEO关键词和描述 其实对google的搜索算法没什么用-->
        <meta name="keywords"
              content="ISUX,中国用户体验,腾讯设计,H5,动画,svg,webpack,vuejs,react,webComponents,react-native,人工智能,VR,AR,QQ,QQ空间,原创,创意,平面设计,UI,UI设计,网页设计,插画,动漫,摄影,字体设计,logo设计,版式设计,前端技术,视觉设计,用户研究,交互设计,品牌设计,UI开发,产品设计,市场研究,UX设计,腾讯社交用户体验设计部,Qlippie,QQfamily,PsPlay,Demoo"/>
        <meta name="description"
              content="腾讯社交用户体验设计,简称ISUX (Internet Social User Experience),成立于2011年1月11日,是腾讯集团核心、全球最具规模的UX设计团队,专业成员包括用户研究、交互设计、视觉设计、品牌设计、视频动画设计、UI开发、产品设计与市场研究等,至今ISUX分布于中国深圳总部、北京、上海、成都及韩国首尔。ISUX主要负责腾讯社交通讯与娱乐类产品服务的用户体验设计与研究,包括主要服务平台如QQ、QQ空间、QQ音乐、腾讯云、腾讯企点、QQ物联、腾讯课堂、兴趣部落、花样直播、全民K歌、全民影帝、企鹅FM、企鹅MV、天天P图、微云和来电等。"/>
        <!-- 使用社交媒体(Open Graph、Twitter Cards 和 Schema.org-->
        <!-- 与Open Graph相似的还有Twitter的Twitter cards(使用name="twitter:title"或者name="twitter:url")以及Google+使用的Schema.org(使用itemscope和itemprop)。-->
        <!-- Open Graph已变得非常受欢迎,所以大多数社交网络默认都是Open Graph。如果Open Graph 的meta标签也没有的话,他们设置缺少meta标签的默认值。-->
        <meta itemprop="name" content="腾讯ISUX - 社交用户体验设计"/>
        <meta itemprop="description" content="腾讯ISUX - 社交用户体验设计"/>
        <meta itemprop="image" content="https://qzonestyle.gtimg.cn/aoi/sola/20160624105951_m9z34gIMy2.jpg"/>
        <link rel="pingback" href="https://isux.tencent.com/xmlrpc.php"/>
        <!-- css -->
        <!-- <link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'> -->
        <link rel="stylesheet" type="text/css" media="all"
              href="https://isux.tencent.com/wp-content/themes/isux_v5/css/reset.css?v=1494217111"/>
        <link rel="stylesheet" href="https://isux.tencent.com/wp-content/themes/isux_v5/css/custom.css?v=1494217111"/>
        <!-- 关于IE的兼容以及版本处理 http://www.weste.net/2013/8-9/93104.html-->
        <!--[if lte IE 9]>
        <link rel="stylesheet" href="https://isux.tencent.com/wp-content/themes/isux_v5/css/lteie9.css"/> <![endif]-->
        <!-- wp head -->
        <!-- dns预读取 http://www.tuicool.com/articles/73iYRrv-->
        <link rel='dns-prefetch' href='//s.w.org'/>
        <!-- rss相关-->
        <link rel="alternate" type="application/rss+xml" title="腾讯ISUX - 社交用户体验设计 » Feed"
              href="https://isux.tencent.com/feed?variant=zh-hans"/>
        <link rel="alternate" type="application/rss+xml" title="腾讯ISUX - 社交用户体验设计 » Comments Feed"
              href="https://isux.tencent.com/comments/feed?variant=zh-hans"/>
        <!-- 代码高亮 google prettify-->
        <link rel='stylesheet' id='plugin_stylesheet-css'
              href='https://isux.tencent.com/wp-content/plugins/wp-googlecodeprettify/js/prettify.css?ver=4.7.3'
              type='text/css' media='all'/>
        <script type='text/javascript' src='https://isux.tencent.com/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
        <script type='text/javascript'
                src='https://isux.tencent.com/wp-content/plugins/wp-googlecodeprettify/js/run_prettify.js?ver=1.1'></script>
        <!-- wordpress相关 没用-->
        <link rel='https://api.w.org/' href='https://isux.tencent.com/wp-json/'/>
    
        <!-- WP Chinese Conversion Plugin Version 1.1.15 -->
        <script type="text/javascript">
            //<![CDATA[
            var wpcc_target_lang = "zh-hans";
            var wpcc_noconversion_url = "https://isux.tencent.com/";
            var wpcc_langs_urls = new Array();
            wpcc_langs_urls["zh-hans"] = "https://isux.tencent.com/?variant=zh-hans";
            wpcc_langs_urls["zh-hant"] = "https://isux.tencent.com/?variant=zh-hant";
            //]]>
        </script>
        <meta name="robots" content="noindex,follow"/>
        <!-- WordPress Facebook Open Graph protocol plugin (WPFBOGP v2.0.13) http://rynoweb.com/wordpress-plugins/ -->
        <meta property="fb:app_id" content="137155036704975"/>
        <meta property="og:url" content="https://isux.tencent.com"/>
        <meta property="og:title" content="腾讯ISUX - 社交用户体验设计"/>
        <meta property="og:site_name" content="腾讯ISUX - 社交用户体验设计"/>
        <meta property="og:description" content="Tencent Internet Social User Experience"/>
        <meta property="og:type" content="website"/>
        <meta property="og:image" content="http://qzonestyle.gtimg.cn/aoi/sola/20160718112032_m2l884XLHH.jpg"/>
        <meta property="og:locale" content="en_us"/>
        <!-- // end wpfbogp -->
        <!-- 通过给图片设置data-lazy-original属性,达到图片滚动到才加载展示的延迟效果,为了更好的按需加载图片-->
        <!-- data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==灰色效果-->
        <script type="text/javascript">(function (a, e) {
            function f() {
                var d = 0;
                if (e.body && e.body.offsetWidth) {
                    d = e.body.offsetHeight
                }
                if (e.compatMode == "CSS1Compat" && e.documentElement && e.documentElement.offsetWidth) {
                    d = e.documentElement.offsetHeight
                }
                if (a.innerWidth && a.innerHeight) {
                    d = a.innerHeight
                }
                return d
            }
            function b(g) {
                var d = ot = 0;
                if (g.offsetParent) {
                    do {
                        d += g.offsetLeft;
                        ot += g.offsetTop
                    } while (g = g.offsetParent)
                }
                return {left: d, top: ot}
            }
            function c() {
                var l = e.querySelectorAll("[data-lazy-original]");
                var j = a.pageYOffset || e.documentElement.scrollTop || e.body.scrollTop;
                var d = f();
                for (var k = 0; k < l.length; k++) {
                    var h = l[k];
                    var g = b(h).top;
                    if (g < (d + j)) {
                        h.src = h.getAttribute("data-lazy-original");
                        h.removeAttribute("data-lazy-original")
                    }
                }
            }
    
            if (a.addEventListener) {
                a.addEventListener("DOMContentLoaded", c, false);
                a.addEventListener("scroll", c, false)
            } else {
                a.attachEvent("onload", c);
                a.attachEvent("onscroll", c)
            }
        })(window, document);</script>
        <!-- 不解-->
        <style>
            html {
                margin-top: 0 !important;
            }
        </style>
        <!-- 不解-->
        <script> var global_cat_id = "" </script>
        <!-- 友盟统计 -->
        <script type="text/javascript">
            var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");
            document.write(unescape("%3Cspan id='cnzz_stat_icon_1260118664'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s95.cnzz.com/z_stat.php%3Fid%3D1260118664' type='text/javascript'%3E%3C/script%3E"));
        </script>
        <script>
            //声明_czc对象:
            var _czc = _czc || [];
            //绑定siteid,请用您的siteid替换下方"XXXXXXXX"部分
            _czc.push(["_setAccount", "1260118664"]);
        </script>
    
    </head>
    <!-- home blog zh-hans这三个class居然没有用到,只有当width<768时会增加一个class mscreen-->
    <body class="home blog zh-hans">
    

     3,为了处理移动端展示,最主要的是菜单的隐藏与展示,使用了很多媒体查询,主要是custom.css

    4,首页的ITEM如何在屏幕宽的时候展示4个,窄一点又展示三个,2个,1个,主要用到的就是#post-area .masonry-post和媒体查询

    .post-area-frame {
        margin: 40px auto 0;
        /*     1720px;*/
    }
    
    #post-area {
        width: 100%;
        overflow: hidden;
    }
    
    #post-area .masonry-post {
        position: relative;
        z-index: 2;
        overflow: hidden;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
        margin: 0 15px 30px;
        width: 100%;
        background: #fff;
        float: left;
        width:calc(25% - 30px);
        width:-webkit-calc(25% - 30px);
        -webkit-transition: all .3s ease;
        -moz-transition: all .3s ease;
        transition: all .3s ease;
    }
    
    #post-area .masonry-post .type-post {
        overflow: hidden;
    }
    
    #post-area .masonry-post .entry-subtitle {
        display: none;
    }
    
    #post-area .masonry-post:hover {
        -webkit-box-shadow: 0px 0px 15px #ccc;
        -moz-box-shadow: 0px 0px 15px #ccc;
        box-shadow: 0px 0px 15px #ccc;
    }
    
    #post-area .masonry-post .isux-image {
        overflow: hidden;
        /*height: 217px;*/
        background: #aaa;
    }
    
    #post-area .masonry-post .isux-image .open-single-frame {
        display: block;
        padding-top: 53%;
        position: relative;
    }
    
    #post-area .masonry-post .isux-image img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: block;
    }
    
    #post-area .masonry-post .isux-category,.latestone .post-cate {
        position: relative;
        float: right;
    }
    
    #post-area .masonry-post .isux-category {
        height: 40px;
        margin-bottom: -8px;
        margin-right: 12px;
    }
    
    #post-area .masonry-post .isux-category span,.latestone .post-cate span {
        float: left;
        overflow: hidden;
        margin: 0 3px;
        width: 38px;
        height: 38px;
        line-height: 38px;
        border: 1px solid #e6e6e6;
        -webkit-border-radius: 40px;
        border-radius: 40px;
        color: #ccc;
        text-align: center;
        font-size: 16px;
        font-weight: 100;
    }
    
    /*#post-area .masonry-post .isux-category span:hover {
        opacity: 0.7;
    }
    */
    #post-area .masonry-post .isux-category .navlist-sub:before {
        padding-right: 20px;
    }
    
    /*#post-area .masonry-post .isux-category .cate-vd,.latestone .post-cate .cate-vd:before {
        border-color: #ff4085;
        color: #ff4085;
    }*/
    
    #post-area .masonry-post .isux-category span:before,.latestone .post-cate span:before {
        display: block;
        width: 40px;
    }
    
    #post-area .masonry-post .isux-category .cate-vd:before,.latestone .post-cate .cate-vd:before {
        content: "D";
    }
    
    /*#post-area .masonry-post .isux-category .cate-id,.latestone .post-cate .cate-id {
        border-color: #ffa900;
        color: #ffa900;
    }*/
    
    #post-area .masonry-post .isux-category .cate-id:before,.latestone .post-cate .cate-id:before {
        content: "D";
    }
    
    /*#post-area .masonry-post .isux-category .cate-fd,.latestone .post-cate .cate-fd {
        border-color: #32b5d7;
        color: #32b5d7;
    }*/
    
    #post-area .masonry-post .isux-category .cate-fd:before,.latestone .post-cate .cate-fd:before {
        content: "E";
    }
    
    /*#post-area .masonry-post .isux-category .cate-ur,.latestone .post-cate .cate-ur {
        border-color: #9abc1c;
        color: #9abc1c;
    }*/
    
    #post-area .masonry-post .isux-category .cate-ur:before,.latestone .post-cate .cate-ur:before {
        content: "R";
    }
    
    /*#post-area .masonry-post .isux-category .cate-ux,.latestone .post-cate .cate-ux {
        border-color: #a866ae;
        color: #a866ae;
    }*/
    
    #post-area .masonry-post .isux-category .cate-ux:before,.latestone .post-cate .cate-ux:before{
        content: "T";
    }
    
    #post-area .masonry-post .isux-category:after {
        clear: both;
        display: table;
        height: 0;
        content: "";
        line-height: 0;
    }
    
    #post-area .masonry-post h2 {
        height: 50px;
        font-size: 30px;
        padding: 0 20px;
    }
    
    #post-area .masonry-post h2 a {
        display: inline-block;
        overflow: hidden;
        box-sizing: border-box;
        width: 100%;
        height: 50px;
        color: #000;
        vertical-align: top;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-weight: normal;
        font-size: 0.20rem;
        line-height: 50px;
    }
    
    #post-area .masonry-post h2 a:hover {
        color: #626262;
    }
    
    #post-area .masonry-post .info {
        position: relative;
        padding: 0 20px;
        /*height: 60px;*/
        overflow: hidden;
    }
    
    #post-area .masonry-post .author,#post-area .masonry-post .isux-date {
        height: 40px;
        line-height: 40px;
    }
    
    #post-area .masonry-post .author:after,#post-area .masonry-post .isux-date:after {
        clear: both;
        display: table;
        height: 0;
        content: "";
        line-height: 0;
    }
    
    #post-area .masonry-post .author {
        float: left;
        display: block;
        text-align: left;
    }
    
    #post-area .masonry-post .author img {
        float: left;
        width: 40px;
        height: 40px;
        border-radius: 20px;
    }
    
    #post-area .masonry-post .author .username {
        float: left;
        overflow: hidden;
        margin-left:10px;
        height: 40px;
        max-width: 87px;
        color: #737373;
        vertical-align: top;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 16px;
        line-height: 40px;
    }
    
    #post-area .masonry-post .isux-date {
        float: left;
        overflow: hidden;
        margin-left: 10px;
        color: #a3a3a3;
        text-align: left;
        white-space: nowrap;
        font-size: 14px;
    }
    
    #post-area .type_photo_double {
        width: 100%;
    }
    @media only screen and (max- 768px) {

    #post-area .masonry-post {
    calc(50% - 30px);
    -webkit-calc(50% - 30px);
    }


    #post-area .masonry-post .author img {
    28px;
    height: 28px;
    }

    #post-area .masonry-post .isux-category a,.latestone .post-cate a {
    margin:0 3px;
    }

    #post-area .masonry-post .author, #post-area .masonry-post .isux-date, #post-area .masonry-post .author .username {
    height: 28px;
    line-height: 28px;
    }
    }

    5,如何使用微信的JSSDK

      注册公众号,然后会有一个AppId和AppSceret

      前端代码如下:

      

    <!-- 使用微信JSSDK -->
        <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
        <script type="text/javascript">
            jQuery(function($){
                // 代码高亮配置
                $("pre").addClass("prettyprint linenums");
                // prettyPrint();
                // 检测wx分享配置数据
    //            alert("url="+encodeURIComponent(location.href.split('#')[0]));
                function wxShareData() {
                    $.ajax({
                        type: "GET",
                        url: "http://www.weichuanghome.com/wx/get.html",
                        dataType: "text",
                        data: "url="+encodeURIComponent(location.href.split('#')[0]),
                        success: function(data) {
    
                            var obj = JSON.parse(data);
    
    
    
                            wx.config({
                                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                                appId: obj.appId, // 必填,公众号的唯一标识
                                timestamp: obj.timestamp, // 必填,生成签名的时间戳
                                nonceStr: obj.nonceStr, // 必填,生成签名的随机串
                                signature: obj.signature,// 必填,签名,见附录1
                                jsApiList: [
                                    'onMenuShareTimeline',
                                    'onMenuShareAppMessage',
                                    'onMenuShareQQ',
                                    'onMenuShareQZone',
                                    'chooseImage',
                                ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
                            });
    
    
                            wx.ready(function(){
                                // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,
                                //所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,
                                //则可以直接调用,不需要放在ready函数中。
    
    
    //                            var config = {
    //                                title: '搞点新意思-QQiPad主题带你飞-腾讯ISUX', // 分享标题
    //                                desc:  '搞点新意思-QQiPad主题带你飞', // 分享描述
    //                                link: 'https://isux.tencent.com/do-something-different-rocking-with-new-qqipad-theme.html?variant=zh-hans', // 分享链接
    //                                imgUrl: 'https://isux.tencent.com/wp-content/uploads/2017/01/080018-42716-500x300.png', // 分享图标
    //                                success: function(){
    //                                    console.log('wx config success');
    //                                },
    //                                cancel: function(){
    //                                    console.log('wx config cancel');
    //                                }
    //                            };
    //                            wx.onMenuShareTimeline(config);
    //                            wx.onMenuShareAppMessage(config);
    //                            wx.onMenuShareQQ(config);
    //                            wx.onMenuShareQZone(config);
    
    //                            wx.chooseImage({
    //                                count: 1, // 默认9
    //                                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
    //                                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
    //                                success: function (res) {
    //                                    var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
    //                                }
    //                            });
                            });
    
                        },
                        error: function(jqXHR,textStatus,errorThrown) {
                            console.log(jqXHR)
                            console.log(textStatus)
                            console.log(errorThrown)
                        }
                    });
                }
    
                wxShareData();
    
            });
    
        </script>

    Java服务端代码如下:

    package com.yrcn.my.sys.common;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Date;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.google.gson.Gson;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    /**
     * Servlet implementation class WxServlet
     * 如果想使用JSSDK,必须获取微信认证的签名
     */
    //@WebServlet(name = "WxServlet1", urlPatterns = { "/WxServlet1" })
    public class WxServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public WxServlet() {
            super();
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String appId = "aaaaaaaaaaaa";
            //######1 获取access_token
            //AppID  
            //AppSecret 
            Object access_tokenObject = request.getServletContext().getAttribute("access_token");
            Object ticketObject = request.getServletContext().getAttribute("ticket");
            Object timestampObject = request.getServletContext().getAttribute("timestamp");
            String access_token = "";
            String ticket = "";
            if (access_tokenObject != null) {
                long timestamp = Long.parseLong(timestampObject.toString());
                boolean isExpires = new Date().getTime() - timestamp*1000 < 7000*1000;
                if(isExpires){
                    access_token = access_tokenObject.toString();
                    ticket = ticketObject.toString();
                }
            }        
            if ("".equals(access_token)) {
                String access_tokenResult = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&appid="+appId+"&secret=aaaaaaaaaaaaaaaaaaaaaa");
                //{"access_token":"Rd8SiZEaW2SRSZKFVxsh_ZS1adNwWP7zRAGG44HFA9lSNQbxOS-2hySxsJKKzUfEqkTJUsN9l_25po9qtoSJUCquad9C-KBh5vFLWdheL4omiICDMsTXBMIho271Cz-qMHAgADAVQJ","expires_in":7200}
    //            System.out.println(access_tokenResult);
                JsonParser jsonParser =new JsonParser();  //创建json解析器
                JsonObject jsonObject = (JsonObject)jsonParser.parse(access_tokenResult);
                access_token = jsonObject.get("access_token").getAsString();
                
                //######2 使用access_token获取jsapi_ticket
                //https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
                String jsapi_ticketResult = HttpRequest.sendGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket", "access_token="+access_token+"&type=jsapi");
                //{"errcode":0,"errmsg":"ok","ticket":"kgt8ON7yVITDhtdwci0qefyIxUzYwFqAaiwhEj1TfdJZcuWSLVXoVHUC7V0qEq-tgWJ0OtvFCU5pzpOHylkW-Q","expires_in":7200}
                System.out.println(jsapi_ticketResult);
                jsonObject = (JsonObject)jsonParser.parse(jsapi_ticketResult);
                ticket = jsonObject.get("ticket").getAsString();
                //
                request.getServletContext().setAttribute("access_token", access_token);
                request.getServletContext().setAttribute("ticket", ticket);
                request.getServletContext().setAttribute("timestamp", new Date().getTime());
            }
            //
            System.out.println("access_token="+access_token);
            System.out.println("ticket="+ticket);
            //######3 签名算法
            //签名生成规则如下:参与签名的字段包括noncestr(随机字符串), 有效的jsapi_ticket, timestamp(时间戳), url(当前网页的URL,不包含#及其后面部分) 。
            //对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1。
            //这里需要注意的是所有参数名均为小写字符。对string1作sha1加密,字段名和字段值都采用原始值,不进行URL 转义。
            String nonceStr = getRandomString(20);
            long timestamp = new Date().getTime()/1000;
            String urlStr = request.getParameter("url");
            if(urlStr == null){
                urlStr = "";
            }
            String url = URLDecoder.decode(urlStr.trim(), "UTF-8");
    //        String url = "http://www.weichuanghome.com/mobile.html";
            String string1 = "jsapi_ticket="+ticket+"&noncestr="+nonceStr+"&timestamp="+timestamp+"&url="+url;
            System.out.println(string1);
            String signature = getSha1(string1);
            //
    //        appId: obj.appId, // 必填,公众号的唯一标识
    //        timestamp: obj.timestamp, // 必填,生成签名的时间戳
    //        nonceStr: obj.nonceStr, // 必填,生成签名的随机串
    //        signature: obj.signature,// 必填,签名,见附录1
            RetObject retObject = new RetObject(appId, timestamp+"", nonceStr, signature);
            System.out.println(new Gson().toJson(retObject, RetObject.class));
            
            response.getWriter().append(new Gson().toJson(retObject, RetObject.class));
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
        private static int getRandom(int count) {
            return (int) Math.round(Math.random() * (count));
        }
         
        private static String string = "abcdefghijklmnopqrstuvwxyz";   
         
        private static String getRandomString(int length){
            StringBuffer sb = new StringBuffer();
            int len = string.length();
            for (int i = 0; i < length; i++) {
                sb.append(string.charAt(getRandom(len-1)));
            }
            return sb.toString();
        }
        
        public static String getSha1(String str){
            if (null == str || 0 == str.length()){
                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 (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return "";
        }
    }
    
    class RetObject{
        private String appId;
        private String timestamp;
        private String nonceStr;
        private String signature;
        
        public RetObject(String appId, String timestamp, String nonceStr, String signature) {
            super();
            this.appId = appId;
            this.timestamp = timestamp;
            this.nonceStr = nonceStr;
            this.signature = signature;
        }
        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 getSignature() {
            return signature;
        }
        public void setSignature(String signature) {
            this.signature = signature;
        }
    }

      

  • 相关阅读:
    vue项目学习--2019/5/6
    JAVA注释--2019-04-28
    MyIbatis和Hibernate的区别--2019-04-26
    Thread类和Runnable接口实现多线程--2019-4-18
    Linux文件的扩展名--2019-04-25
    Linux文件名匹配和输出重定向--2019-4-24
    linux学习之命令的排列、替换和别名--2019-04-23
    linux学习--2019-04-22
    操作系统中线程和进程的概念--2019-4-17
    arrayList和vector的区别--2019-4-16
  • 原文地址:https://www.cnblogs.com/yrcn/p/6831690.html
Copyright © 2011-2022 走看看