码迷,mamicode.com
首页 > 其他好文 > 详细

Session

时间:2017-08-21 09:50:29      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:date   dispatch   cti   body   个人信息   session   存在   head   定向   

servlet代码

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class Aservlet extends HttpServlet {

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //从request中获取参数
        String s1 = request.getParameter("username");
        String s2 = request.getParameter("password");
        
        //功能逻辑处理用户名正确或者错误时,需要响应的页面以及信息;
        if(!s1.equals("wangyinxu")){
            //用户名正确时,保存用户名到Cookie中,用于显示到登录页面的username的value值中
            Cookie cookie = new Cookie("uname",s1);//创建cookie
            cookie.setMaxAge(60*60*24);//设置cookie时间
            response.addCookie(cookie);//添加cookie
            
            //保存参数到session域中
            HttpSession session = request.getSession();
            session.setAttribute("username", s1);
            response.sendRedirect("/day_11_3/HttpSession/succes1.jsp");//重定向到succes1.jsp
        }else{
            request.setAttribute("error", "用户名或者密码错误");
            request.getRequestDispatcher("/HttpSession/login.jsp").forward(request, response);//请求转发
        }
    }

}

jsp代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘login.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
  <%
  String msg ="";
  String error = (String)request.getAttribute("error");
  if(error!=null){
      msg=error;
  }
  %>
  <%=msg %>
  <% 
    String name = "";
      Cookie[]uname = request.getCookies();
      if(uname!=null){
          for(Cookie cookie : uname){
              if(cookie.getName().equals("uname")){
                  name = cookie.getValue();
              }
          }
      }
  %>
    <form action="/day_11_3/Aservlet" method="post">
        <table bgcolor="#aacc00">
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username" value="<%=name%>"/> </td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password" /> </td>
            </tr>
            <tr >
                <td colspan="2"><input type="submit"  value="提交" /> </td>
            </tr>
        </table>
          
    </form>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘succes1.jsp‘ starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <%
      String username = (String)session.getAttribute("username");
    if(username==null){
        response.sendRedirect("/day_11_3/HttpSession/login.jsp");
        return;
    }
    %>
    <div>
        <font color="#ccaa00">玩家:<%=username %>已登录</font>
    </div>
    <div>
        <a href="/day_11_3/HttpSession/succes2.jsp">个人信息</a>
    </div>
  </body>
</html>

***HttpSession的其他方法:
String  getId();获取sessionid
int getMaxInactiveInterval() 获取session可以的最大不活动时间(秒),默认30分钟,当session在30分钟内没有使用,那么就会从session池中移除
void  invalidate():让session失效,使用这个方法会让session失效,当session失效再次访问服务器会创建一个session,并在响应中把jsessionid保存到Cookie中;
boolean  isNew(): 查看session是为新。当客户端第一次求情时,服务器为客户端创建session,但这是服务器还没有响应客户端,也就是没有把sessisonid保存在cookie中响应给客户端;
***web.xml中配置session的最大不活动时间:
<session-config>
    <session=timeout>30</session-timeout>
</session-config>
***HttpSession原理:
在用户访问服务器的时候,服务器不会马上给你创建session,当你第一次获取session时,才会给你创建,也就是当你第一次调用request.getSession()方法时,服务器会创建session;
服务器获取sessionID的途径有两种:
1、通过Cookie头传递JSESSIONID
2、通过参数传递JSESSIONID 例:<a href="/day_11_1/login.jsp;JSESSIONID=‘<%=session.getId()%>‘">百度 </a>
*request.getSession();方法获取session
  如果session不存在,创建session把session保存起来,把新创建的JsessionID保存到Cookie中
  如果session存在,通过sessionid查找session对象,如果没有查找到,创建session,把session保存起来,把新创建的sessionid保存到cookie中
  如果session存在,通过sessionid查找session对象,如果找到,不创建session
  首先session的生命周期是一个会话,只要不关闭浏览器,sessionid就不会丢失,session在服务器默认保存时间是30分钟,如果30分钟内没动session就会自动消失;当你关闭服务器时,丢失的是jsessionid;没有sessionid就找不到原来的session;
  JSP中自定义了session域所以访问jsp就一定会创建session
  request.getSession(false) 如果session缓存中(Cookie不存在),不存在session,那么放回null,不会创建session对象。
  request.getSession(true)  这个方法肯定会创建session
  request.getSession()   这个方法肯定会返回session
***URL重写: (测试点,禁用浏览器cookie,看看是否可以正常使用session)
session依赖cookei,目的是让客户端发出请求时,归还jsessionid;
如果客户端禁用cookie,那么就无法得到sessionid,session就无用了;
response.encodeURL("/day_11_3/HttpSession/login.jsp"); 该方法会对url进行智能重写,当请求中没有归还sessionid这个cookie,那么该方法会重写url,否则不会重写,当然url必须是指向本站的url。
就是把所有的页面中的路径,都用response.encodeURL(String url);处理!

总结:
客户端访问服务器,服务器会给客户端一个sessionid,保存在cookie中,但是客户端禁用cookie,所以再次访问这个页面或者上面的超链接sessionid就不会被带去服务器,
那么session就没用了,为了解决这个问题,所以我们需要用url重写来解决;就是把这个网站所有的url路径后面都加上jsessionid;而这个便捷方法就是response.encodeURL(String url);

 

Session

标签:date   dispatch   cti   body   个人信息   session   存在   head   定向   

原文地址:http://www.cnblogs.com/wangyinxu/p/7402299.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!