iT邦幫忙

DAY 6
3

JSP 學習分享系列 第 6

JSP 之Cookie範例

JSP Cookie的用法
1.傳一個名字,寫到Cookie,再秀出來,
傳值的form用之前的

  <%@page contentType="text/html" pageEncoding="UTF-8"%>

    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    
    
      <form method="post" action="setCookie.jsp">
          User name: <input type="text" name="userName" >
        <input type="submit" name="submit" value="Save">
      </form>
    

2.先建立一個Cookie的物件,再加到response裡
===setCookie.jsp===

  <%@ page import="java.util.*"%>
<%
  String username=request.getParameter("userName");
  if(username==null){
    username="";
  }
  Cookie cookie = new Cookie ("username",username);
  response.addCookie(cookie);
%>

    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    
    
        <a href="showCookieValue.jsp">Next Page to view the cookie value</a>
    

3.從cookie裡把值再拿出來
===showCookieValue.jsp===

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
  String cookieName = "username";
  Cookie cookies [] = request.getCookies ();
  Cookie myCookie = null;
  if (cookies != null){
    for (int i = 0; i < cookies.length; i++) {
      if (cookies [i].getName().equals (cookieName)){
        myCookie = cookies[i];
        break;
      }
    }
  }
%>

    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    
    
<%
  if (myCookie == null) {
    %>
    No Cookie found with the name <%=cookieName%>
    <%
  } else {
    %>
    <p>Welcome: <%=myCookie.getValue()%>.
    <%
  }
%>
    

上一篇
useBean的功能
下一篇
使用JSP產生一個數字類型的圖片辦識碼
系列文
JSP 學習分享30

尚未有邦友留言

立即登入留言