others-how to write a servlet filter in kotlin?

1. Purpose

In this post, I will show you how to write a servlet filter in kotlin.

2. Solution

2.1 What is a servlet filter?

Servlet Filter is defined in the Servlet 2.3 specification and can check and modify the request object and response object passed to the Web resource by the Servlet container.

The Servlet API provides a Filter interface. When developing a web application, if the written Java class implements this interface, the Java class is called a Filter. by Filter technology, developers can implement users to intercept access requests and responses before accessing a target resource.

Here is the Filter interface provided by Servlet API:

public abstract interface Filter{  
    public abstract void init(FilterConfig paramFilterConfig) throws ServletException;  
    public abstract void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain   
        paramFilterChain) throws IOException, ServletException;  
    public abstract void destroy();  
}

2.2 How does the servlet filter intercepts a http request?

There is a doFilter method in the Filter interface. When we write the Filter and configure which web resource to intercept, the WEB server calls the service method of the web resource every time.

The doFilter method of the filter will be called first, so writing code in this method can achieve the following goals:

  • Let a piece of code execute before calling the target resource.
  • Whether to call the target resource (that is, whether to let the user access the web resource).
  • Let a piece of code execute after invoking the target resource.
  • When the web server calls the doFilter method, it will pass a filterChain object in. The filterChain object is the most important object in the filter interface. It also provides a
  • The doFilter method, the developer can decide whether to call this method according to the requirements, and if this method is called, the web server will call the service method of the web resource, that is, the web resource will be accessed.Otherwise the web resource will not be accessed.

2.2 Write a servlet filter in java and spring

We can use spring to implement a java servlet filter easily.

@Component
public class SimpleFilter implements Filter {
   @Override
   public void destroy() {}

   @Override
   public void doFilter
      (ServletRequest request, ServletResponse response, FilterChain filterchain) 
      throws IOException, ServletException {}

   @Override
   public void init(FilterConfig filterconfig) throws ServletException {}
}

The above is a simple skeleton servlet filter code, we can add more code to it:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.stereotype.Component;

@Component
public class SimpleFilter implements Filter {
   @Override
   public void destroy() {}

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) 
      throws IOException, ServletException {
      
      System.out.println("Remote Host is:"+request.getRemoteHost());
      System.out.println("Remote Address is:"+request.getRemoteAddr());
      filterchain.doFilter(request, response);
   }

   @Override
   public void init(FilterConfig filterconfig) throws ServletException {}
}

2.3 Write a servlet filter in kotlin

We can use Kotlin to re-write the servlet filter as follows:

package com.example.filters

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.slf4j.MDC
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import java.io.IOException
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
@Order(1)
class SwFilter : Filter {
    val Any.logger: Logger
        get() = LoggerFactory.getLogger(this.javaClass)

    @Throws(IOException::class, ServletException::class)
    override fun doFilter(
        request: ServletRequest,
        response: ServletResponse,
        chain: FilterChain
    ) {
        val req: HttpServletRequest = request as HttpServletRequest
        val res: HttpServletResponse = response as HttpServletResponse
        logger.info(
            "Logging Request  {} : {}", req.getMethod(),
            req.getRequestURI()
        )
        chain.doFilter(request, response)
        logger.info(
            "Logging Response :{}",
            res.getContentType()
        )
    } // other methods
}



3. Summary

In this post, I demonstrated how to write servlet filter in kotlin. That’s it, thanks for your reading.