Jetty is a lightweight Servlet container which we suggest you use if you are going to develop servlets on your local machine, please don't run it on eniac.
java -jar start.jarThe server will start and log messages should start appearing in the terminal.
<html> <head><title>Example Web Application</title></head> <body> <p>This is a static document with a form in it.</p> <form method="POST" action="servlet"/> <input name="field" type="text" /> <input type="submit" value="Submit" /> </form> </body> </html>If you start the server at this point and click here you will see this new page.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String q = req.getParameter("q");
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<body>");
out.println("The paramter q was \"" + q + "\".");
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String field = req.getParameter("field");
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<body>");
out.println("You entered \"" + field + "\" into the text box.");
out.println("</body>");
out.println("</html>");
}
}
javac -cp PATH_TO_JETTY/lib/servlet-api-2.5-6.1.11.jar HelloServlet.javaThe "-cp" option adds the given jar file to the list of places to search for other classes your code requires. Copy the resulting HelloServlet.class file into the "hello/WEB-INF/classes" directory.
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>Example</display-name>
<!-- Declare the existence of a servlet. -->
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<!-- Map URLs to that servlet. -->
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
</web-app>
Note, there are two methods in a servlet class, doGet() and doPost(). These correspond to the two types of HTTP requests. The form we have uses the POST method. It could also use the GET method. The difference is that in the GET method the parameters are passed as part of the URL, which is inappropriate for most web forms. Try entering "http://localhost:8080/hello/servlet?q=Hello" into your browser to see how passing parameters with the GET method works.
If you have any questions, please post to the class newsgroup so others can benefit from the answer.