Taogen's Blog

Stay hungry stay foolish.

Background

I using Ant Design Table component to accomplish my list page. I return list data to frontend, but I got some error message in browser console.

Error Info

Warning: Each child in a list should have a unique "key" prop.
Solution

Solutions

Add a field “key” to each objects of the list

[{
key: 1,
createTime: "2021-01-07 11:13:00",
numberOfTopUp: 100,
totalNumber: 100
},
...
]

Reasons

Ant design defined this usage.

References

[1] Ant Design Components - Table

Principles

  • Member Variables of classes should use wrapper types for nullable. E.g. Integer, Long.

Primitive Types and Literals

byte

// use hex value
byte num1 = (byte) 0x7F; // 127
// use int
byte num3 = (byte) 127;
// use string
byte num2 = new Byte("127"); // 127

byte array

// use hex values
byte[] byteArray1 = new byte[]{(byte) 0xE2, (byte) 0x98, (byte) 0x83};
// use byte values
byte[] byteArray2 = new byte[]{(byte) -30, (byte) -104, (byte) -125};
// use int values
byte[] byteArray3 = new byte[]{(byte) 226, (byte) 152, (byte) 131};
System.out.println(Arrays.toString(byteArray1)); // [-30, -104, -125]
System.out.println(Arrays.toString(byteArray2)); // [-30, -104, -125]
System.out.println(Arrays.toString(byteArray3)); // [-30, -104, -125]

Initialize variables

  • Initialize Primitive type variables
byte byteVal = 1;
short shortVal = 1;
int intVal = 1;
long longVal = 1L;
float floatVal = 1.0F;
double doubleVal = 1.0;
boolean booleanVal = true;
char charVal = 'a';
  • Initialize Strings and array variables
String str = "hello";
int[] array = {1, 2, 3};
int[] array2 = new int[]{1, 2, 3};
int[] array3 = new int[3];
array3[0] = 1;
array3[1] = 2;
array3[2] = 3;
// objects
Object object = new Object();
  • Initialize List variables
List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3));
  • Initialize Set variables
// Using Another Collection Instance
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));

// Using Anonymous Class
Set<Integer> set = new HashSet() {{
add(1);
add(2);
}};

// Using Stream Since Java 8
Set<String> set3 = Stream.of("a", "b", "c")
.collect(Collectors.toCollection(HashSet::new));
  • Initialize Maps variables
// Using Anonymous Class (Not recommend, Double Brace Initialization should not be used. Replace of to use map.put(key, value).)
Map<Integer, String> map = new HashMap<Integer, String>() {{
put(1, "one");
put(2, "two");
put(3, "three");
}};

// Using Stream Since Java 8
Map<String, Integer> map2 = Stream.of(new Object[][] {
{ "key1", 1 },
{ "key2", 2 },
}).collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));

// Using a Stream of Map.Entry
Map<String, Integer> map3 = Stream.of(
new AbstractMap.SimpleEntry<>("key1", 1),
new AbstractMap.SimpleEntry<>("key2", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Initialize constants

  • Initialize Primitive type constants
public static final byte byteVal = 1;
public static final short shortVal = 1;
public static final int intVal = 1;
public static final long longVal = 1L;
public static final float floatVal = 1.0F;
public static final double doubleVal = 1.0;
public static final boolean booleanVal = true;
public static final char charVal = 'a';
  • Initialize Strings and Array constants
public static final String str = "hello";
public static final int[] MY_ARRAY = {1, 2, 3};
  • Initialize List constants
public static final List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3));
  • Initialize Set constants
public static final Set<Integer> SET = new HashSet();
static {
SET.add(1);
SET.add(2);
}
  • Initialize Map constants
public static final Map<Integer, String> MAP = new HashMap<Integer, String>();
static {
MAP.put(1, "one");
MAP.put(2, "two");
MAP.put(3, "three");
}

Initialize Immutable Container

  • Initialize Immutable List
// JDK 8 (Don't expose internal_list reference of unmodifiableList(List internale_list)). Arrays.asList() can't increase size, but it can modify its elements.
public static final List UNMODIFY_LIST = Collections.unmodifiableList(Arrays.asList(1, 2, 3));

// JDK 9 (Recommend, less space cost)
public static final List stringList = List.of("a", "b", "c");
  • Initialize Immutable Set
// JDK 8
public static final Set<String> stringSet = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));

// JDK 9 (Recommend)
public static final Set<String> stringSet2 = Set.of("a", "b", "c");
  • Initialize Immutable Map
// Immutable Map, JDK 8
public static final Map<Integer, String> UNMODIFY_MAP = Collections.unmodifiableMap(
new HashMap<Integer, String>()
{
{
put(1, "one");
put(2, "two");
put(3, "three");
};
});

// java 9, return ImmutableCollections (Recommend)
public static final Map<Integer, String> my_map2 = Map.of(1, "one", 2, "two");

// java 10, return ImmutableCollections (Recommend)
public static final Map<Integer, String> my_map3 = Map.ofEntries(
entry(1, "One"),
entry(2, "two"),
entry(3, "three"));

Enumeration Type vs Constants

  • If number of a set of constant is fixed, you should use enum type.
  • If number of a set of constant is increasing and variable, you should use constant variables.
