I get the code from a book about Servlets:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ColorSession extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name;
String color;
Integer hitCounts;
HttpSession mySession = request.getSession(true);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (mySession.isNew()) { //html page1
out.println("<HTML>");
out.println("<HEAD><TITLE>Select Color</TITLE></HEAD>");
out.println("<BODY>");
out.println("<FORM METHOD=\"POST\" ACTION=\"ColorSession\">");
out.println("Please select your color:<BR>");
out.println("<INPUT TYPE=\"RADIO\" NAME=\"bcolor\" "
+ "VALUE=\"white\">White<BR>");
out.println("<INPUT TYPE=\"RADIO\" NAME=\"bcolor\" "
+ "VALUE=\"red\">Red<BR>");
out.println("<INPUT TYPE=\"RADIO\" NAME=\"bcolor\" "
+ "VALUE=\"green\">Green<BR>");
out.println("<INPUT TYPE=\"RADIO\" NAME=\"bcolor\" "
+ "VALUE=\"blue\">Blue<P>");
out.println("Please enter your name:<BR>");
out.println("<INPUT TYPE=\"TEXT\" NAME=\"name\" "
+ "SIZE=\"25\"><P>");
out.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Submit\">");
out.println("</FORM>");
out.println("</BODY>");
out.println("</HTML>");
} else {
String bcolor = request.getParameter("bcolor");
if (bcolor != null) {
if (bcolor.equals("red")) {
color = "#FF0000";
} else if (bcolor.equals("green")) {
color = "#00FF00";
} else if (bcolor.equals("blue")) {
color = "#0000FF";
} else {
color = "FFFFFF";
}
name = request.getParameter("name");
hitCounts = new Integer(1);
mySession.setAttribute("bcolor", color);
mySession.setAttribute("hitCounts", hitCounts);
mySession.setAttribute("name", name);
} else {
color = (String) mySession.getAttribute("bcolor");
name = (String) mySession.getAttribute("name");
hitCounts = (Integer) mySession.getAttribute("hitCounts");
}
mySession.setAttribute("hitCounts", new Integer(hitCounts
.intValue() + 1));
out.println("<HTML>"); //html page2
out.println("<HEAD><TITLE>Color Select</TITLE></HEAD>");
out.println("<BODY BGCOLOR=\"" + color + "\">");
out.println("<H2>Hello " + name + "!</H2>");
out.println("<H3>You have requested this page " + hitCounts
+ "times.<BR></H3>");
out.println("<A HREF=\"ColorSession\">Reload Page</A>");
out.println("</BODY>");
out.println("</HTML>");
}
}
}
This servlet creates a HttpSession in order to store the user's name,preffer color and the times it has been accessed.
When it is accessed for the first time ,it will create a new session and display a html page to ask the user enter
his color and name. And after this it will display the information about the session.But,when i click the submit button in
the page1,it only display the same page(page1),not page2!
I don't know why!How can i make it do the things i want to?