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
Over 2 million developers have joined DZone.
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
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI

Trending

  • AI Paradigm Shift: Analytics Without SQL
  • Dear Micromanager: Your Distrust Has a Job; It’s Just Not the One You’re Doing
  • Run Gemma 4 on Your Laptop: A Hands-On Guide to Google's Latest Open Multimodal LLM
  • From Indicators to Insights: Automating IOC Enrichment Using Python and Threat Feeds
  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 user avatar
Chad Lung
·
Oct. 23, 11 · Interview
Likes (0)
Comment
Save
Tweet
Share
43.9K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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