public enum WeekDay {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
public static final int MONDAY = 0;
public static final int TUESDAY = 1;
public static final int WEDNESDAY = 2;
public static final int THURSDAY = 3;
public static final int FRIDAY = 4;
public static final int SATURDAY = 5;
public static final int SUNDAY = 6;

Type Formatting

Integer formatting

// Specifying length. 
String str2 = String.format("|%10d|", 101); // | 101|
// Left-justifying within the specified width.
String str3 = String.format("|%-10d|", 101); // |101 |
// Filling with zeroes.
String str4 = String.format("|%010d|", 101); // |0000000101|

Double formatting

Double value = 9.999;
String result = new DecimalFormat("#0.00").format(value);
double value = 3.1415926;
String result = String.format("value is: %.2f", value);
System.out.println(result); // value is: 3.14

Date formatting

Date date = new Date();
String result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

String formatting

String s = String.format("name is %s", name);
// Specify Maximum Number of Characters
String.format("|%.5s|", "Hello World"); // |Hello|
// Fill with zeros
String.format("%32s", Integer.toBinaryString(value)).replace(' ', '0')

If the template string contain %, you need replace with %%. For example,

String.format("%s increase 7%%", "Stock"); // Stock increase 7%
String.format("name like '%%%s%%'", "Jack"); // name like '%Jack%'

Value Comparison

Wrapper Object Comparison

Value type: 1. cache value(Integer: -128~127). 2. non-cache value. 3. null value.

Integer a = null; // 1, 128, null
Integer b = null; // 1, 128, null
boolean doesEqual = (a != null && a.equals(b)) || a == b;
System.out.println(doesEqual);

References

[1] Initialize a HashMap in Java

Sometimes we need to access our web projects running on local environments by domain names. We can reverse proxy a virtual domain by Nginx. Then we can use configured domain names to visit our local projects.

Downloading Nginx for Windows

Downloading Nginx for Windows from Nginx.

Configuring hosts file of Windows

Configuring virtual domains in C:\Windows\System32\drivers\etc\hosts

127.0.0.1 example1.com
127.0.0.1 example2.com

Check if the virtual domains are working

Open CMD terminal on Windows, and run the virtual domain test command. e.g. ping example1.com

Pinging example1.com [127.0.0.1] with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=64
Reply from 127.0.0.1: bytes=32 time<1ms TTL=64
Reply from 127.0.0.1: bytes=32 time<1ms TTL=64
Reply from 127.0.0.1: bytes=32 time<1ms TTL=64
...

Configuring Nginx Reverse Proxy

Configuring Nginx reverse proxy in conf\nginx.conf

http {
...
server {
listen 80;
server_name example1.com;
location / {
proxy_pass http://127.0.0.1:8081;
}
}

server {
listen 80;
server_name example2.com;
location / {
proxy_pass http://127.0.0.1:8082;
}
}

}

Starting Nginx

Starting Nginx

cd D:\nginx-1.18.0
start nginx.exe

Check if your Nginx server is up and running

Visit http://localhost to see the “welcome to nginx!” page

Visit

Visit the virtual domain (server name) URL http://example1.com/{your_app_request_path}

Warning: Ensure you are not using an HTTP proxy client such as v2rayN before accessing virtual domain URLs.

Stop Nginx

CMD of Windows

cd D:\nginx-1.18.0

# fast shutdown
nginx -s stop

# graceful shutdown
nginx -s quit

Git bash

cd D:\nginx-1.18.0

# fast shutdown
./nginx.exe -s stop

# graceful shutdown
./nginx.exe -s quit

Reload the configuration of Nginx

CMD of Windows

cd D:\nginx-1.18.0
nginx -s reload

Git bash

cd D:\nginx-1.18.0
./nginx.exe -s reload

Note

  1. Ensure that the ports 80, 433… where Nginx is listening are not occupied.
  2. Ensure you are not using an HTTP proxy client such as v2rayN before accessing virtual domain URLs.
  3. You must use Nginx commands to start and stop Nginx. Else you can’t stop the Nginx. Unless the Nginx process is killed in the task manager-Windows details or the Windows system is restarted.
  4. Before running start nginx, you must check if an Nginx server is running. If an Nginx server is running, you must run nginx -s stop first. Repeatedly running start nginx will start multiple Nginx servers, and you can’t stop all Nginx servers. Unless the Nginx process is killed in the task manager-Windows details or the Windows system is restarted.

Background

It’s a CRM system, and a single page web application, and has same URL for every page. It consists of top, left menu, right content, bottom area. It uses jQuery to fill different HTML to the content area when clicking the different menu. It using Bootstrap Modal to construct edit form pages.

Originally, It has no form validation, after I take over the project, I want to add form validation. So I add jQuery Validation Plugin to do form validation. Originally, the form page has no <form>, but <div>. The jQuery validation plugin need <form> to work, so I replace <div id="myForm"> with <form id="myForm">. However, after I added <form>, when I click the submit button, Some problems have occurred. The problem is after submitting the form, the current URL page auto-refresh. However, render pages in this project can’t by refresh URL but only by fill HTML. This auto-refresh problem confused me. The following code is to submit the form and then close the modal.

$("#myForm").find("#submit").off("click").on("click", function () {
// form validation and submit, after submit success to close modal and refresh table
...
});

Error Info

The current URL page auto refresh.

Solutions

We should override the submit event of the <form>, and using Event.preventDefault() to prevent the default actions of submit form. (e.g the default action of clicking on a checkbox is toggling a checkbox.)

$('#' + formElementId).bind('submit', function (e) {
e.preventDefault();
// form validation and submit, after submit success to close modal and refresh table
...
});

Reasons

Cause by the default action of submit form.

References

[1] Bootstrap Modal

[2] Event.preventDefault

jQuery Ajax Basic

Ajax Requests

jQuery.ajax(url [, settings ]) or jQuery.ajax( [settings] )

Perform an asynchronous HTTP (Ajax) request.

  • $.ajax()
  • $.get()
  • $.post()
  • $({selector}).load(): Load data from the server and place the returned HTML into the matched elements.

jQuery.ajaxSetup(options)

Set default values for future Ajax requests. Its use is not recommended.

options: A set of key/value pairs that configure the default Ajax request. All options are optional.

All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup().

Note: The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.

For example: Sets the defaults for Ajax requests to the url “/xmlhttp/“, disables global handlers and uses POST instead of GET. The following Ajax requests then sends some data without having to set anything else.

$.ajaxSetup({
url: "/xmlhttp/",
global: false,
type: "POST"
});
$.ajax({ data: myData });

Ajax Settings

settings

  • Type: PlainObject

A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup()

Settings for Request

accepts

  • Type: PlainObject
  • default: depends on dataType

A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept request header. This header tells the server what kind of response it will accept in return.

async

  • Type: Boolean
  • default: true

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

cache

  • Type: Boolean
  • Default: true, false for dataType 'script' and 'jsonp'

If set to false, it will force requested pages not to be cached by the browser.

Retrieve the latest version of an HTML page.

$.ajax({
url: "test.html",
cache: false
})
.done(function( html ) {
$( "#results" ).append( html );
});

contentType

  • Type: Boolean or String
  • Default: 'application/x-www-form-urlencoded; charset=UTF-8'

When sending data to the server, use this content type. Default is “application/x-www-form-urlencoded; charset=UTF-8”, which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

crossDomain

  • Type: Boolean
  • Default: false for same-domain requests, true for cross-domain requests

If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5)

data

  • Type: PlainObject or String or Array

Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL.

When data is an object, jQuery generates the data string from the object’s key/value pairs unless the processData option is set to false. For example, { a: "bc", d: "e,f" } is converted to the string "a=bc&d=e%2Cf". If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.

When data is passed as a string it should already be encoded using the correct encoding for contentType, which by default is application/x-www-form-urlencoded.

In requests with dataType: "json" or dataType: "jsonp", if the string contains a double question mark (??) anywhere in the URL or a single question mark (?) in the query string, it is replaced with a value generated by jQuery that is unique for each copy of the library on the page (e.g. jQuery21406515378922229067_1479880736745).

