Thursday, August 29, 2013

Java: How to read form-data in HttpServletRequest

Sometimes you need to filter requests out by the data they contain. For example, if the user is trying to login, you do not need him to be authenticated. You can do this by looking at the Form Data of the request.

    public void doFilter(ServletRequest request, ServletResponse response, 
        FilterChain chain) throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest) || 
                !(response instanceof HttpServletResponse)) {
            throw new ServletException("Not an HTTP Request/Response!");
        }
        HttpServletRequest hRequest = ((HttpServletRequest) request);
        HttpServletResponse hResponse = ((HttpServletResponse) response);

        // get Form Data Map
        Map<String,String[]> paramMap = hRequest.getParameterMap();

        // can look at URL query string like this
        String queryStr = hRequest.getQueryString();

        // look if it contains something you need
        boolean hasFormData = paramMap.containsKey("m") &&
            !paramMap.get("m").equals("login");

        if (hasFormData) {
            //response.doSomething()
        }
}

No comments:

Post a Comment