![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhS2_8-EquHR8KugyXG8AN2VplERrE79zw5YPYHLpjYrTH9o3fHHEVqacHTGi4hxoipyqsr8tbtiAQgjD9jtFHvWSn35jlaPoWrX777dnwGcYwi0O2BdIAW2XrOYM5ScKafxXZ6CZEvMmA/s1600/servlet.png)
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":
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9-TozUt-s8oeZmQnjdU2k2vvx6V3BI7WsPI2X1Ags_tvA-o1DT4AAXWXJdC-7VdGODxylQQYbNqUjBF0euS-1WnyoN7UKFYvu5AQ0nSUNFZGnvEhh2oK8V55rzxy44QPJOO81z5OZyvo/s320/1.png)
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:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjqIT5pu-019ye6IU5IYqLz3xoBm7CE_zGaSRQKF6NJtxcTSKRh_x1eRhL_FhPxm-PDyWvXh7-_EDZ1skSQ5xRDpFQ5sP5gx_RucWhvoIYlp0iukk06BlX-ls4r1PbyIXOjBlvfTV2NxE0/s1600/2.png)
The result can be seen below:
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgp_KK4nOfegzTZ7LElds6rLAD8l-cuQr4G6picIEoI1PjySlrfQTgxUnP-9wZwqkwQ5XIhxK3WTLlVcxEkexuPVaU-vIQnv-8ia3dWR79DhTIG9sDfg1jHy_S1ruSKJvHYJkEJ0iVSmaE/s1600/2.png)
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