dataType

  • Type: String
  • Default: Intelligent Guess (xml, json, script, or html)
  • values: “xml”, “html”, “script”, “json”, “jsonp”, “text”

The type of data that you’re expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.

multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType.

headers

  • Type: PlainObject
  • default: {}

An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5)

ifModified

  • Type: Boolean
  • Default: false

Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the ‘etag’ specified by the server to catch unmodified data.

isLocal

  • Type: Boolean
  • Default: depends on current location protocol

Allow the current environment to be recognized as “local,” (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1)

jsonp

  • Type: String or Boolean

Override the callback function name in a JSONP request. This value will be used instead of ‘callback’ in the ‘callback=?’ part of the query string in the url. So {jsonp:’onJSONPLoad’} would result in ‘onJSONPLoad=?’ passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the “?callback” string to the URL or attempting to use “=?” for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: “callbackName” }. If you don’t trust the target of your Ajax requests, consider setting the jsonp property to false for security reasons.

jsonpCallback

  • Type: String or Function()

Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery.

method

  • Type: String
  • Default: 'GET'

mimeType

  • Type: String

A mime type to override the XHR mime type.

password

  • Type: String

A password to be used with XMLHttpRequest in response to an HTTP access authentication request.

processData

  • Type: Boolean
  • Default: true

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type “application/x-www-form-urlencoded”. If you want to send a DOMDocument, or other non-processed data, set this option to false.

scriptAttrs

  • Type: PlainObject

Defines an object with additional attributes to be used in a “script” or “jsonp” request. The key represents the name of the attribute and the value is the attribute’s value. If this object is provided it will force the use of a script-tag transport. For example, this can be used to set nonce, integrity, or crossorigin attributes to satisfy Content Security Policy requirements. (version added: 3.4.0)

scriptCharset

  • Type: String

Only applies when the “script” transport is used. Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. Alternatively, the charset attribute can be specified in scriptAttrs instead, which will also ensure the use of the “script” transport.

timeout

  • Type: Number

Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent.

traditional

  • Type: Boolean

Set this to true if you wish to use the traditional style of param serialization.

traditional=true, param is encoded, traditional=false, params is decoded

var myObject = {
a: {
one: 1,
two: 2,
three: 3
},
b: [ 1, 2, 3 ]
};
var recursiveEncoded = $.param( myObject );
var recursiveDecoded = decodeURIComponent( $.param( myObject ) );
a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3
a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3

type

  • Type: String
  • Default: ‘GET’

An alias for method. You should use type if you’re using versions of jQuery prior to 1.9.0.

url

  • Type: String
  • Default: The current page

A string containing the URL to which the request is sent.

username

  • Type: String

A username to be used with XMLHttpRequest in response to an HTTP access authentication request.

xhr

  • Type: Function()
  • default: ActiveXObject when available (IE), the XMLHttpRequest otherwise

Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.

xhrFields

  • Type: PlainObject

An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
});

Settings for Response

contents

  • Type: PlainObject

An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5)

context

  • Type: PlainObject

This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

converters

  • Type: PlainObject
  • Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}

An object containing dataType-to-dataType converters. Each converter’s value is a function that returns the transformed value of the response. (version added: 1.5)

Settings for Ajax Event

beforeSend

  • Type: Function( jqXHR jqXHR, PlainObject settings )

A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request.

complete

  • Type: Function( jqXHR jqXHR, String textStatus )

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

dataFilter

  • Type: Function( String data, String type ) => Anything

A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the ‘dataType’ parameter.

error

  • Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are “timeout”, “error”, “abort”, and “parsererror”. When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as “Not Found” or “Internal Server Error.” (in HTTP/2 it may instead be an empty string) As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.

statusCode

  • Type: PlainObject
  • Default: {}

An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});

success

  • Type: Function( Anything data, String textStatus, jqXHR jqXHR )

A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.

Settings for Global Ajax Event

global

  • Type: Boolean
  • default: true

Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered.

The jqXHR Object

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser’s native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

overrideMimeType()

As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:

$.ajax({
url: "https://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});

Promise interface

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

  • jqXHR.done(function( data, textStatus, jqXHR ) {});

    An alternative construct to the success callback option, refer to deferred.done() for implementation details.

  • jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

    An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

  • jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); (added in jQuery 1.6)

    An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

    In response to a successful request, the function’s arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

  • jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

    Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:

  • readyState
  • responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
  • status
  • statusText (may be an empty string in HTTP/2)
  • abort( [ statusText ] )
  • getAllResponseHeaders() as a string
  • getResponseHeader( name )
  • overrideMimeType( mimeType )
  • setRequestHeader( name, value ) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
  • statusCode( callbacksByStatusCode )

No onreadystatechange mechanism is provided, however, since done, fail, always, and statusCode cover all conceivable requirements.

Data Type

Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.

The available data types are text, html, xml, json, jsonp, and script.

If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.

If xml is specified, the response is parsed using jQuery.parseXML before being passed, as an XMLDocument, to the success handler. The XML document is made available through the responseXML property of the jqXHR object.

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

If script is specified, $.ajax() will execute the JavaScript that is received from the server before passing it on to the success handler as a string.

If jsonp is specified, $.ajax() will automatically append a query string parameter of (by default) callback=? to the URL. The jsonp and jsonpCallback properties of the settings passed to $.ajax() can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. $.ajax() will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the $.ajax() success handler.

Sending Data to the Server

By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.

Additional Notes

  • Due to browser security restrictions, most “Ajax” requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
  • Script and JSONP requests are not subject to the same origin policy restrictions.

Global Ajax Event Handlers

These methods register handlers to be called when certain events, such as initialization or completion, take place for any Ajax request on the page. The global events are fired on each Ajax request if the global property in jQuery.ajaxSetup() is true, which it is by default. Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.

  • .ajaxStart(), Register a handler to be called when the first Ajax request begins. This is an Ajax Event.
  • .ajaxSend(), Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.
  • .ajaxStop(), Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.
  • .ajaxComplete(), Register a handler to be called when Ajax requests complete. This is an AjaxEvent.
  • .ajaxError(), Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.
  • .ajaxSuccess(), Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.

Helper Functions

These functions assist with common idioms encountered when performing Ajax tasks.

  • jQuery.param(), Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.
  • .serialize(), Encode a set of form elements as a string for submission.
  • .serializeArray(), Encode a set of form elements as an array of names and values.

Low-Level Interface

These methods can be used to make arbitrary Ajax requests.

jQuery.ajax()

Perform an asynchronous HTTP (Ajax) request.

jQuery.ajaxPrefilter()

Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().

jQuery.ajaxSetup()

Set default values for future Ajax requests. Its use is not recommended.

jQuery.ajaxTransport()

Creates an object that handles the actual transmission of Ajax data.

Shorthand Methods

These methods perform the more common types of Ajax requests in less code.

jQuery.get()

Load data from the server using a HTTP GET request.

jQuery.getJSON()

Load JSON-encoded data from the server using a GET HTTP request.

jQuery.getScript()

Load a JavaScript file from the server using a GET HTTP request, then execute it.

jQuery.post()

Send data to the server using a HTTP POST request.

.load()

Load data from the server and place the returned HTML into the matched elements.

Request Data Handling

Query String

// by processData
$.ajax({
url: url,
type: 'GET',
processData: true, // default: true
data: {JSON_object}
});

or

// by $.param(data)
$.ajax({
url: url + '?' + $.param(data),
type: 'xxx'
});

Request Body JSON

// data: JSON_string
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
data: {JSON_string}
});

or

// data: JSON_object, processData: false
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json',
processData: false, // default: true
data: {JSON_object}
});

FormData

Ajax request with application/x-www-form-urlencoded

// data: form.serialize(), processData: false
$.ajax({
url: url,
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
processData: false, // default: true
data: form.serialize()
});

or

// data: {JSON_object}, processData: true
$.ajax({
url: url,
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
processData: true, // default: true
data: {JSON_object}
});

Ajax request with multipart/form-data

// data: formdata, processData: false
$.ajax({
url: url,
type: 'POST',
contentType: 'multipart/form-data',
processData: false, // default: true
data: formdata
});

References

[1] jQuery API Documentation

Backend

Design

  • Class hierarchy design.

Global Functions

  • Core
    • For user
      • Authentication and authorization(menu, privilege, data scope). Sign in and sign out. Session Expiration Time. User, role, privilege. Data privilege and operation privilege.
      • File upload and download.
      • Scheduling Tasks.
    • For system
      • Exception handling. Error message encapsulation.
      • Logging. Method logging with AOP and annotations.
      • Cache handling.
      • Concurrency and asynchronization.
      • Testing. Unit testing.
      • HTTP clients
  • Others
    • For user
      • File online preview.
      • File conversion.
      • SSO (Single Sign on)
      • Web Socket and browser notification. Push messages to client browser pages. (implemented by WebSocket or Ajax loop call)
      • Workflow.
      • I18n (database value, Java string value, JSP element value)
      • Full-text Search by Elasticserach.
    • For system
      • Filter error request.
      • Enable CORS(Cross-Origin Resource Sharing) on server-side.
      • Prevent duplicate form submission.
      • Using multiple data sources.
      • Performance optimization. For example, MySQL optimization. Indexing, optimizing schema and SQL. JVM optimization.
      • Data import into and export from MySQL and Elasticsearch.
      • Third party API access.
      • HTTPS.
      • Reverse Proxy Server.
      • DevOps. Git Flow, code review, test, package, deployment.
      • Crawler and anti-cralwer.

Module Functions

  • RESTful API. CRUD API + UI pages (single table, left tree right table, one-to-many nested tables)

    • Request parameters to POJO. E.g. spring framework@ModelAttribute, @RequestBody.
    • Data validation. E.g. spring framework@Validated).
    • Type conversion. E.g. spring framework @DateTimeFormat for datetime, @JsonSerialize for enumeration).
    • Data formatting. E.g. spring framework @JsonFormat for datetime, @JsonValue form enumeration).
    • Service transaction.
    • Persistence. CRUD.
  • Table data import from and export to Excel file.

  • Aggregation query (SQL, ES) and UI charts.

  • Unit tests.

Frontend

Basic UI Components

  • Top bar <header>. (Logo, website name, user center link, login/logout)
  • Horizontal navigation bar <nav>.
  • Left vertical sidebar menu <aside>.
  • Breadcrumb.
  • Content area <main>, <section>, <article>. (Search, Table and pagination, Form)
  • Bottom footer <footer>.

Global Functions

  • Copy text.
  • View bigger picture.
  • Prevent duplicate form submission.
  • Redirect to another page.
  • Send CRUD HTTP requests. Submit form.
  • Initialize operation privilege.
  • Load components.
  • File structure. Separated index, edit, view page.
  • Alert success and error message.
  • Send CORS Ajax request with jQuery.
  • Send browser notifications.

Module Functions

  • List page
    • Initialize operation privilege.
    • Initialize index page. Display breadcrumb, load search area elements (input, select, date time picker), display operation buttons row, load table and pagination, additionally, may load left area tree.
    • Index page add, edit, delete, search, import/export buttons bind events.
    • Search. Send request with form serialize or FormData.
    • Delete rows.
  • Edit page
    • Initialize edit page title, form elements, and submit button. Form elements: input, radio, checkbox, select, select picker, file, rich text editor, date time picker, and input tags.
    • Add edit page bind events.
    • Form data validation. Show error messages.
    • Save or update. Submit form, send request with FormData or JSON.
  • Other page
    • Statistical charts.
    • Complex page layout and style.

References

Semantic Elements in HTML

Introduction

cron is a UNIX tool that has been around for a long time, so its scheduling capabilities are powerful and proven.

The software utility cron also known as cron job is a time-based job scheduler in Unix-like computer operating systems. Users that set up and maintain software environments use cron to schedule jobs (commands or shell scripts) to run periodically at fixed times, dates, or intervals. It typically automates system maintenance or administration—though its general-purpose nature makes it useful for things like downloading files from the Internet and downloading email at regular intervals. The origin of the name cron is from the Greek word for time, χρόνος (chronos).

Cron is most suitable for scheduling repetitive tasks. Scheduling one-time tasks can be accomplished using the associated at utility.

Format

A cron expression is a string comprised of 6 or 7 fields separated by white space.

second, minute, hour, day of month, month, day(s) of week

Fields can contain any of the allowed values, along with various combinations of the allowed special characters for that field. The fields are as follows:

Field Name Mandatory Allowed Values Allowed Special Characters
Seconds YES 0-59 , - * /
Minutes YES 0-59 , - * /
Hours YES 0-23 , - * /
Day of month YES 1-31 , - * ? / L W
Month YES 1-12 or JAN-DEC , - * /
Day of week YES 1-7 or SUN-SAT , - * ? / L #
Year NO empty, 1970-2099 , - * /

So cron expressions can be as simple as this: * * * * ? *

or more complex, like this: 0/5 14,18,3-39,52 * ? JAN,MAR,SEP MON-FRI 2002-2010

Special characters

  • * (“all values”) - used to select all values within a field. For example, “*****” in the minute field means “every minute”.
  • ? (“no specific value”) - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but don’t care what day of the week that happens to be, I would put “10” in the day-of-month field, and “?” in the day-of-week field.

