Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Web and Application Interfaces: Default Return String Encoding and Customization

Tech 1

Default and Custom String Encoding for Java Interface Returns

In Java, standard web application interfaces (like Spring MVC controllers, Servlet responses) default to returinng strings with UTF-8 encoding. For non-web contexts, raw Java interfaces themselves don’t enforce encoding—enocding behavior depends on the caller and how the string is transmitted or persisted. Below are practical steps to handle encoding consistently across both scenarois.

Phase Action
1 Define a base string-provider interface
2 Implement a baseline UTF-8 return version
3 Create a web-specific adapter to adjust response headers for custom encoding
4 Write a test caller to verify output correctness
Define Base Interface
import java.nio.charset.Charset;

public interface TextProvider {
    String fetchLocalizedText();
    Charset getTargetEncoding();
}
Implement Baseline UTF-8 Provider
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Utf8TextService implements TextProvider {
    @Override
    public String fetchLocalizedText() {
        return "こんにちは、世界!これはUTF-8のデフォルト出力です。";
    }

    @Override
    public Charset getTargetEncoding() {
        return StandardCharsets.UTF_8;
    }
}
Web-Specific Custom Encoding Adapter (Servlet Example)
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;

public class EncodedTextServletAdapter {
    public static void writeEncodedResponse(TextProvider provider, HttpServletResponse resp) throws IOException {
        Charset targetCharset = provider.getTargetEncoding();
        resp.setContentType("text/plain; charset=" + targetCharset.name());
        resp.setCharacterEncoding(targetCharset.name());
        try (PrintWriter writer = resp.getWriter()) {
            writer.write(provider.fetchLocalizedText());
        }
    }
}

public class ShiftJisTextService implements TextProvider {
    @Override
    public String fetchLocalizedText() {
        return "こんにちは、世界!これはShift_JISのカスタム出力です。";
    }

    @Override
    public Charset getTargetEncoding() {
        return Charset.forName("Shift_JIS");
    }
}
Test Caller for Raw and Web Contexts
import jakarta.servlet.http.HttpServletResponse;
import org.mockito.Mockito;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class EncodingTester {
    public static void main(String[] args) throws Exception {
        // Test raw UTF-8 string provider
        TextProvider utf8Provider = new Utf8TextService();
        String rawUtf8 = utf8Provider.fetchLocalizedText();
        System.out.println("Raw UTF-8 Bytes Length: " + rawUtf8.getBytes(StandardCharsets.UTF_8).length);

        // Test web Shift_JIS adapter with mock response
        TextProvider shiftJisProvider = new ShiftJisTextService();
        HttpServletResponse mockResp = Mockito.mock(HttpServletResponse.class);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PrintWriter mockWriter = new PrintWriter(outputStream, true, shiftJisProvider.getTargetEncoding());
        Mockito.when(mockResp.getWriter()).thenReturn(mockWriter);
        EncodedTextServletAdapter.writeEncodedResponse(shiftJisProvider, mockResp);
        byte[] shiftJisBytes = outputStream.toByteArray();
        System.out.println("Shift_JIS Bytes Length: " + shiftJisBytes.length);
        System.out.println("Decoded Shift_JIS Text: " + new String(shiftJisBytes, shiftJisProvider.getTargetEncoding()));
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.