Java Handling of UTF-8 Encoded Query Parameters

When working with Java web applications, it is essential to manage query parameters correctly, especially when they contain non-ASCII characters like Chinese. This article explains how to retrieve and decode UTF-8 encoded query parameters in Java, along with code examples.

Encdoing Mechanism for Query Parameters

Query parameters are typically encoded using URL encoding, which converts special characters into a format that can be safely transmitted over the intrenet. For Chinese characters, this process usually involves UTF-8 encoding.

For example, the string "你好" would be encoded as "%E4%BD%A0%E5%A5%BD" in UTF-8.

Retrieving and Decoding Parameters in Java

In Java Servlets, you can use the request.getParameter() method to retrieve query parameters. When these parameters include Chinese characters, proper decoding is required to ensure accurate data retrieval.

Below is a sample servlet demonstrating how to extract and decode a parameter named "name":

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

@WebServlet("/example")
public class ExampleServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String input = request.getParameter("name");
        if (input != null) {
            String result = URLDecoder.decode(input, "UTF-8");
            System.out.println("Decoded Value: " + result);
        }
    }
}

In this example, request.getParameter("name") retrieves the parameter value, and URLDecoder.decode() decodes it using UTF-8.

Clas Diagram

The following class diagram outlines the key components used in the example:

classDiagram
    class ExampleServlet {
        +doGet(HttpServletRequest, HttpServletResponse): void
    }
    interface HttpServletRequest {
        +getParameter(String): String
    }
    interface HttpServletResponse {
        // methods
    }
    class URLDecoder {
        +decode(String, String): String
    }

Tags: java servlet URL Decoding UTF-8 web development

Posted on Tue, 13 Oct 2026 16:08:11 +0000 by adam_gardner