Note: ‘?’ can only be specfied for Day-of-Month or Day-of-Week.

  • - - used to specify ranges. For example, “10-12” in the hour field means “the hours 10, 11 and 12”.
  • , - used to specify additional values. For example, “MON,WED,FRI” in the day-of-week field means “the days Monday, Wednesday, and Friday”.
  • / - used to specify increments. For example, “0/15” in the seconds field means “the seconds 0, 15, 30, and 45”. And “5/15” in the seconds field means “the seconds 5, 20, 35, and 50”. You can also specify ‘/’ after the ‘’ character - in this case ‘’ is equivalent to having ‘0’ before the ‘/’. ‘1/3’ in the day-of-month field means “fire every 3 days starting on the first day of the month”.
  • L (“last”) - has different meaning in each of the two fields in which it is allowed. For example, the value “L” in the day-of-month field means “the last day of the month” - day 31 for January, day 28 for February on non-leap years. If used in the day-of-week field by itself, it simply means “7” or “SAT”. But if used in the day-of-week field after another value, it means “the last xxx day of the month” - for example “6L” means “the last friday of the month”. You can also specify an offset from the last day of the month, such as “L-3” which would mean the third-to-last day of the calendar month. When using the ‘L’ option, it is important not to specify lists, or ranges of values, as you’ll get confusing/unexpected results.
  • W (“weekday”) - used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify “15W” as the value for the day-of-month field, the meaning is: “the nearest weekday to the 15th of the month”. So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you specify “1W” as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not ‘jump’ over the boundary of a month’s days. The ‘W’ character can only be specified when the day-of-month is a single day, not a range or list of days.

The ‘L’ and ‘W’ characters can also be combined in the day-of-month field to yield ‘LW’, which translates to *“last weekday of the month”*.

  • # - used to specify “the nth” XXX day of the month. For example, the value of “6#3” in the day-of-week field means “the third Friday of the month” (day 6 = Friday and “#3” = the 3rd one in the month). Other examples: “2#1” = the first Monday of the month and “4#5” = the fifth Wednesday of the month. Note that if you specify “#5” and there is not 5 of the given day-of-week in the month, then no firing will occur that month.

The legal characters and the names of months and days of the week are not case sensitive. MON is the same as mon.

Examples

Expression Meaning
0 0 12 * * ? Fire at 12pm (noon) every day
0 15 10 ? * * Fire at 10:15am every day
0 15 10 * * ? Fire at 10:15am every day
0 15 10 * * ? * Fire at 10:15am every day
0 15 10 * * ? 2005 Fire at 10:15am every day during the year 2005
0 * 14 * * ? Fire every minute starting at 2pm and ending at 2:59pm, every day
0 */1 * * * ? Fire every minute starting at 0 second, every day
0 0/5 14 * * ? Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day
0 0/5 14,18 * * ? Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day
0 0-5 14 * * ? Fire every minute starting at 2pm and ending at 2:05pm, every day
0 10,44 14 ? 3 WED Fire at 2:10pm and at 2:44pm every Wednesday in the month of March.
0 15 10 ? * MON-FRI Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday
0 15 10 15 * ? Fire at 10:15am on the 15th day of every month
0 15 10 L * ? Fire at 10:15am on the last day of every month
0 15 10 L-2 * ? Fire at 10:15am on the 2nd-to-last last day of every month
0 15 10 ? * 6L Fire at 10:15am on the last Friday of every month
0 15 10 ? * 6L Fire at 10:15am on the last Friday of every month
0 15 10 ? * 6L 2002-2005 Fire at 10:15am on every last friday of every month during the years 2002, 2003, 2004 and 2005
0 15 10 ? * 6#3 Fire at 10:15am on the third Friday of every month
0 0 12 1/5 * ? Fire at 12pm (noon) every 5 days every month, starting on the first day of the month.
0 11 11 11 11 ? Fire every November 11th at 11:11am.

Generators

Cron Expression Generator - freeformatter

References

[1] cron - Wikipedia

[2] Cron Trigger Tutorial

[3] Scheduling Tasks - Spring

Configuring OS Environments

Configuring Environments on Windows

  1. Add environment variable JAVA_HOME={jdk11_path}.
  2. Add %JAVA_HOME%\bin to the environment variable path.
  3. Verify Java version. $ java -version.
  4. Restart IDE.

Note: After updating the JAVA_HOME environment variable, you need to restart your IDE.

Configuring Maven Project pom.xml

By default your version of Maven might use an old version of the maven-compiler-plugin that is not compatible with Java 9 or later versions. To target Java 9 or later, you should at least use version 3.6.0 of the maven-compiler-plugin and set the maven.compiler.release property to the Java release you are targetting (e.g. 9, 10, 11, 12, etc.). [1]

<properties>
<maven.compiler.release>11</maven.compiler.release>
</properties>

<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>

or

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>

Configuring IDE

Configuring Java 11 for IntelliJ IDEA

  1. Open Project Settings (Ctrl + Shift + Alt + S) –> Project –> Project SDK: 11, Project language level: 11.
  2. Open Settings (Ctrl + Alt + S) –> Build, Execution, Deployment –> Compiler –> Java Compiler –> Project bytecode version: 11

Verification

Running test

$ mvn test

References

[1] Maven in 5 Minutes

CSS Colors

Colors in CSS can be specified by the following methods:

  • Hexadecimal colors
  • Hexadecimal colors with transparency
  • RGB colors
  • RGBA colors
  • HSL colors
  • HSLA colors
  • Predefined/Cross-browser color names
  • With the currentcolor keyword

Hexadecimal Colors

A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue) hexadecimal integers specify the components of the color. All values must be between 00 and FF.

For example, the #0000ff value is rendered as blue, because the blue component is set to its highest value (ff) and the others are set to 00.

#p1 {background-color: #ff0000;}   /* red */
#p2 {background-color: #00ff00;} /* green */
#p3 {background-color: #0000ff;} /* blue */

Hexadecimal Colors With Transparency

A hexadecimal color is specified with: #RRGGBB. To add transparency, add two additional digits between 00 and FF.

#p1a {background-color: #ff000080;}   /* red transparency */
#p2a {background-color: #00ff0080;} /* green transparency */
#p3a {background-color: #0000ff80;} /* blue transparency */

RGB Colors

An RGB color value is specified with the rgb() function, which has the following syntax:

rgb(red, green, blue)

Each parameter (red, green, and blue) defines the intensity of the color and can be an integer between 0 and 255 or a percentage value (from 0% to 100%).

For example, the rgb(0,0,255) value is rendered as blue, because the blue parameter is set to its highest value (255) and the others are set to 0.

Also, the following values define equal color: rgb(0,0,255) and rgb(0%,0%,100%).

#p1 {background-color: rgb(255, 0, 0);}   /* red */
#p2 {background-color: rgb(0, 255, 0);} /* green */
#p3 {background-color: rgb(0, 0, 255);} /* blue */

RGBA Colors

RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity of the object.

An RGBA color is specified with the rgba() function, which has the following syntax:

rgba(red, green, blue, alpha)

The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

#p1 {background-color: rgba(255, 0, 0, 0.3);}   /* red with opacity */
#p2 {background-color: rgba(0, 255, 0, 0.3);} /* green with opacity */
#p3 {background-color: rgba(0, 0, 255, 0.3);} /* blue with opacity */

HSL Colors

HSL stands for hue, saturation, and lightness - and represents a cylindrical-coordinate representation of colors.

HSLA Colors

HSLA color values are an extension of HSL color values with an alpha channel - which specifies the opacity of the object.

Predefined/Cross-browser Color Names

140 color names are predefined in the HTML and CSS color specification.

For example: blue, red, coral, brown, etc:

#p1 {background-color: blue;}
#p2 {background-color: red;}
#p3 {background-color: coral;}

The currentcolor Keyword

The currentcolor keyword refers to the value of the color property of an element.

#myDIV {
color: blue; /* Blue text color */
border: 10px solid currentcolor; /* Blue border color */
}

Color Schemes

  • Achromatic Color Schemes
  • Monochromatic Color Schemes. Monochromatic schemes use different tones from the same angle on the color wheel (the same hue).
  • Analogous Color Schemes. Analogous color schemes are created by using colors that are next to each other on the color wheel.
  • Complementary Color Schemes. Complementary schemes are created by combining colors from opposite sides of the color wheel.
  • Triadic. Triadic schemes are made up of hues equally spaced around color wheel.
  • Compound (aka Split Complementary) Color Scheme. Compound schemes are almost the same as complementary schemes. Instead of using colors that are opposites, it uses colors on both sides of the opposite hue.

Color Psychology

  • Colors can influence human behavior.
  • Colors can influence human perceptions.
  • Colors can influence the taste of food.
  • Colors can influence attractiveness.
RED
Red attracts the human eye

Energy: power, strength, excitement.

Danger: fire, blood, urgency, traffic stop.

Passion: appetite, emotion, love.

GREEN
Green is the most restful color

Nature: Fertility, Freshness, New Growth.

Safety: Good Health, Healing Power, Free Traffic.

Harmony: Peace, Easiness, Calmness.

BLUE
Blue is the most used office color

Sea: Water, Ocean, Depth, Wealth.

Quality: Stability, Conservatism, Productivity, Wisdom, Intelligence.

Sky: Truth, Peace, Heaven.

Yellow
Yellow is a Happy Color

Sunshine: Light, Clarity, Energy, Warmth.

Optimism: Happiness, Positivity, Cheerfulness, Youngfulness.

Black
Black is Authority and Mystery

Authority: Power, Elegance, Formality.

Mystery: Evil, Fear, Death.

Gray
Grey is Conservative

Security
Reliability
Classic Knowledge
Professional Wisdom

White
White is Purity
Cleanliness Neutrality Goodness Innocence

Common Colors

  • Color Names Supported by All Browsers
  • Color Groups
  • Color Shades
  • Fashion Color

Color Names Supported by All Browsers

Color Names Supported by All Browsers

Color Groups

HTML Color Groups

2014 Material Design color palettes

The color system - Material Design

Shades of Gray

Gray Shades HEX RGB
HTML Black #000000 rgb(0,0,0)
#080808 rgb(8,8,8)
#101010 rgb(16,16,16)
#181818 rgb(24,24,24)
#202020 rgb(32,32,32)
#282828 rgb(40,40,40)
#303030 rgb(48,48,48)
#383838 rgb(56,56,56)
#404040 rgb(64,64,64)
#484848 rgb(72,72,72)
#505050 rgb(80,80,80)
#585858 rgb(88,88,88)
#606060 rgb(96,96,96)
#686868 rgb(104,104,104)
#696969 rgb(105,105,105)
#707070 rgb(112,112,112)
#787878 rgb(120,120,120)
HTML Gray #808080 rgb(128,128,128)
#888888 rgb(136,136,136)
#909090 rgb(144,144,144)
#989898 rgb(152,152,152)
#A0A0A0 rgb(160,160,160)
#A8A8A8 rgb(168,168,168)
HTML DarkGray !!! #A9A9A9 rgb(169,169,169)
#B0B0B0 rgb(176,176,176)
#B8B8B8 rgb(184,184,184)
X11 Gray #BEBEBE rgb(190,190,190)
HTML Silver #C0C0C0 rgb(192,192,192)
#C8C8C8 rgb(200,200,200)
#D0D0D0 rgb(208,208,208)
HTML LightGray #D3D3D3 rgb(211,211,211)
#D8D8D8 rgb(216,216,216)
HTML Gainsboro #DCDCDC rgb(220,220,220)
#E0E0E0 rgb(224,224,224)
#E8E8E8 rgb(232,232,232)
#F0F0F0 rgb(240,240,240)
HTML WhiteSmoke #F5F5F5 rgb(245,245,245)
#F8F8F8 rgb(248,248,248)
HTML White #FFFFFF rgb(255,255,255)

Colors for Alerts

Display Dangers

Danger!

Red often indicates a dangerous or negative situation.

HEX: #FFDDDD

Danger!

Red often indicates a dangerous or negative situation.

HEX: #F44336

Display Warnings

Warning!

Yellow often indicates a warning that might need attention.

HEX: #FFFFCC

Warning!

Yellow often indicates a warning that might need attention.

HEX: #FFEB3B

Display Successs

Success!

Green often indicates something successful or positive.

HEX: #DDFFDD

Success!

Green often indicates something successful or positive.

HEX: #4CAF50

Display Information

Info!

Blue often indicates a neutral informative change or action.

HEX: #DDFFFF

Info!

Blue often indicates a neutral informative change or action.

HEX: #2196F3

More alert colors

Danger!

Red often indicates a dangerous or negative situation.

HEX: #E91E63

Danger!

Red often indicates a dangerous or negative situation.

HEX: #FF9800

Danger!

Red often indicates a dangerous or negative situation.

HEX: #FF5722

Danger!

Red often indicates a dangerous or negative situation.

HEX: #607D8B

Danger!

Red often indicates a dangerous or negative situation.

HEX: #FFC107

Fashion Colors

