May 27, 2015

Java Servlet

A Servlet is nothing more than a simple Java HTTP server. It's a class that extends from the HTTPServlet class, which can override methods like GET and POST, to process the requests and then return something. Here you can see how to do a simple Servlet using Eclipse and Tomcat.

Start creating a new "Dynamic Web Project" and in the "web.xml" insert this:


This code creates a servlet on the URI "/test" and who will handle the requests will be the class "com.l3oc.Test". Now create a package "com.l3oc" and a class "Test":

Do the Test class extends from "HTTPServer" class and override its "doPost" and "doGet" methods:

package com.l3oc;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Test extends HttpServlet {
 private static final long serialVersionUID = 1L;
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.getWriter().println("<b>Servlet</b> is working!");
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

The "doGet" method process the HTTP GET requests, you just set the response content-type and the through the writer you can return data using the println function, the same for POST method. That's it, you can override the others methods too:

The result can be seen below:

About the versions
  • Eclipse Java EE IDE for Web Developers Luna Service Release 1 (4.4.1)
  • Tomcat Server 8.0

0 comentários :

Post a Comment