Java String to HTML Entities Encoder

The following is a handy Java utility method to encode a plain text string into appropriate HTML entities. This method is similar to the htmlentities function in PHP. This method only encodes some of the more common characters to the equivalent HTML entity name while the rest are encoded as HTML entity numbers.

public static String stringToHTMLEntities(String string) {
  if (string == null) {
    return "";

  StringBuffer sb = new StringBuffer(string.length());

  boolean lastWasBlankChar = false;
  int len = string.length();
  char c;

  for (int i = 0; i < len; i++) {
    c = string.charAt(i);

    if (c == ' ') {
      if (lastWasBlankChar) {
        lastWasBlankChar = false;
        sb.append(" ");
      } else {
        lastWasBlankChar = true;
        sb.append(' ');
    } else {
      lastWasBlankChar = false;

      if (c == '"') {
      } else if (c == '&') {
      } else if (c == '<') {
      } else if (c == '>') {
      } else if (c == 'n') {
      } else if (c == 39) { //check for apostrophe character
      } else {
        int ci = 0xffff & c;

        if (ci < 160) {
        } else {
          sb.append(new Integer(ci).toString());

  return sb.toString();

JSON Interchange Using AJAX and Java Servlets

The following is a simple example of how to implement a JSON based data interchange using an AJAX client-side request and a Java Servlet server-side response. The expected result of the example code is that an individual’s full name is displayed after the client enters a user ID.

On the client-side, we need a web page with an input field to capture the user ID (user_id) and a placeholder to display the returned full name (user_name).

User ID: <input type='text' name='user_id' id='user_id' />
         <span id="user_name"></span>

We need to load the jQuery library to be able to use some of the nice AJAX functionality.

<script src=""></script>

We also need a JavaScript function on the client-side to generate the XMLHttpRequest. The following jQuery based function will generate the XMLHttpRequest when the user_id input field changes. When the user changes the contents of the input field, this function is called and a request is then submitted to the server-side Java Servlet (FullNamePopulator). The JSON based response from the Java Servlet is then parsed by the function and the user_name placeholder is replaced with the returned full name.

$(function() {
  $("input#user_id").change(function() {
    $.getJSON("/FullNamePopulator",{user_id: $(this).val()}, function(j) {
      var value = '';
      for (var i = 0; i < j.length; i++) {
        value = j[i].optionDisplay;

The Java Servlet is expected to return a JSON formatted response as follows given an input user_id of “abc.”

[{"optionValue":"abc","optionDisplay":"Full Name 1"}]

The Java Servlet handles the look up and formatting of the response. In this example, a simple HashMap is used to hold three sample user ID’s and the associated full names. The user_id submitted to the Servlet is used as a key to the HashMap. If a value is found, then the full name is used otherwise “Unknown User” is used and the JSON response is formatted and sent to the client.


import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FullNamePopulatorServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public void init(ServletConfig config) throws ServletException {

  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    ServletOutputStream outputStream = null;
    String userID = null;
    String userName = null;
    StringBuffer outputStringBuffer = new StringBuffer();
    HashMap exampleHashMap = new HashMap();

    exampleHashMap.put("abc", "Full Name 1");
    exampleHashMap.put("xyz", "Full Name 2");
    exampleHashMap.put("123", "Full Name 3");

    try {
      response.setHeader("Pragma", "no-cache");
      response.setDateHeader("Expires", -1);

      if (request != null) {
        userID = request.getParameter("user_id");

      if ((userID == null) || (userID.trim().equals(""))) {
        userID = "";

      if (exampleHashMap.containsKey(userID)) {
        userName = (String) exampleHashMap.get(userID);
      } else {
        userName = "Unknown User";

      outputStream = response.getOutputStream();


    } catch (Exception e) {
    } finally {


  public void destroy() {