Servlet处理Cookie

1.CGI:进程,servlet:线程
2.HttpServletResponse下的方法就没有get开头的,(PrintWriter)getWriter在ServletResponse下。
3.str==null||str.length()=0(注意顺序),这样判断更健壮,可能初始化为空串。
4.<label> 标签为 input 元素定义标注(标记),label 元素不会向用户呈现任何特殊效果。不过,它为鼠标用户改进了可用性。如果您在 label 元素内点击文本,就会触发此控件。就是说,当用户选择该标签时,浏览器就会自动将焦点转到和标签相关的表单控件上。<label> 标签的 for 属性应当与相关元素的 id 属性相同。
注释:"for" 属性可把 label 绑定到另外一个元素。请把 "for" 属性的值设置为相关元素的 id 属性的值。

<html>
<body>
<p>请点击文本标记之一,就可以触发相关控件:</p>
<form>
<label for="male">Male</label>
<input type="radio" name="sex" id="male" />
<br />
<label for="female">Female</label>
<input type="radio" name="sex" id="female" />
</form>
</body>
</html>

5.做留言板时需要把里面的特殊字符替换掉,用String的replaceAll,处理<>' &,最后替换换行符" ",换成<br>,这个一定要放在大于小于号后面。

public static String filterHtml(String input) {
        if (input == null) {
            return null;
        }
        if (input.length() == 0) {
            return input;
        }
        input = input.replaceAll("&", "&amp;");
        input = input.replaceAll("<", "&lt;");
        input = input.replaceAll(">", "&gt;");
        input = input.replaceAll(" ", "&nbsp;");
        input = input.replaceAll("'", "&#39;");
        input = input.replaceAll(""", "&quot;");
        return input.replaceAll("
", "<br>");
    }

6.cookie:饼干,曲奇;http是无状态协议、断开式链接,所以残生了cookie,是文本文件,采用key-value存储。只能是英文或者数字。实现记住我功能,定制个性化页面。win7在C盘User目录下,使用setMaxAge设置有效期(秒),大小和数量有限制。因为cookie是铭文的,所以可能会泄露信息。注意cookies更改过后还需要再加载到服务器,因为
修改只是在本地硬盘。没有删除cookie的方法,设置有效期是0就行了。
7.最后访问时间

//在java.text,java.util已经过时
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Cookie cookie2 = new Cookie("lastTime", sdf.format(new Date()));
//cookie一个月,没必要再判断一个月 多少天
cookie2.setMaxAge(24 * 60 * 60 * 30);
//需要放回服务器
response.addCookie(cookie2);
            
            
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
for (int i = 0; i < cookies.length; i++) {
        cookie = cookies[i];
        if (cookie.getName().equals("username")) {
             out.println("用户名:" + cookie.getValue());
             out.println("<br>");
        }
        if (cookie.getName().equals("lastTime")) {
             out.println("最后访问时间:" + cookie.getValue());
             out.println("<br>");
        }
}
        
原文地址:https://www.cnblogs.com/hxsyl/p/3426960.html