session应用:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" session="true"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>登录</title>
  </head>
  
  <body>
        sessionID<%=session.getId() %>
        
        <%
            Object username=session.getAttribute("username");
            if(username==null){
                username="";
            }
         %>
        <form action="hello.jsp" method="post">
            username:<input type="text" name="username" 
            value="<%= username %>"/>
            
                <input type="submit" value="Submit"/>
        </form>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" session="true"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>HELLO SESSION</title>
  </head>
  
  <body>
        sessionID<%=session.getId() %>
        <%=request.getParameter("username") %>
        <%
            session.setAttribute("username", request.getParameter("username"));
         %>
    <a href="<%= response.encodeURL("login.jsp") %>">重新登录</a>    
    &nbsp;&nbsp;&nbsp;&nbsp;
    <a href="<%= response.encodeURL("zhuxiao.jsp") %>">注销</a>
  </body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" session="true"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>注销</title>
  </head>
  
  <body>
  sessionId:<%=session.getId() %>
        <h3>Session</h3>
        Bye: <%= session.getAttribute("username") %>
    <%
        session.invalidate();
        
     %>
  </body>
</html>

 在servlet中:存入到session中  :session.setAttribute("username", request.getParameter("username"));

        在页面中取值:session.getAttribute("username")

 

当浏览器禁用了cookie后,就可以用URL重写这种解决方案解决Session数据共享问题。而且response. encodeRedirectURL(java.lang.String url) 和response. encodeURL(java.lang.String url)是两个非常智能的方法,当检测到浏览器没有禁用cookie时,那么就不进行URL重写了。

posted @ 2017-04-06 20:56  陆伟  阅读(225)  评论(0编辑  收藏  举报