Friday, October 16, 2015

Web Development Misc



https://stackoverflow.com/questions/1134290/cookies-on-localhost-with-explicit-domain
By design, domain names must have at least two dots; otherwise the browser will consider them invalid. (See reference on http://curl.haxx.se/rfc/cookie_spec.html)

When working on localhost, the cookie domain must be omitted entirely. Just setting it to "" or NULL or FALSE instead of "localhost" is not enough.
also check secure -> may need set it to false if its not https
https://wanago.io/2018/06/18/cookies-explaining-document-cookie-and-the-set-cookie-header/
Using document.cookie is not an only way to set a cookie. An HTTP request might respond with a Set-Cookie header. As a result, a cookie will be sent by the browser of the client.
In Node.js you can do it with the setHeader function:
It is a convenient way to, for example, handle authentication tokens. This is due to the fact, that you can set additional directives, which can make it all more secure.
This communication goes both ways: the browser will send your cookies with the requests that you make. It means, that if you would like that data to stay in the browser, it might be better to use Web Storage API.

https://stackoverflow.com/questions/9821919/delete-cookie-from-a-servlet-response
Setting the maximum age to 0 is right. But it must have exactly the same other cookie properties, except of the value. Thus exactly the same domain, path, secure, etc. The value is optional, it can best be set to null.
So, given the way how you created the cookie,
Cookie cookie = new Cookie("user", user);
cookie.setPath("/MyApplication");
cookie.setHttpOnly(true);
cookie.setMaxAge(3600);
response.addCookie(cookie);
it needs to be removed as follows:
Cookie cookie = new Cookie("user", null); // Not necessary, but saves bandwidth.
cookie.setPath("/MyApplication");
cookie.setHttpOnly(true);
cookie.setMaxAge(0); // Don't set to -1 or it will become a session cookie!
response.addCookie(cookie);
That said, I'm not sure how it's useful to store the logged-in user as a cookie. You're basically also allowing the enduser to manipulate its value. Rather just store it as a session attribute instead and call session.invalidate() on logout.
https://www.cnblogs.com/13yan/p/3471077.html
简单说就是一个会话级的cookie,外加服务器端内存中一组散列表。
当你关闭浏览器的时候,这个cookie将消失。
这个cookie不写在磁盘上,而是存在于浏览器缓存。

关于Session的传说
传说中,Web应用程序中的Session和Application保存服务器端,而cookie保存在客户端。
其实Session同时存在于客户端与服务器端。
开发中如果你已经写了一个Session,打开火狐浏览器,清理cookie的时候你会找到一个session_id(java开发者会看到JSESSIONID)的cookie,删除他后Session将失效。
如果你打开的是IE浏览器,清理cookie后Session依然存在,我不知道IE是怎么处理的,也许它只从磁盘里去清理。

Session实现原理
1、创建Session的时候,服务器将生成一个唯一的sessionid然后用它生成一个关闭浏览器就会失效的cookie。
2、然后再将一个与这个sessionid关联的数据项加入散列表。
    例如这样一段代码:Session["UserName"]=23;
    假设sessionid为123那么散列表中会追加一行
     sessionid          username
     123                  23
3、当浏览器端提交到服务器时,会通过sessionid=123去散列表中寻找属于该用户的Session信息。

why url random number
http://stackoverflow.com/questions/1744051/why-do-so-many-javascript-scripts-append-random-numbers-to-things-collision
What problem does this solve? An example parameter from the Readability bookmarklet:
_readability_script.src='http://lab.arc90.com/....script.js?x='+(Math.random());

 it's typically a trick employed to prevent caching. Browsers typically cache JavaScript and CSS very aggressively, which can save you bandwidth, but can also cause deployment problems when changing your scripts.

The idea is that browsers will consider the resource located at http://www.example.com/something.js?foo different from http://www.example.com/something.js?bar, and so won't use their local cache to retrieve the resource.

Probably a more common pattern is to append an incrementing value which can be altered whenever the resource needs to change. In this way, you benefit by having repeat requests served by the client-side cache, but when deploying a new version, you can force the browser to fetch the new version.

Personally, I like to append the last-modified time of the file as as a Unix timestamp, so I don't have to go hunting around and bumping version numbers whenever I change the file.
This is because Internet Explorer likes to cache everything, including requests issued via JavaScript code.
Another way to do this, without random numbers in the URL, is to add Cache-Control headers to the directories with the items you don't want cached:
# .htaccess
Header set Cache-Control "no-cache"
Header set Pragma "no-cache"
Most browsers respect Cache-Control but IE (including 7, haven't tested 8) only acknowledge the Pragma header.

http://gaolixu.iteye.com/blog/311033
      大家在系统开发中都可能会在js中用到ajax或者dwr,因为IE的缓存,使得我们在填入相同的值的时候总是使用IE缓存,为了解决这个问题一般可以用一下方法:
       1:在ajax或者dwr提交的url后面加时间戳。
       例如
    http_request.onreadystatechange = funcName(函数名);
    http_request.open("GET", url, true);
    比如url是test .jsp
    那么我们在它后面加上?time=new Date();
    即url=test.jsp?time=new Date();
       2 :在url后面加一个随机数。
     。。。。。。。。。
     url=test.jsp?number=Math.random();


只要js认为链接不一样就会再次取新的内容。
时间戳应该是比随机数更随机的数,保证了每次不一样。 <script type="text/javascript"></script>






http://reeoo.me/archives/strictmode.html

为整个脚本启用严格模式

在所有语句之前放一个特定语句 "use strict";
要给某个函数开启严格模式,得把"use strict"; 声明放在函数体所有语句之前就行了。
function strictFun()
{
  // 函数级别严格模式语法
  'use strict';
  console.log('I am a strictmode function!');
}
JavaScript作为一门一开始用于浏览器的脚本语言,容错性非常好,即使有时候你的代码写的不标准,也不会报错,但这有时候会变成代码隐患。开启了严格模式之后,JavaScript的一些不合理的不严谨的语法都会得到控制,让你能够更严谨的书写JavaScript代码,成为一个更好的程序员。严格模式是ES5时代的产物,ES2015已经在普及的路上,是时候使用严格模式了!


http://stackoverflow.com/questions/24369328/how-to-use-strict-mode-in-chrome-javascript-console
The easiest way to use strict mode is to use an IIFE (immediately Invoked Function Expression) like so:
(function()
{
    'use strict';
    var foo = 123;//works fine
    bar = 345;//ReferenceError: bar is not defined
}());
To create a new-line in the console, use shift + enter, or write your code in a separate editor first, then copy-paste it to the console. Setting up a fiddle is all fine and dandy, but just test your code with the markup it was written for (ie: just clear the browser cache and test).
However, I'd urge you to install node.js, still. It's a lot easier to test your code, or validate it (both syntactically and coding-style wise) using JSHint. There are also a lot of ways to examine and your code that run out of node.js, so it's a really good development tool to have


怎样防止F5重复提交表单?
首先我们在进入目标页面的时候在session内用uuid生成一个token标志并且将其保存在页面的一个hidden input域

然后我们提交表单的时候,后台可以接收这个input值,并且取出session中的token值,比较,如果session的token存在并且与hidden域的相等,那么执行操作,并且在操作完成后删除session该属性。

这样我们再重复提交的时候这个时候虽然input域传值过来,但是session已经没了这个属性,所以我们可以判断什么都不做。

    public String preventFormCommit(String orderName,String judgeDuplicate,HttpSession session){
        String token = (String)session.getAttribute("token");
        if(StringUtils.isNotBlank(token) && token.equals(judgeDuplicate)) {
            System.out.println("收到订单:" + orderName + "这里将进行数据库运算");
            //操作完成后删除session中的对象
            session.removeAttribute("token");
        }
        return null;
    }
    @RequestMapping(value = "/demoindex")
    public String gotoDemo(HttpSession session){
        UUID uuid = UUID.randomUUID();
        session.setAttribute("token",uuid.toString());
        return "demo";
    }
    <form method="post" action="/demo">
        <input type="text" name="orderName"/>
        <input type="submit"/>
        <input type="hidden" name="judgeDuplicate" value="${token!""}"/>
    </form>

为什么需要设置一个隐藏域?

这个问题我一开始没想明白,我认为,进入页面的时候设置一个session并且再token设值,添加的时候把这个值删掉。然后这样我们再按F5的时候就没办法重复提交了(因为这个时候判断session为空)。我觉得这样就ok了,设置hidden域感觉没任何必要。
然而简直是图样图森破,对于一般用户这样当然是可以的。但是对于而已用户呢?加入恶意用户开两个浏览器窗口(同一浏览器的窗口公用一个session)这样窗口1提交完,系统删掉session,窗口1停留着,他打开第二个窗口进入这个页面,系统又为他们添加了一个session,这个时候窗口1按下F5,那么直接重复提交!
所以,我们必须得用hidden隐藏一个uuid的token,并且在后台比较它是否与session中的值一致,只有这样才能保证F5是不可能被重复提交的!

http://blog.600km.xyz/2015/12/21/html-auto-submit/
业务场景为一个type=text的表单元素,通过ajax进行搜索。但是遇到一个bug,就是在输入之后按回车,就会自动提交表单。查找之后发现了浏览器的表单提交特性
如果只有一个text表单元素,回车会自动提交表单!!
为了避免这种bug,将表单回车后提交的场景都测试了一遍。

场景一:只有一个type=text表单元素

<form action="http://blog.600km.xyz">
    <input type="text" name="username" />
</form>
在此场景下,只要在input中按下回车键,就会自动提交表单。
为了避免自动提交,可以设置一个隐藏的text元素,如
<form action="http://blog.600km.xyz">
    <input type="text" style="display:none" />
    <input type="text" name="username" />
</form>

场景二:有n个type=text和一个type=submit表单元素

<form action="http://blog.600km.xyz">
    <input type="text" name="username" />
    <input type="text" name="password" />
    <input type="submit" value="Submit!" />
</form>
在此场景下,只要在input中按下回车键,就会自动提交表单。
为了避免自动提交,网上常见的例子是在form表单中监听onkeydown事件,如果是回车输入,则返回false,阻止表单提交。
<form action="http://blog.600km.xyz" onkeydown="if(event.keyCode==13){return false;}">
    <input type="text" name="username" />
    <input type="text" name="password" />
    <input type="submit" value="Submit!" />
</form>
但是这种写法存在1个问题:如果是textarea,可能会需要回车操作。
为了解决上述问题,需要增加针对textarea的判断条件,而且还要注意兼容ie。
<script type="text/javascript">
document.onkeydown = function(event) {
    event = event || window.event;
    var param = event.target || event.srcElement;
    // if (param.name=="username"){return true;}
    if (event.keyCode == 13) {
        if ("INPUT" == param.tagName) {
            return false;
        }
    }
};
</script>
<form action="http://blog.600km.xyz">
    <input type="text" name="username" />
    <input type="text" name="password" />
    <textarea name="introduction"></textarea>
    <input type="submit" value="Submit!" />
</form>
根据if (param.name==”username”){return true;}就可以自定义在某个表单元素中,点击回车键,就可以提交表单。

场景三:有n个type=text,没有type=submit元素

此时点击回车键时,表单不会提交。可以通过监听onkeydown事件,利用submit()方法,根据keyCode和tagName或者表单元素的name来自定义提交规则
<script type="text/javascript">
document.onkeydown = function(event) {
    event = event || window.event;
    var param = event.target || event.srcElement;
    if (event.keyCode == 13 && param.name=="password"){
        document.getElementById("entityForm").submit();
    }
};
</script>
<form action="http://blog.600km.xyz" id="entityForm">
    <input type="text" name="username" />
    <input type="text" name="password" />
    <textarea name="introduction"></textarea>
</form>

场景四:有n个type=text和一个button标签元素

button标签,如果未指定type,则在ie6和ie7下为type=”button”, 在ie8及chrome和火狐下为type=”submit”,为了避免这种混乱,button标签一定要指定type。
如果指定为type=”button”,则和场景三的处理方式一致,
如果是type=”submit”,则同场景二。
http://www.cnblogs.com/yxy99/p/5243451.html
简述三种异步上传文件方式
  9     <div>
 10         <p id="upfile">附件: <input type="file" id="myfile" style="display: inline"></p>
 11         <p id="upbtn">
 12             <input style="padding-left:50px;padding-right: 50px;" type="button" value="异步上传" onclick="upload();">
 13             <span id="uptxt" style="display: none">正在上传...</span>
 14             <span id="upprog"></span>
 15             <button id="stopbtn" style="display:none;">停止上传</button>
 16         </p>
 17     </div>
 18 
 19     <div id="flist" style="border:1px dotted darkgray;"></div>
 20 
 21 <script>
 22     function upload() {
 23         // 1.准备FormData
 24         var fd = new FormData();
 25         fd.append("myfile", $("#myfile")[0].files[0]);
 26 
 27         // 创建xhr对象
 28         var xhr = new XMLHttpRequest();
 29 
 30 
 31         // 监听状态,实时响应
 32         // xhr 和 xhr.upload 都有progress事件,xhr.progress是下载进度,xhr.upload.progress是上传进度
 33         xhr.upload.onprogress = function(event) {
 34             if (event.lengthComputable) {
 35                 var percent = Math.round(event.loaded * 100 / event.total);
 36                 console.log('%d%', percent);
 37                 $("#upprog").text(percent);
 38             }
 39         };
 40 
 41         // 传输开始事件
 42         xhr.onloadstart = function(event) {
 43             console.log('load start');
 44             $("#upprog").text('开始上传');
 45 
 46             $("#stopbtn").one('click', function() {
 47                xhr.abort();
 48                 $(this).hide();
 49             });
 50 
 51             loading(true);
 52         };
 53 
 54         // ajax过程成功完成事件
 55         xhr.onload = function(event) {
 56             console.log('load success');
 57             $("#upprog").text('上传成功');
 58 
 59             console.log(xhr.responseText);
 60             var ret = JSON.parse(xhr.responseText);
 61             addToFlist(ret.fname);
 62         };
 63 
 64         // ajax过程发生错误事件
 65         xhr.onerror = function(event) {
 66             console.log('error');
 67             $("#upprog").text('发生错误');
 68         };
 69 
 70         // ajax被取消
 71         xhr.onabort = function(event) {
 72             console.log('abort');
 73             $("#upprog").text('操作被取消');
 74         };
 75 
 76         // loadend传输结束,不管成功失败都会被触发
 77         xhr.onloadend = function (event) {
 78             console.log('load end');
 79             loading(false);
 80         };
 81 
 82         // 发起ajax请求传送数据
 83         xhr.open('POST', '/upload3', true);
 84         xhr.send(fd);
 85     }
 86 
 87     
 88     function addToFlist(fname) {
 89         var temp = ["<p id='" + fname + "'>",
 90                     fname,
 91             "<button onclick='delFile(\"" + fname + "\");'>删除</button>",
 92                     "</p>"
 93                     ];
 94         $("#flist").append(temp.join(""));
 95     }
 96 
 97     function delFile(fname) {
 98         console.log('to delete file: ' + fname);
 99         // TODO: 请实现
100     }
101 
102     function loading(showloading) {
103         if (showloading) {
104             $("#uptxt").show();
105             $("#stopbtn").show();
106         } else {
107             $("#uptxt").hide();
108             $("#stopbtn").hide();
109         }
110     }
111 </script>

https://apple.stackexchange.com/questions/278067/open-terminal-via-safari
There are three URL types which can open Terminal from Safari:
  1. ssh
  2. telnet
  3. x-man-page
Those informations can be found under CFBundleURLTypes key in: /Applications/Utilities/Terminal.app/Contents/Info.plist
So in order to open Terminal app, you can place link like:
<a href="telnet://">telnet</a>
<a href="ssh://">ssh</a>
<a href="x-man-page://">man page</a>
It does not prefill informations in Terminal for me.


Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts