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.

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).

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

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.

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

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.

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.