/*
* TestEncodeCookiesServlet - Depend on setting of encodeCookies property
* in sun-web.xml, this web app check if
* cookies are URL encoded or not.
* It encodes by "adding" cookies to response,
* and it decodes by "getting" cookies from
* request. The gotten cookies should equals
* to the added cookies
*/
package servlet_tests;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class TestEncodeCookiesServlet extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("
");
out.println("");
String action = null;
action = request.getParameter("action");
Cookie[] myCookies = new Cookie[3];
myCookies[0] = new Cookie("cookie0", "00");
myCookies[1] = new Cookie("cookie1", "h@wdy");
myCookies[2] = new Cookie("cookie2", "w0rld");
out.println("TestEncodeCookiesServlet
");
if (action != null && action.equalsIgnoreCase("add")) {
// Add cookies to HTTP response
out.println("Add cookies to HTTP response
");
for (int i = 0; i < myCookies.length; i++) {
response.addCookie(myCookies[i]);
out.println(" Add myCookies[" + i + "] = " +
myCookies[i].getName() + " = " +
myCookies[i].getValue() + "
");
System.out.println(" Add myCookies[" + i + "] = " +
myCookies[i].getName() + " = " +
myCookies[i].getValue() + "
");
}
} else if (action != null && action.equalsIgnoreCase("get")) {
// Get cookies from HTTP request
out.println("Get cookies from HTTP request
");
Cookie[] requestCookies = request.getCookies();
if (requestCookies != null && requestCookies.length > 0) {
for (int i = 0; i < requestCookies.length; i++) {
int index = -1;
for (int j = 0; j < myCookies.length; j++) {
if (requestCookies[i].getName().equals(myCookies[j].getName()) &&
requestCookies[i].getValue().equals(myCookies[j].getValue())) {
index = j;
break;
}
}
if (index > -1) {
out.print(" requestCookies[" + i + "] = " +
requestCookies[i].getName() + " = " +
requestCookies[i].getValue());
out.println(" -> match to myCookies[" + index + "]
");
} else {
out.print(" requestCookies[" + i + "] = " +
requestCookies[i].getName() + " = " +
requestCookies[i].getValue());
out.println(" -> NOT match to any myCookies
");
}
}
} else {
out.println(" requestCookies is null
");
}
} else {
out.println("Undefined action. -> Action is either add or get
");
}
out.println("");
}
}