I try to search information from many websites, but what i can found is they only demonstrate the example with ONE ATTRIBUTE in a Cookie only.
What i want is how to set more than 1 attribute in a same cookie?
Below is my code: currently i only can show the username but cannot show the age. How to enable the ShowCookie.jsp able to show both the attribute of "username" and "age" enter by User?
GetValue.jsp
SetCookie.jsp
ShowCookie.jsp
What i want is how to set more than 1 attribute in a same cookie?
Below is my code: currently i only can show the username but cannot show the age. How to enable the ShowCookie.jsp able to show both the attribute of "username" and "age" enter by User?
GetValue.jsp
Code:
<%@ page language="java" %> <html> <head><title>Get username & age</title></head> <body bgcolor="cyan"> <table> <form method="post" action="http://localhost:8080/SetCookie.jsp"> <tr> <td>Enter Your Name:</td> <td><input type="text" name="username" length="20" maxlength="20"></td> </tr> <tr> <td>Enter Your Age:</td> <td><input type="text" name="age" length="3" maxlength="3"></td> </tr> <tr> <td colspan="2"><center><input type="submit" value="Submit"></center></td> </tr> </form> </table> </body> </html>
Code:
<%@ page language="java" %>
<%
String username=request.getParameter("username");
String age=request.getParameter("age");
if(username == null) username = "";
if(age = null) age = "";
Cookie usernameCookie = new Cookie("username",username);
usernameCookie.setMaxAge(7*24*60*60);
response.addCookie(usernameCookie);
Cookie ageCookie = new Cookie("age",age);
ageCookie.setMaxAge(7*24*60*60);
response.addCookie(ageCookie);
%>
<html>
<head><title>Set Cookie</title></head>
<body bgcolor="cyan">
<a href="http://localhost:8080/ShowCookie.jsp">Show cookie value</a>
</body>
</html>
Code:
<%@ page language="java" %>
<%
String cookieName = "username";
String cookieAge = "age";
Cookie cookies [] = request.getCookies();
Cookie usernameCookie = null;
Cookie ageCookie = null;
if(cookies != null)
{
for(int i=0; i<cookies.length; i++)
{
if(cookies [i].getName().equals(cookieName))
{
usernameCookie = cookies [i];
break;
}
if(cookies [i].getName().equals(cookieAge))
{
ageCookie = cookies [i];
break;
}
}
}
%>
<html>
<head><title>Show Cookie</title></head>
<body bgcolor="cyan">
<%
if(usernameCookie == null)
{
out.println("Hello, World!");
}
else
{
out.println("Hello, " + usernameCookie.getValue() + "!");
}
%>
<%
if(ageCookie == null)
{
out.println("You forgot enter your age!");
}
else
{
out.println("Your age is: " + ageCookie.getValue() + "!");
}
%>
</body>
</html>