Skip to content

Instantly share code, notes, and snippets.

@eirikbakke
Created June 30, 2011 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eirikbakke/1056066 to your computer and use it in GitHub Desktop.
Save eirikbakke/1056066 to your computer and use it in GitHub Desktop.
Basic structure of a Servlet.
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/* The relative URL that this servlet will be handling. For instance, if we are running
Tomcat locally with an Eclipse project called "SomeProject", then by specifying "/Main"
below, Tomcat will use this servlet to handle requests for the URL
"http://localhost:8080/SomeProject/Main". */
@WebServlet("/Main")
public class MainPage extends HttpServlet {
/* Boilerplate. */
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
/* Boilerplate. */
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma" , "no-cache");
/* Anything you print here will be visible in Eclipse's console, since servlets are run
on the server side. */
System.out.println("Got a request!");
/* Get a parameter that was submitted through a form (if the request happened because a
form was submitted). This example retrieves parameters submitted through the HTML form
above. */
String ageParam = request.getParameter("ageParam" );
String colorParam = request.getParameter("colorParam");
// Do something with the parameters here...
/* Set some attributes; these will be available from the JSP file (e.g.
"${someAttribute1}"). */
request.setAttribute("someAttribute1", someObject1);
request.setAttribute("someAttribute2", someObject2);
request.setAttribute("someAttribute3", someObject3);
/* Dispatch a particular JSP page to handle the request (now with attributes
attached). */
RequestDispatcher rd = getServletContext().getRequestDispatcher("/WEB-INF/SomePage.jsp");
rd.forward(request, response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment