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()%>.
<%
}
%>