Servlets..a complex example

Posted: June 20, 2009 in Java

In this example, two types of request will be served, namely the request for a simple page with a form in it via a GET request and process the form with some simple validation via a POST request. The methods doGet and doPost are both implemented in the code below.

By passing the servlet two parameters, errorMsg and niceMsg, the servlet will be more flexible with the messages that are passed back to the client as a result of the validation. The way in which the init parameters are picked up is illustrated in the init method of this example.

There is also a helper method, createForm, used to remove the form generation away from the actual request methods. It is used by both of the request methods to generate the form.

import javax.servlet.*;
import javax.servlet.http.*;

public class FormServlet extends HttpServlet
    private String errorMsg = 
		"You need to fill in the required Field!!!";
    private String beNice =
		"The form was filled in correctly, thank you for calling.";

    public void init(ServletConfig config)
    throws ServletException, UnavailableException {
       String tmp = config.getInitParameter("errorMsg");
       if(tmp != null) {
            errorMsg = tmp;

       tmp = config.getInitParameter("niceMsg");
       if(tmp != null) {
            beNice = tmp;

    public void destroy()
        // although I don't actually need to clear anything up here
        // this is the method to do it in.

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException
		PrintWriter out = resp.getWriter();

      out.println(createForm("", "", "")); 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s