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 == '"') {
        sb.append("\"");
      } else if (c == '&') {
        sb.append("&");
      } else if (c == '<') {
        sb.append("<");
      } else if (c == '>') {
        sb.append(">");
      } else if (c == 'n') {
        sb.append("n");
      } else if (c == 39) { //check for apostrophe character
        sb.append("'");
      } else {
        int ci = 0xffff & c;

        if (ci < 160) {
          sb.append(c);
        } else {
          sb.append("&#");
          sb.append(new Integer(ci).toString());
          sb.append(';');
        }
      }
    }
  }

  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 outcome 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="http://code.jquery.com/jquery-latest.min.js"></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;
      }
      $("#user_name").html(value);
    })
  })
});

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.io.IOException;

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 {
    super.init(config);
  }

  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.reset();
      response.setHeader("Pragma", "no-cache");
      response.setDateHeader("Expires", -1);
      response.setContentType("text/html");

      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();

      outputStringBuffer.append("[{\"optionValue\":\"")
                        .append(userID)
                        .append("\",\"optionDisplay\":\"")
                        .append(userName)
                        .append("\"}]");

      outputStream.print(outputStringBuffer.toString());
    } catch (Exception e) {
    } finally {
    }

    return;
  }

  public void destroy() {
    return;
  }
}

Round Double To Nearest Hundredth

Here are a few ways to round a double in Java to the nearest integer, tenths, hundredths, or thousandths decimal place.

UPDATE #1: A reader commented that the code was not working for tenths, hundredths, and thousandths. It has been corrected, as suggested, by adding a decimal point to the multipliers and divisors.

UPDATE #2: A reader commented that the code was only working for positive numbers. It has been corrected to handle both positive and negative numbers (and zero, too).

Such simple code, yet two errors were identified by readers. Shame on me for not fully testing the code before posting. Feel free to let me know if you find any other scenarios that don’t work as expected.

double x = 0.0d;
double y = 0.0d;

// Double rounded to the nearest integer.
y = (int) (x + ((x < 0.0) ? -0.5 : 0.5));

// Double rounded to the nearest tenth.
y = ((int) ((x * 10.0) + ((x < 0.0) ? -0.5 : 0.5))) / 10.0;

// Double rounded to the nearest hundredth.
y = ((int) ((x * 100.0) + ((x < 0.0) ? -0.5 : 0.5))) / 100.0;

// Double rounded to the nearest thousandth.
y = ((int) ((x * 1000.0) + ((x < 0.0) ? -0.5 : 0.5))) / 1000.0;