DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Leverage Lambdas for Cleaner Code
  • My Experiences with Maven in IntelliJ IDEA and NetBeans IDE
  • DataWeave Interview Question: Compare IDs From Two Arrays and Create a New Array
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption

Trending

  • A Non-Expiring AKS Deployment Token Could Read Secrets Across Three Namespaces
  • Guess the Speed: Building a Family Internet Speed Guessing Game
  • After the AI Commit: What Eight Retrospectives Taught Me About Working With Coding Agents
  • Why Spark Executors Leave Cores Idle on YARN: A Packing Model for Executor Sizing

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Using a Java Servlet Filter to intercept the response HTTP status code with NetBeans IDE 7 and Maven

Using a Java Servlet Filter to intercept the response HTTP status code with NetBeans IDE 7 and Maven

By 
Chad Lung
·
Oct. 23, 11 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
44.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Version 2.3 of the Java servlet spec introduced the concept of filters. According to the documentation from Oracle’s site: “A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses”. Today I’ll show you how to build a simple filter to intercept the response HTTP response code using annotations introduced in the Servlet 3.0 specification.


With NetBeans IDE 7 create a new Maven Java Web Application called: Intercept

Delete the index.jsp file under the Web Pages folder. Right-click on the project and add a new servlet called: MainServlet

Since we are using the new Servlet 3 annotations we don’t need to set a whole lot of properties.

Maven generates a decent MainServlet.java file for us, I just removed the comments for the output. My file looks like this:

package com.giantflyingsaucer.intercept;
 
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet(name = "MainServlet", urlPatterns = {"/"})
public class MainServlet extends HttpServlet {
 
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
 
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MainServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet MainServlet</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }
 
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
 
    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
 

Right-click on the project and add a Filter called: InterceptFilter

We will add the following two lines to the doFilter method.

HttpServletResponse hsr = (HttpServletResponse) response;
System.out.println("HTTP Status: " + hsr.getStatus());

My doFilter method looks like this:

@Override
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain)
        throws IOException, ServletException {
 
    if (debug) {
        log("InterceptFilter:doFilter()");
    }
 
    doBeforeProcessing(request, response);
 
    HttpServletResponse hsr = (HttpServletResponse) response;
    System.out.println("HTTP Status: " + hsr.getStatus());       
 
    Throwable problem = null;
    try {
        chain.doFilter(request, response);
    } catch (Throwable t) {
        problem = t;
        t.printStackTrace();
    }
 
    doAfterProcessing(request, response);
 
    if (problem != null) {
        if (problem instanceof ServletException) {
            throw (ServletException) problem;
        }
        if (problem instanceof IOException) {
            throw (IOException) problem;
        }
        sendProcessingError(problem, response);
    }
}

Clean and Build the project and deploy it to Apache Tomcat. Access the URL with a browser and take a look at your catalina.out file and you should see the HTTP response code.

Note: You shouldn’t need to do any changes to the web.xml file for this project to work.

From http://www.giantflyingsaucer.com/blog/?p=3279

Integrated development environment Filter (software) code style Apache Maven Java (programming language) NetBeans

Opinions expressed by DZone contributors are their own.

Related

  • Leverage Lambdas for Cleaner Code
  • My Experiences with Maven in IntelliJ IDEA and NetBeans IDE
  • DataWeave Interview Question: Compare IDs From Two Arrays and Create a New Array
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook