// Purpose.  3 ways to pass "state" information from 1 HTTP request to another
//    1) URL parameters
//    2) <input type=hidden name=xxx value=yyy> HTML tags
//    3) HttpSession object

package testservlet;

import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.http.*;

public class ServletStateDemo extends HttpServlet {
  public void doPost( HttpServletRequest req, HttpServletResponse resp )
                    throws javax.servlet.ServletException, IOException {
    PrintWriter pw = resp.getWriter();
    String   state = req.getParameter( "state" );
    String  choice = req.getParameter( "choice" );

    HttpSession session = req.getSession();
    if (session != null) {
      String str = (String) session.getAttribute( "state" );
      if (str != null) state = str;
    }

    pw.println( "<html><head><title>Servlet State Demo</title></head><body>" );

    // URL parameters
    if (state == null) {
      pw.println( "Select a link:<ul>" );
      pw.println( "<li><a href=stateDemo?state=link&choice=first>First</a>" );
      pw.println( "<li><a href=stateDemo?state=link&choice=second>Second</a>" );
      pw.println( "<li><a href=stateDemo?state=link&choice=third>Third</a>" );
      pw.println( "</ul>");

    // "hidden" HTML tag
    } else if (state.equals("link")) {
      pw.println( "<form method=post action=stateDemo>" );
      pw.println( "<input type=hidden name=state value=hidden>" );
      pw.println( "Previous URL parameter was --- " + choice );
      pw.println( "<p>Enter a string for \"hidden\":" );
      pw.println( "<input type=text name=choice>" );
      pw.println( "<p><input type=submit value=Submit>" );
      pw.println( "</form>" );

    // setAttribute()
    } else if (state.equals("hidden")) {
      session.setAttribute( "state", "session" );
      pw.println( "Previous text with \"hidden\" HTML tag was --- " + choice );
      pw.println( "<p><a href=stateDemo>Next</a>" );

    // invalidate()
    } else if (state.equals("session")) {
      session.invalidate();
      pw.println( "Here is state.equals(\"session\")" );
      pw.println( "<p><a href=stateDemo>Top</a>" );
    }

    pw.println( "</body></html>" );
    pw.close();
  }

  public void doGet( HttpServletRequest req, HttpServletResponse resp )
                    throws javax.servlet.ServletException, IOException {
    doPost( req, resp );
} }