2019 - Living Coral
HEX: #FF6F61
PANTONE 16-1546
2018 - Ultra Violet
HEX: #6B5B95
PANTONE 18-3838
2017 Greenery
Hex #88B04B
RGB(136, 176, 75)
Pantone 15-0343
2016 Rose Quartz
Hex #F7CAC9
RGB(247, 202, 201)
Pantone 13-1520
2016 Serenity
Hex #92A8D1
RGB(146, 168, 209)
Pantone 15-3919
2015 Marsala
Hex #955251
RGB(149, 82, 81)
Pantone 18-1438
2014 Radiand Orchid
Hex #B565A7
RGB(181, 101, 167)
Pantone 18-3224
2013 Emerald
Hex #009B77
RGB(0, 155, 119)
Pantone 17-5641
2012 Tangerine Tango
Hex #DD4124
RGB(221, 65, 36)
Pantone 17-1463
2011 Honeysucle
Hex #D65076
RGB(214, 80, 118)
Pantone 18-2120
2010 Turquoise
Hex #45B8AC
RGB(68, 184, 172)
Pantone 15-5510
2009 Mimosa
Hex #EFC050
RGB(239, 192, 80)
Pantone 14-0848
2008 Blue Izis
Hex #5B5EA6
RGB(91, 94, 166)
Pantone 18-3943
2007 Chili Pepper
Hex #9B2335
RGB(155, 35, 53)
Pantone 19-1557
2006 Sand Dollar
Hex #DFCFBE
RGB(223, 207, 190)
Pantone 13-1106
2005 Blue Turquoise
Hex #55B4B0
RGB(85, 180, 176)
Pantone 15-5217
2004 Tigerlily
Hex #E15D44
RGB(225, 93, 68)
Pantone 17-1456
2003 Aqua Sky
Hex #7FCDCD
RGB(127, 205, 205)
Pantone 14-4811
2002 True Red
Hex #BC243C
RGB(188, 36, 60)
Pantone 19-1664
2001 Fuchsia Rose
Hex #C3447A
RGB(195, 68, 122)
Pantone 17-2031
2000 Cerulean Blue
Hex #98B4D4
RGB(152, 180, 212)
Pantone 15-4020

Appendixes

Online Tools

References

CSS Colors

Color Schemes, Psychology

Common Colors

Basics

Types of Boxes

CSS display types (types of boxes):

  • block
  • inline
  • inline-block.
New Line Horizontal Space Actual Width Height Margin Padding
Block elements Always starts on a new line Always occupy the entire horizontal space. 100% by default. You can specify width. Height of content by default. Can specify height. OK OK
Inline elements Don’t start on a new line Width of content. width of content by default. Can’t specify width. Height of content by default. Can’t specify height. Horizontal margin is OK. But vertical margin don’t work. Horizontal padding is OK. But vertical padding don’t occupy space just overlay.
Inline-Block elements Don’t start on a new line Width of content by default. Or specified width. width of content by default. You can specify width. Same with “Block elements” Same with “Block elements” Same with “Block elements”

Height and Width

Width

  • 宽度一般不设置,用内容本身去撑(动态宽度)。也可以设置固定的宽度,使用百分比宽度。
  • 用 padding/margin left/right 百分比,去设置两个元素之间的水平间距。

Height

  • 高度一般也不设置,用内容本身撑(动态高度)。
  • 使用 padding/margin top/bottom 固定值,去增加高度。

Align

Horizontal Align

Horizontally center a div

Horizontally center a div using margin auto
margin: auto;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
}
#innerDiv {
background-color: green;
width: 200px;
height: 200px;
margin: auto;
margin-top: 40px;
margin-bottom: 40px;
}
</style>
</head>
<body>
<div>123</div>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
<div>123</div>
</body>
</html>
Horizontally center a div using flexbox in the container
display:flex;
flex-direction:row; /* by default */
justify-content:center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
display:flex;
flex-direction:row; /* by default */
justify-content:center;

}
#innerDiv {
background-color: blue;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
</body>
</html>
Horizontally center a div using transform
/* container */
position: relative;
/* inner div */
position: absolute;
left: 50%;
transform: translate(-50%, 0); /* or transform: translateX(-50%);*/
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container {
position: relative;
height: 400px;
background-color: lightgray;
}

#centeredDiv {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
height: 200px;
width: 200px;
background-color: white;
}
</style>
</head>
<body>
<div id="container">
<div id="centeredDiv">
Content
</div>
</div>
</body>
</html>

Horizontally Center Text

Horizontally center text using text align
text-align: center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#myDiv {
background-color: green;
text-align: center;
}
</style>
</head>
<body>
<div id="myDiv">Content</div>
</body>
</html>
Horizontally center text using flex
display:flex;
flex-direction:row; /* by default */
justify-content:center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#myDiv {
background-color: green;
height: 200px;
display:flex;
flex-direction:row; /* by default */
justify-content:center;
}
</style>
</head>
<body>
<div id="myDiv">Content</div>
</body>
</html>

Align a div to right

Align a div to right using position
position: absolute;
right: 0px;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
position: absolute;
right: 0px;
}
#innerDiv {
background-color: blue;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
</body>
</html>
Align a div to right using float
float: right;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
}
#innerDiv {
background-color: green;
width: 200px;
height: 200px;
float: right;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
</body>
</html>

Align div to left and right

Align a div to left and right using float
<div class="container">
<div class="left-item"></div>
<div class="left-item"></div>
<div class="right-item"></div>
<div class="right-item"></div>
</div>
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.container {
height: 100px;
background-color: gray;
/* fixing overflow outside by adding scroll bar*/
overflow: auto;
}
.container .left-item {
background-color: green;
width: 20%;
height: 200px;
float: left;
margin-right: 10px;
}
.container .right-item {
background-color: blue;
width: 20%;
height: 200px;
float: right;
margin-left: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="left-item">1</div>
<div class="left-item">2</div>
<div class="right-item">3</div>
<div class="right-item">4</div>
</div>
</body>
</html>

Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the “clearfix“ hack to fix this. We can add overflow: auto; to the containing element to fix this problem

Vertical Align

Vertically center a div

Vertically center a div using flexbox in the container

Method 1: using align-items: center

align-items: the direction is across with flex-direction.

display:flex;
flex-direction:row; /* by default*/
align-items:center;

Method 2: using justify-content: center

justify-content: the direction is the same with flex-direction.

display:flex;
flex-direction:column;
justify-content:center;

flex-direction:

  • row (by default, from left to right)
  • row-reverse
  • column (from top to bottom)
  • column-reverse
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
background-color: darkgray;
height: 300px;
display:flex;
flex-direction:row; /* by default */
align-items:center;
}
#outerDiv2 {
background-color: lightgray;
height: 300px;
display:flex;
flex-direction:column;
justify-content:center;
}
#innerDiv {
background-color: green;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
<div id="outerDiv2">
<div id="innerDiv">Content</div>
</div>
</body>
</html>
Vertically center a div using transform
/* container */
position: relative;
/* inner div */
position: absolute;
top: 50%;
transform: translate(0, -50%); /* or transform: translateY(-50%);*/
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container {
position: relative;
height: 400px;
background-color: lightgray;
}

#centeredDiv {
position: absolute;
top: 50%;
transform: translate(0, -50%);
height: 200px;
width: 200px;
background-color: white;
}
</style>
</head>
<body>
<div id="container">
<div id="centeredDiv">
Content
</div>
</div>
</body>
</html>

Vertically center text

Vertically center text using line height

Only center a single line text vertically

height: 150px;
line-height: 150px;
Details
<style type="text/css">
#myDiv {
background-color: green;
width: 200px;
height: 150px;
line-height: 150px;
}
</style>

<div id="myDiv">Content</div>
Vertically center text using vertical-align + table-cell

Center multiple lines text vertically

#innerDiv {
display:table-cell;
vertical-align:middle;
}
Details
<style type="text/css">
#myDiv {
background-color: green;
height:400px;
width:150px;
display:table-cell;
vertical-align:middle;
}
</style>

<div id="myDiv">this is multiple lines. this is multiple lines. this is multiple lines. this is multiple lines. this is multiple lines. this is multiple lines. this is multiple lines. </div>
Vertically center text using padding

Using padding in no height a div.

padding-top: 50px;
padding-bottom: 50px;
Details
<style type="text/css">
#myDiv {
background-color: green;
width: 200px;
padding-top: 100px;
padding-bottom: 100px;
}
</style>

<div id="myDiv">Content</div>
Vertically center text using flex
display:flex;
flex-direction:row; /* by default */
align-items:center;
Details
<style type="text/css">
#myDiv {
background-color: blue;
width: 200px;
height: 200px;
display:flex;
flex-direction:row; /* by default */
align-items:center;
}
</style>

<div id="myDiv">Content</div>
Vertically center text by center a inner div vertically

Horizontal and vertical Align

Horizontally and vertically center a div

Using flex
display:flex;
flex-direction:row; /* by default */
justify-content:center;
align-items: center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outerDiv {
height: 500px;
background-color: darkgray;
display:flex;
flex-direction:row; /* by default */
justify-content:center;
align-items: center;
}
#innerDiv {
background-color: blue;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="outerDiv">
<div id="innerDiv">Content</div>
</div>
</body>
</html>
Using transform
/* container */
position: relative;
/* inner div */
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#container {
position: relative;
height: 400px;
background-color: lightgray;
}

#centeredDiv {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
height: 200px;
width: 200px;
background-color: white;
}
</style>
</head>
<body>
<div id="container">
<div id="centeredDiv">
Content
</div>
</div>
</body>
</html>

Horizontally and vertically center text

Using flex
display:flex;
flex-direction:row; /* by default */
justify-content:center;
align-items: center;
Details
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#myDiv {
background-color: green;
height: 200px;
display:flex;
flex-direction:row; /* by default */
justify-content:center;
align-items: center;
}
</style>
</head>
<body>
<div id="myDiv">Content</div>
</body>
</html>

Layout

Multiple div in one line

float:left (or right);
display:inline-block;
display:flex;

Dynamic Layout

Inline elements in a block element auto wrapping lines until decrease to the block minimal width:

min-width: {fixed_value}

Break Word

  • word-break: normal; // newline for words
  • word-break: break-all; // newline for characters
  • word-break: keep-all; // don’t newline
  • word-break: break-word; // newline for words, if a single word over the block width then newline for character. Deprecated. Using word-break: normal and overflow-wrap: anywhere replace word-break: break-word.

Common CSS

first-of-type and first-child

  • xxx:first-of-type: match the first of selector occur from a parent.
  • xxx:nth-of-type(1)
  • xxx:last-of-type
  • xxx:nth-last-of-type(1)
  • xxx:first-child : match when the first of child of a parent is the selector.
  • xxx:nth-child(1)
<div class="column">
<div class="row">I am .row:first-of-child.</div>
<div class="row">this is a lines. </div>
<div class="row">this is a lines. </div>
</div>
<div class="column">
<p>I am p:first-of-child</p>
<div class="row">I am .row:first-of-type not .row:first-of-child.</div>
<div class="row">this is a lines. </div>
<div class="row">this is a lines. </div>
</div>

Classic Layout

Multiple columns align left using display: flex;

<style type="text/css">
#content {
display: flex;
flex-direction: row;
}
.column {
background-color: darkgray;
padding: 20px 20px 20px 0px;
}
.column:first-of-type {
padding-left: 20px
}
.row {
background-color: green;
height: 30px;
margin-top: 10px;
}
.row:first-of-type {
margin-top: 0px;
font-weight: bold;
}
</style>

<div id="content">
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
</div>

Multiple columns align left and one column align right using display: flex; and margin-left: auto;

<style type="text/css">
#content {
background-color: darkgray;
width: 100%;
display: flex;
flex-direction: row;
}
.column {
background-color: orange;
padding: 20px 20px 20px 0px;
}
.column:first-of-type {
padding-left: 20px
}
.column:nth-last-of-type(1) {
background-color: red;
margin-left: auto;
}
.row {
background-color: green;
height: 30px;
margin-top: 10px;
}
.row:first-of-type {
margin-top: 0px;
font-weight: bold;
}
</style>

<div id="content">
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
</div>

columns have two directions, some from align left, others align right, using flex-direction: row and flex-direction: row-reverse;

<style type="text/css">
#content {
background-color: darkgray;
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
}
#section1 {
display: flex;
flex-direction: row;
}
#section2 {
display: flex;
flex-direction: row-reverse;
}
.column {
background-color: orange;
padding: 20px 20px 20px 0px;
}
.column:first-of-type {
padding-left: 20px
}
.column:nth-last-of-type(1) {
background-color: red;
}
.row {
background-color: green;
height: 30px;
margin-top: 10px;
}
.row:first-of-type {
margin-top: 0px;
font-weight: bold;
}
</style>

<div id="content">
<div id="section1">
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
</div>
<div id="section2">
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
<div class="column">
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
<div class="row">this is multiple lines. </div>
</div>
</div>
</div>

Common class name

  • row
  • column
  • title
  • content
  • item
  • wrapper
  • menu-bar
  • top, header, footer
  • logo

References

[1] CSS display properties: block, inline, and inline-block — & how to tell the difference

[2] CSS Layout - Horizontal & Vertical Align - w3schools

[3] Aligning Items in a Flex Container

0%