Developing Web Applications With Ant by Richard Hightower - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

HelloWorldServlet.java

The servlet is contained in the class xptoolkit.web.HelloWorldServlet (see Listing 20.22). Like the Java application, it uses the Greeting interface and the GreetingFactory class that are packaged in greetmodel.jar, the output of the model project.

package xptoolkit.web;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.RequestDispatcher;

/* import the classes to create a greeting object or type greeting */ import xptoolkit.model.GreetingFactory;
import xptoolkit.model.Greeting;

public class HelloWorldServlet extends HttpServlet{ public void init(ServletConfig config) throws ServletException{ super.init(config);

/* Read in the greeting type that the factory should create */ String clazz = config.getInitParameter("Greeting.class") ; if(clazz!=null)System.setProperty("Greeting.class",clazz);

} public void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException{ RequestDispatcher dispatch;
ServletContext context;

/*Get the session, create a greeting bean, map the greeting bean in the session, and redirect to the Hello World JSP.
*/
try {

/* Create the greeting bean and map it to the session. */
HttpSession session = request.getSession(true); Greeting greet = (Greeting)

GreetingFactory.getGreetingFactory().getGreeting(); session.setAttribute("greeting", greet);

/* Redirect to the HelloWorld.jsp */
context = getServletContext();
dispatch = context.getRequestDispatcher("/HelloWorldJSP"); dispatch.forward(request, response);

}catch(Exception e){
throw new ServletException(e);
}
}

/* Just call the doGet method */
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException{ doGet(request, response);
}
} Listing 20.22