Tagged: servlet

Java Servlet: Servering static content

If you want to server static content – like PNGs, Javascript, etc – you need to explicitly tell your server this in its web.xml

Edit: I’ve changed this article due to an error and infelicitiy:

Add this file somewhere, and, voila, all the files in your res/ directory (in src/main/webapp/res in the gradle directory structure, that is) will be served.

public class ResourcesServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    RequestDispatcher rd = getServletContext().getNamedDispatcher("default");
    HttpServletRequest wrapped = new HttpServletRequestWrapper(req) {
      public String getServletPath() {
        return "/res/";
    rd.forward(wrapped, resp);
java java-servlet java-servlet-static-content

Servlets: Forwarding and Redirecting

If you want a 302 redirect, where res is a HttpServletResponse:


The first part of the path will be the name your site has in the container. If you uploaded SomeWar file, and Tomcat give it that name to request, your context path will be that.

The next part is either blank or the path to your servlet. For example, if you url-pattern in your web.xml is /somepath/* then this will be ‘somepath’.

The final part is the path to your servlet.

If you want to transparently forward to another servlet, keeping the existing objects in your HttpServletRequest:

    RequestDispatcher disp = httpServletRequest.getRequestDispatcher("/YourServletPath/PathToServlet");
    disp.forward(req, res);

The url here is the same as before but without the context path.

servlet servlet-forwarding

Tomcat 7: Error pages for exceptions and error codes

You can specify an error page in your web folder for either an exception or a standard error code.

The below makes error404.html be shown each time an array out of bounds error occurs.

       <!-- <error-code>404</error-code> -->
servlet servlet-error-pages

Servlets: filtering

You can filter all servlet requests, including REST ones with Jersey, with a filter:

 public class HelloFilter implements Filter {
  public void destroy() {
  public void doFilter(ServletRequest req, ServletResponse resp, 
           FilterChain chain) throws IOException, ServletException {
    chain.doFilter(req, resp);
  public void init(FilterConfig arg0) throws ServletException {

In the doFilter() method you call the rest of the filters on the chain to continue. Alternatively, you can just bail out there with something like:

  HttpServletResponse r = (HttpServletResponse) resp;

The filter allows you do look at the request and response, do various things with the servletcontext or httpservletrequest the latterly called doGet or REST method will see such changes.

You can register this in your web.xml like so:

servlet servlet-filters

Tomcat 7: REST services with Jersey

First download Apache Jersey. I downloaded the archive with the follow jars in them and placed them in /usr/share/tomcat7/lib and restarted tomcat.


I had to increase Tomcat’s memory size to avoid out of memory errors. I put this line at the top of /usr/share/tomcat7/bin/catalina.sh


Then you can create a simple POJO with the @XMLRootElement annotation. This will allow it to be converted into JSON for the REST services (Yes, it does say XMLRoot…)

 public class JsonObject {
   private String str;
   public String getStr() {
      return str;
   public void setStr(String str) {
      this.str = str;

Next you can create your REST class by creating a class like the following:

 public class Rest {
   UriInfo info;
   Request request;
   ServletContext context;
   public void init() {

This defines a new rest api that will have the ‘/rest/’ prefix. The @Context annotation injects UriInfo and details of the actual request that you may want to use. You can access these methods in a method annotated with @PostConstruct

The real logic comes in the method signatures:

 public String sayRest() {
   return "rest";

 public String sayRest() {
   return "html text";

This will produce different responses, depending on whether the client is asking for plain text or html. The path is /rest/r.

This produces and consumes the POJO object we created above:

 public JsonObject intakeJson(JsonObject intake) {
   intake.setStr("intaken: " + intake.getStr());
   return intake;

You can either pass in query parameters or path parameters:

 public String sayRestInHtml(@QueryParam("q") String q) {
   return "rest: "+q;

 public String sayRestInHtmlWithPath(@PathParam("q") String q) {
   return "rest with param: "+q;

You’d access these via /rest/r?q=sdfsdf and /rest/r/sdfsdf.

You can craft HTTP responses using:


This creates a CREATED HTTP response with the absolute path gained from the UriInfo via the @Context annotation above.

You now need to edit your web.xml to activate this servlet:

    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-name>Jersey REST Service</servlet-name>

This is a normal servlet mapping except the servlet-class is a Jersey class, and the init-param state where the REST class is. And the com.sun.jersey.api.json.POJOMappingFeature ensures you use Jackson instead of the standard Java implementation JaxB (which you don’t want).

You final urls will be such as

jersey java REST servlet tomcat

Page 1 of 2