javaWeb知識學習——session的理解使用

知識點彙總

1.session機制採用的是在服務器端保持HTTP狀態信息的方案。
2.session通過SessionID來區分不同的客戶,session是以cookie或URL重寫爲基礎的
默認使用cookie來實現,系統會創造一個名爲JSESSIONID的輸出cookie,session
cookie是存儲到瀏覽器內存中的並不是寫到硬盤上。
3.HttpSession的生命週期
page指令的session=’false‘當前頁面禁用session隱含變量,但可以使用顯示的HttpSession對象
銷燬HttpSession對象:①直接調用HttpSession的invalidate()方法使得HTTP Session失效
②服務器卸載當前的WEB應用
③超過HttpSession的過期時間
4.設置過期時間:①秒爲單位setMaxInactiveInterval()②在web.xml文件中設置
HttpSession的過期時間單位分鐘<session-config><session-timeout>10</session-timeout></session-config>
5.利用URL重寫實現Session的跟蹤,Servlet中一種補充的會話管理機制,它允許不支持
Cookie的瀏覽器中也可以與WEB服務器保持連續的會話。將會話標識號以參數形式
附加在超鏈接的URL地址後面的技術稱爲URL重寫
HttpServletResponse接口中定義了兩個用於完成URL重寫方法:encodeURL方法,encodeRedirectURL方法。

一:使用舉例

1.創建login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
SessionId: <%=session.getId()%><br>
IsNew:<%=session.isNew()%><br>
MaxInactiveInterval:<%=session.getMaxInactiveInterval()%><br>
CreateTime:<%=session.getCreationTime()%><br>
LastAccessTime:<%=session.getLastAccessedTime()%><br>

<%
    Object username=session.getAttribute("username");
    if(username==null){
        username="";
    }
%>
<form action="hello.jsp" method="post">
    <%--<form action="<%=response.encodeURL(hello.jsp)%>" method="post">  在禁用cookie的情況下使用--%>
    username:<input type="text" name="username" value="<%=username%>"/>
    <input type="submit" value="submit"/>
</form>
</body>
</html>

2.創建hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
SessionId: <%=session.getId()%><br>
IsNew:<%=session.isNew()%><br>
MaxInactiveInterval:<%=session.getMaxInactiveInterval()%><br>
CreateTime:<%=session.getCreationTime()%><br>
LastAccessTime:<%=session.getLastAccessedTime()%><br>

<%
    session.setAttribute("username",request.getParameter("username"));
%>
<a href="login.jsp">重新登錄</a>
<br>
<a href="logOff.jsp">註銷</a>
</form>
</body>
</html>

3.創建logOff.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
SessionId: <%=session.getId()%><br>
IsNew:<%=session.isNew()%><br>
MaxInactiveInterval:<%=session.getMaxInactiveInterval()%><br>
CreateTime:<%=session.getCreationTime()%><br>
LastAccessTime:<%=session.getLastAccessedTime()%><br>

Bye:<%=session.getAttribute("username")%>
<%session.invalidate();%>
<a href="login.jsp">重新登錄</a>
</body>
</html>

二.實現簡易購物車功能

1.創建step1.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>step1</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/processStep1" method="post">
    <table border="1"cellpadding="10"cellspacing="0">
        <tr>
            <td>書名</td>
            <td>購買</td>
        </tr>
        <tr>
            <td>java</td>
            <td><input type="checkbox"name="book" value="java"/></td>
        </tr><tr>
            <td>javaWeb</td>
            <td><input type="checkbox"name="book" value="javaWeb"/></td>
        </tr><tr>
            <td>Python</td>
            <td><input type="checkbox"name="book" value="Python"/></td>
        </tr><tr>
            <td>C#</td>
            <td><input type="checkbox"name="book" value="C#"/></td>
        </tr><tr>
            <td>C</td>
            <td><input type="checkbox"name="book" value="C"/></td>
        </tr>
<tr>
    <td><input type="submit"value="submit"/></td>
</tr>
    </table>
</form>
</body>
</html>

創建響應的Servlet

public class ProcessStep1Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //獲取圖書信息
        String [] books=request.getParameterValues("book");
        //將圖書信息放入HttpSession中
        request.getSession().setAttribute("books",books);
        //重定向
        response.sendRedirect("/javaweb4/step2.jsp");
    }
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
//並在web.xml中添加相應的配置信息

2.創建step2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>step2</title>
</head>
<body>
<h3>輸入地址和信用卡信息</h3>
<form action="/javaweb4/processStep2" method="post">
<table cellpadding="10"cellspacing="10"border="1">
<tr>
    <td colspan="2">寄送信息</td>
</tr>
    <tr>
        <td>姓名:</td>
        <td><input type="text" name="name"/></td>
    </tr>
    <tr>
        <td>寄送地址</td>
        <td><input type="text"name="address"/></td>
    </tr><tr>
    <td colspan="2">信用卡信息</td>
</tr>
    <tr>
        <td>種類:</td>
        <td><input type="radio" name="cardType"value="Visa"/>Visa
            <input type="radio" name="cardType" value="Master"/>Master</td>
    </tr>
    <tr>
        <td>卡號:</td>
        <td><input type="text"name="card"/></td>
    </tr>
    <tr>
        <td colspan="2"><input type="submit"name="submit"/></td>
    </tr>
</table>
</form>
</body>
</html>

創建響應的Servlet

public class ProcessStep2Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//獲取所有信息
        String name=request.getParameter("name");
        String address=request.getParameter("address");
        String cardType=request.getParameter("cardType");
        String card=request.getParameter("card");
        Customer customer=new Customer(name,address,cardType,card);
        //放到session中
        HttpSession session=request.getSession();
        session.setAttribute("customer",customer);
        //重定向
        response.sendRedirect("/javaweb4/confirm.jsp");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}
//並在web.xml中添加相應的配置信息

3.創建confirm.jsp

<%@ page import="cn.javaweb4.com.Customer" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>confirm</title>
</head>
<body>
<%
    Customer customer=(Customer)session.getAttribute("customer");
    String [] books=(String[])session.getAttribute("books");
%>
<table>
    <tr>
        <td>顧客姓名:</td>
        <td><%=customer.getName()%></td>
    </tr> <tr>
        <td>地址:</td>
        <td><%=customer.getAddress()%></td>
    </tr> <tr>
        <td>卡號:</td>
        <td><%=customer.getCard()%></td>
    </tr><tr>
        <td>卡類型:</td>
        <td><%=customer.getCardType()%></td>
    </tr>
    <tr>
        <td>Books:</td>
        <td>
            <%
                for(String book:books){
                    out.print(book);
                }
            %>
        </td>
    </tr>
</table>
</body>
</html>

三.重複提交問題

1.創建index.jsp

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>
</head>
<body>
  <%
      String tokenValue=new Date().getTime()+"";
      session.setAttribute("token",tokenValue);
  %>
<form action="<%=request.getContextPath()%>/tokenServlet" method="post">
<input type="hidden" name="token"value="<%=tokenValue%>"/>
    name:<input type="text"name="name"/>
    <input type="submit"value="Submit"/>
</form>
</body>
</html>

2.創建對應的Servlet

public class TokenServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session=request.getSession();
        Object token=session.getAttribute("token");
        String tokenValue=request.getParameter("token");
        if(token!=null&& token.equals(tokenValue)){
            session.removeAttribute("token");
        }else {
            response.sendRedirect(request.getContextPath()+"/javaweb4/token.jsp");
            return;
        }
    }
}
//在web.xml中加入相關配置

3.創建提示頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>repeat</title>
</head>
<body>
<h3>重複提交</h3>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章