Wednesday, April 24, 2013

2.1 Servlets

I do not intend to write a comprehensive post that would describe the servlet technology as a whole. It's just not possible. Great books with numerous pages are already written on each of the tech stack of JEE 6. Servlets are no exceptions. So, I would try to capture the basic idea of these things.

Overview:

Servlets are pieces of program that run in server to handle clients requests. Unlike the web servers, Servlets can access DAL, convert the resultset into browser readable format. Servlets can handle multiple client requests efficiently as they are not run as processes rather, as threads.

Let's look at an example of a servlet.
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet(name = "WelcomeServlet", urlPatterns = "/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.getWriter().println("welcome to the hotel california!");

        response.getWriter().close();

    }

}

}
You might notice that the line
@WebServlet(name = "WelcomeServlet", urlPatterns = "/welcome")
defines the servlets name and url pattern that it would serve. For example, if your project's root is localhost:8080/myapp, then this servlet can be called by the url localhost:8080/myapp/welcome. It is possible to override this url pattern annotation by modifying the web.xml file found in WEB.INF folder. If we add these lines in web.xml
    
        HelloServlet
        servlets.HelloServlet
    

    
        HelloServlet
        /hello
    
then the servlet's name would be overridden and it would be called by "/hello".





No comments:

Post a Comment