JAX-RS @FormParam one time for all methods

288 views Asked by At

I am developing Java "JAX-RS" Web Services for books and contents. There will be 100s of URLs something similar ...

https://api.example.com/v1.3/book1/chapter/1

https://api.example.com/v1.3/book1/chapter/2

...

https://api.example.com/v1.3/book1/chapterN

To fetch the chapter content user needed to POST authToken, which I validate in server and return content or error. The sample code ...

@Path("/book1")
public class Book1 {

    @Path("/chapter/{cNum}")
    public String getMedias(
            @PathParam("cNum") String cNum, 
            @FormParam("authToken") String authToken) {
        // so here I validate the authToken
        return "bla bla!";
    }
}

This works perfectly. But I repeated @FormParam("authToken") in all 100s of methods like above. Is there a way that I can check only one time somewhere and remove from all methods? Thank you so much!

1

There are 1 answers

0
Madan Sapkota On BEST ANSWER

This will filter the required parameters before processing.

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(urlPatterns = {"/*"}, description = "Filters!")
public class MyFilter implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final String authToken = servletRequest.getParameter("authToken");
        if (authToken != null) {
            // and token is valid ? // etc etc ...
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // not valid
            servletResponse.getWriter().write("No Way! No Token!");
        }
    }

    @Override
    public void destroy() {
    }
}

This is helpful, if you want to check the security token or database connection or log URLs before processing the request.