Java Reference
In-Depth Information
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
3. CounterServlet will extend HttpServlet to create the shell for the class, like
this:
public class CounterServlet extends HttpServlet
{
}
4. Next, you need to create code for the doGet() method:
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
}
5. You are now ready to code the body of the doGet() method. This will be the
code that executes every time the servlet is invoked:
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
// You must set the content type before writing output.
res.setContentType("text/html");
// This creates a session if one doesn't exist or retrieves it if it does
// exist.
HttpSession session = req.getSession();
// Sessions are like HashMaps and only contain objects not primitives.
Integer count = (Integer) session.getAttribute("count");
// Count will be null the first time you invoke the servlet because it is a
// new session.
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
// This stores the object back into the session.
session.setAttribute("count", count);
// This is writing the HTML back to the browser.
PrintWriter out = res.getWriter();
Search WWH ::




Custom Search