重温httpsession①

Session—HTTPSession 服务器创建的,Javaweb提供的 与HTTP协议无关是服务器端对象,保存在服务器端。用来会话跟踪。

Cookie与服务器创建,与HTTP协议相关,保存在客户端上面。

SerVlet三大域对象

Request 多个 一次一个

Session 一个用户打开浏览器开始到关闭。一个用户一个Session

底层依赖于cookie 或是url重写。

服务器一方可以存放多个Session 放在一个map中

Servlet中得到Session对象 HTTPSession Session=request.getSession();

Jsp中得到Session对象:Session是jsp的内置对象,不用创建即可使用

Cookie底层不能跨浏览器。

<body>

保存Session. <br>

<%

    session.setAttribute("aaa", "AAA");

%>

</body>

<body>

获取Session. <br>

<% String s=(String)session.getAttribute("aaa"); %>

<%=s %>

</body>

第二个例子

action="<%=path%>/LoginServlet"

重定向时我们的servlet的路径不显示在地址栏中。

重定向是使用 response.sendRedirect("必须得些项目名");

可以是本项目以外的路径。两次请求,不存在request域

转发时会看到servlet的路径,不用加项目名,必须是本项目内的路径

request.setAttribute("message", "用户名或密码错误");

request.getRequestDispatcher("anli/error.jsp").forward(request, response);

存在request域。一次请求

保存cookie用response

拿到cookie使用request 注意判断是否为空

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        String username=request.getParameter("username");

        String password=request.getParameter("password");

        if (username.equals("124")&&password.equals("zhangsan")) {

            

            Cookie cookie=new Cookie("uname", username);

            cookie.setMaxAge(60*60);

            response.addCookie(cookie);

            

            HttpSession session=request.getSession();

            session.setAttribute("username", "124");

            session.setAttribute("password", "zhangsan");

            request.getRequestDispatcher("anli/success1.jsp").forward(request, response);

        }else {

            request.setAttribute("message", "用户名或密码错误");

            request.getRequestDispatcher("anli/login.jsp").forward(request, response);

        }

    }

<body>

This is my JSP page. <br>

<h1>登陆页面</h1>

<%

String uname="";

Cookie[]cookies=request.getCookies();

    if(cookies!=null){

     for(Cookie c:cookies){

    if("uname".equals(c.getName())){

        uname=c.getValue();

    }

}

    }

%>

<%

String message="";

String mes=(String)request.getAttribute("message");

if(mes!=null){

    message=mes;

}

%>

<font color="red"><b><%=message %></b></font>

<form action="<%=path%>/LoginServlet" method="pot">

<!-- 获取cookie中的uname的值放到用户名文本框中 -->

    用户名:<input type="text" name="username" value="<%= uname%>"><br>

    密码:<input type="password" name="password"><br>

    <input type="submit" value="提交">

</form>

</body>

Session的原理

Jssessionid

Jsp自动创建Session,servlet不自动创建

其他方法:getId()

Invalidate()

isNew()

原文地址:https://www.cnblogs.com/chengzhipcx/p/4994614.html