request,response ,cookies的常用几种方法

String fullContentType = "application/json;charset=UTF-8";
response.setContentType(fullContentType);//告知客户端响应正文类型  
response.setHeader("Cache-Control", "no-cache");//控制浏览器不要缓存 
 
 
//设置允许跨域
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials","true");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,token");
response.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
 

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8")//设置编码
 

Cookies

1.String name:该Cookie的名称。Cookie一旦创建,名称便不可更改。 Object value:该Cookie的值。如果值为Unicode字符,需要为字符编码。如果值为二进制数据,则需要使用BASE64编码。 

2.int maxAge:该Cookie失效的时间,单位秒。

如果为正数,则该Cookie在>maxAge秒之后失效。

如果为负数,该Cookie为临时Cookie,关闭浏览器即失效,浏览器也不会以任何形式保存该Cookie。

如果为0,表示删除该Cookie。默认为–1。

3.boolean secure:该Cookie是否仅被使用安全协议传输。安全协议。安全协议有HTTPS,SSL等,

在网络>上传输数据之前先将数据加密。默认为false。 

4.String path:该Cookie的使用路径。如果设置为“/sessionWeb/”,则

只有contextPath为“/sessionWeb”的程序可以访问该Cookie。如果设置为“/”

,则本域名下contextPath都可以访问该Cookie。注意最后一个字符必须为“/”

5.String domain:可以访问该Cookie的域名。如果设置为“.google.com”,则所有以“google.com”结尾的域名都可以访问该Cookie。注意第一个字符必须为“.”。 

6.String comment:该Cookie的用处说明。浏览器显示Cookie信息的时候显示该说明。 int version:该Cookie使用的版本号。0表示遵循Netscape的Cookie规范,1表示遵循W3C的RFC 2109规范。

 
/**
 * 得到Cookie的值,
 *
 * @param request 请求
 * @param cookieName cookie的名字
 * @return
 */
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
    Cookie[] cookieList = request.getCookies();
    if (cookieList == null || cookieName == null) {
        return null;
    }
    String retValue = null;
    try {
        for (int i = 0; i < cookieList.length; i++) {
            if (cookieList[i].getName().equals(cookieName)) {
                if (isDecoder) {
                    retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
                } else {
                    retValue = cookieList[i].getValue();
                }
                break;
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return retValue;
}
 
/**
 * 设置Cookie的值,并使其在指定时间内生效
 *
 * @param cookieMaxage cookie生效的最大秒数
 */
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response,
                                      String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
    try {
        if (cookieValue == null) {
            cookieValue = "";
        } else if (isEncode) {
            cookieValue = URLEncoder.encode(cookieValue, "utf-8");
        }
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxage > 0)
            cookie.setMaxAge(cookieMaxage);
        if (null != request) {// 设置域名的cookie
            String domainName = getDomainName(request);
            System.out.println(domainName);
            if (!"localhost".equals(domainName)) {
                cookie.setDomain(domainName);
            }
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
/**
 * 得到cookie的域名
 */
private static final String getDomainName(HttpServletRequest request) {
    String domainName = null;

    String serverName = request.getRequestURL().toString();
    if (serverName == null || serverName.equals("")) {
        domainName = "";
    } else {
        serverName = serverName.toLowerCase();
        serverName = serverName.substring(7);
        final int end = serverName.indexOf("/");
        serverName = serverName.substring(0, end);
        final String[] domains = serverName.split("\\.");
        int len = domains.length;
        if (len > 3) {
            // www.xxx.com.cn
            domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
        } else if (len <= 3 && len > 1) {
            // xxx.com or xxx.cn
            domainName = "." + domains[len - 2] + "." + domains[len - 1];
        } else {
            domainName = serverName;
        }
    }

    if (domainName != null && domainName.indexOf(":") > 0) {
        String[] ary = domainName.split("\\:");
        domainName = ary[0];
    }
    return domainName;
}

Cookie并不提供修改、删除操作。如果要修改某个Cookie,只需要新建一个同名的Cookie,添加到response中覆盖原来的Cookie。如果要删除某个Cookie,只需要新建一个同名的Cookie,并将maxAge设置为0,并添加到response中覆盖原来的Cookie。注意是0而不是负数。负数代表关闭浏览器,cookies即失效

注意:修改、删除Cookie时,新建的Cookie除value、maxAge之外的所有属性,例如name、path、domain等,都要与原Cookie完全一样。否则,浏览器将视为两个不同的Cookie不予覆盖,导致修改、删除失败。

 
 

HttpSession 怎么知道是同一个? java都封装好了
 
 //使用request对象的getSession()获取session,如果session不存在则创建一个
18         HttpSession session = request.getSession();

  //将数据存储到session中
20         session.setAttribute("data", "孤傲苍狼");
21         //获取session的Id
22         String sessionId = session.getId();
23         //判断session是不是新创建的
24         if (session.isNew()) {
25             response.getWriter().print("session创建成功,session的id是:"+sessionId);
26         }else {
27             response.getWriter().print("服务器已经存在该session了,session的id是:"+sessionId);
28         }

转自https://www.cnblogs.com/xdp-gacl/p/3855702.html 猜想封装好了的内容

1 //获取session的Id
2 String sessionId = session.getId();
3 //将session的Id存储到名字为JSESSIONID的cookie中
4 Cookie cookie = new Cookie("JSESSIONID", sessionId);
5 //设置cookie的有效路径
6 cookie.setPath(request.getContextPath());
7 response.addCookie(cookie);

 

session对象默认30分钟没有使用,则服务器会自动销毁session,在web.xml文件中可以手工配置session的失效时间

 

Tomcat中Session的默认超时时间为20分钟。通过setMaxInactiveInterval(int seconds)修改超时时间。可以修改web.xml改变Session的默认超时时间。例如修改为60分钟:

1
2
3
< session-config >
    < session-timeout >60</ session-timeout >      <!-- 单位:分钟 -->
</ session-config >

注意:参数的单位为分钟,而setMaxInactiveInterval(int s)单位为秒。

在server.xml中定义context时采用如下定义(单位为秒):

1
2
3
< Context  path="/livsorder" docBase="/home/httpd/html/livsorder" defaultSessionTimeOut="3600" isWARExpanded="true"
     isWARValidated="false" isInvokerEnabled="true"
     isWorkDirPersistent="false"/>


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值