// See if the username is specified in the request
String name = request.getParameter("username");
// If not, look in the session object. The web server or servlet
// container performs session tracking automatically for the servlet,
// and associates a HttpSession object with each session.
if (name == null)
name = (String)request.getSession().getAttribute("username");
// If the username is not found in either place, use a default name.
if (name == null) name = "World";
// Specify the type of output we produce. If this servlet is
// included from within another servlet or JSP page, this setting
// will be ignored.
response.setContentType("text/html");
// Get a stream that we can write the output to.
PrintWriter out = response.getWriter();
// And, finally, do our output.
out.println("Hello " + name + "!");