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:

<servlet>
    <servlet-name>Test</servlet-name>
    <servlet-class>com.l3oc.Test</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Test</servlet-name>
    <url-pattern>/test</url-pattern>
</servlet-mapping>

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 java.io.IOException;
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;
 
 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  response.getWriter().println("<b>Servlet</b> is working!");
 }
 
 @Override
 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:


Download
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