Java – Check If URL Contains Query String or not

In this post, we show you two ways how to check if URL contains query string or not in Java Web: using HttpServletRequest.getQueryString() and using HttpServletRequest.getParameterMap().

 

1. Using HttpServletRequest.getQueryString()

Example1Servlet.java
package com.bytenota;

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 = "Example1Servlet", urlPatterns = {"/example1"})
public class Example1Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        if (request.getQueryString() == null) {
            out.write("The URL does not contain query string.");
        }
    }

}

In the above code, we simply check whether request.getQueryString() is null or not. If it returns null, the current URL does not contain query string and vice versa.

 

2. Using HttpServletRequest.getParameterMap()

Example2Servlet.java
package com.bytenota;

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 = "Example2Servlet", urlPatterns = {"/example2"})
public class Example2Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        if (request.getParameterMap().isEmpty()) {
            out.write("The URL does not contain query string.");
        }
    }

}

In the above code, we simply check whether request.getParameterMap() is empty or not. If it is empty, the current URL does not contain query string and vice versa.

Leave a Reply

avatar