Taogen's Blog

Stay hungry stay foolish.

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()
  • $.load()

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

Errors

ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

Solutions

Check InnoDB status for locks

SHOW ENGINE InnoDB STATUS;

Check MySQL open tables

SHOW OPEN TABLES WHERE In_use > 0;

Check pending InnoDB transactions

for kill slow query by view query SQL statement (trx_query)

SELECT * FROM `information_schema`.`innodb_trx` ORDER BY `trx_started`; 

Check lock dependency - what blocks what

for kill locked query

SELECT * FROM `information_schema`.`innodb_locks`;

Show running threads

get query thread ID

SHOW PROCESSLIST;
SELECT * 
FROM information_schema.processlist
WHERE user <> 'system user' and
COMMAND != 'Sleep'and
info like '%SELECT%'
order by `time` desc;
Id	`User`	Host	db	Command	`Time`	State	Info
  • Id: thread ID.
  • db: database name.
  • Command: Query, Sleep(the session is idle).
  • Time: the time in seconds that the thread has been in its current state. For a replica SQL thread, the value is the number of seconds between the timestamp of the last replicated event and the real time of the replica host.
  • Info: the statement the thread is executing, or NULL if it is executing no statement.

Kill Threads By Thread ID

Kill a Particular Thread

KILL {processlist_id};

get kill all your MySQL queries

SELECT GROUP_CONCAT(CONCAT('KILL ',id,';') SEPARATOR ' ') 
FROM information_schema.processlist
WHERE user <> 'system user' and
COMMAND != 'Sleep'and
info like '%SELECT%';
KILL 1; KILL 2;
SELECT CONCAT('KILL ',id,';') AS kill_list 
FROM information_schema.processlist
WHERE user <> 'system user' and
COMMAND != 'Sleep'and
info like '%SELECT%';
+------------------------+
| kill_list |
+------------------------+
| KILL 1; |
| KILL 2; |
+------------------------+

References

[1] Fixing “Lock wait timeout exceeded; try restarting transaction” for a ‘stuck” Mysql table?

[2] How To Kill MYSQL Queries

[3] 26.3.23 The INFORMATION_SCHEMA PROCESSLIST Table - MySQL

[4] 13.7.8.4 KILL Statement - MySQL

The web page language for displaying is:

  • Not determined by your operating system display language.
  • Not determined by your browser display language.
  • Not determined by the HTTP header Accept-Language.

The web page language for display is determined by the preferred language of your browser. The preferred language list of your browser is the same as your operating system display language or browser display language. But you can set to add your custom preferred language and move it to the top of the list.

Chrome

Chrome settings –> Advanced –> Languages –> Order languages based on your preference –> Add languages –> Move your preferred language for displaying to the top.

Firefox

Options –> General –> Language and Appearance –> Language –> Choose your preferred language for displaying pages –> Choose –> Add your language –> Move your preferred language for displaying to the top.

本文将介绍微信支付开发相关内容,微信支付有很多种途径,本文主要以 JSAPI 支付为例。接下来将介绍微信支付的基础和 JSAPI 支付开发过程。

微信支付的基础

微信支付产品

  • 付款码支付:付款码支付是用户展示微信钱包内的“刷卡条码/二维码”给商户系统扫描后直接完成支付的模式。主要应用线下面对面收银的场景。
  • Native 支付:Native支付是商户系统按微信支付协议生成支付二维码,用户再用微信“扫一扫”完成支付的模式。该模式适用于PC网站支付、实体店单品或订单支付、媒体广告支付等场景。
  • JSAPI支付:JSAPI支付是用户在微信中打开商户的H5页面,商户在H5页面通过调用微信支付提供的JSAPI接口调起微信支付模块完成支付。
  • APP支付:APP支付又称移动端支付,是商户通过在移动端应用APP中集成开放SDK调起微信支付模块完成支付的模式。
  • H5支付:H5支付主要是在手机、ipad等移动设备中通过浏览器来唤起微信支付的支付产品。
  • 小程序支付:小程序支付是专门被定义使用在小程序中的支付产品。目前在小程序中能且只能使用小程序支付的方式来唤起微信支付。

以上不同的微信支付产品对应不同的微信支付系统的 API。其中,线上使用的支付方式:JSAPI 支付,APP 支付,H5 支付。对于在微信公众号内的微信支付,一般使用 JSAPI 支付方式。

常见术语名词解释

  • 微信公众平台:微信公众平台是微信公众账号申请入口和管理后台。商户可以在公众平台提交基本资料、业务资料、财务资料申请开通微信支付功能。
  • 微信开放平台:微信开放平台是商户APP接入微信支付开放接口的申请入口,通过此平台可申请微信APP支付。
  • 微信商户平台:微信商户平台是微信支付相关的商户功能集合,包括参数配置、支付数据查询与统计、在线退款、代金券或立减优惠运营等功能。
  • 微信支付系统:微信支付系统是指完成微信支付流程中涉及的API接口、后台业务处理系统、账务系统、回调通知等系统的总称。
  • 商户证书:商户证书是微信提供的二进制文件,商户系统发起与微信支付后台服务器通信请求的时候,作为微信支付后台识别商户真实身份的凭据。
  • 签名:商户后台和微信支付后台根据相同的密钥和算法生成一个结果,用于校验双方身份合法性。签名的算法由微信支付制定并公开,常用的签名方式有:MD5、SHA1、SHA256、HMAC等。
  • Openid:用户在公众号内的身份标识,不同公众号拥有不同的openid。商户后台系统通过登录授权、支付通知、查询订单等API可获取到用户的openid。主要用途是判断同一个用户,对用户发送客服消息、模版消息等。企业号用户需要使用企业号userid转openid接口与openid互换接口)将企业成员的userid转换成openid。

申请开通微信支付功能

微信公众号商户可以在微信公众平台提交开通微信支付的申请,第三方APP商户可以在微信开放平台提交申请。申请提交后,微信支付工作人员审核资料无误将开通相应的微信支付权限。微信支付申请审核通过后,商户在申请资料填写的邮箱中收取到由微信支付小助手发送的邮件,此邮件包含开发时需要使用的支付账户信息。

  • APPID:appid是微信公众账号或开放平台APP的唯一标识,在公众平台申请公众账号或者在开放平台申请APP账号后,微信会自动分配对应的appid,用于标识该应用。
  • 微信支付商户号 mch_id:商户申请微信支付后,由微信支付分配的商户收款账号。
  • API 密钥:交易过程生成签名的密钥,仅保留在商户系统和微信支付后台,不会在网络中传播。商户妥善保管该Key,切勿在网络中传输,不能在其他客户端中存储,保证key不会被泄漏。
  • Appsecret:AppSecret是APPID对应的接口密码,用于获取接口调用凭证access_token时使用。在微信支付中,先通过OAuth2.0接口获取用户openid,此openid用于微信内网页支付模式下单接口使用。
  • 商户平台登录帐号。
  • 商户平台登录密码。

开通微信支付功能后,会得到额外三个用于开发微信支付的参数:mch_id, API 密钥, Appsecret。这三个参数在调用微信支付系统的 API 时需要用到。

微信 JSAPI 支付开发

微信微信 JSAPI 支付开发前提

  • 申请商户的微信支付账号。商户在微信公众平台或开放平台提交微信支付申请,申请成功后可获取其支付账号的相关参数用于微信支付开发。
  • 设置支付目录。1)商户最后请求拉起微信支付收银台的页面地址我们称之为“支付目录”,例如:https://www.weixin.com/pay.php。2)商户实际的支付目录(支付页面URL)必须和在微信支付商户平台设置的一致。3)如果支付授权目录设置为顶级域名(例如:https://www.weixin.com/ ),那么只校验顶级域名,不校验后缀。
  • 设置授权域名。在统一下单接口中要求必传用户openid,即需要进行网页授权,获取用户信息。

微信支付系统主要提供的 API 和功能

  • 支付下单、查询订单、支付结果通知(微信回调)
  • 申请退款、查询退款、退款通知(微信回调)

详细的 API 列表可参考微信支付官方文档:微信支付 API 列表

微信 JSAPI 支付开发需要的参数

  • 商户号(mch_id)
  • API 密钥(key):交易过程用于生成签名的密钥,仅保留在商户系统和微信支付后台。
  • API 证书(application_cert.pem):微信支付接口中,涉及资金回滚的接口会使用到 API 证书,包括退款、撤销接口。证书文件主要用于退款时发送 SSL 请求。
  • 当然还包括公众平台的参数(appId,appSecret)。

其中公众平台的 appId 与微信支付系统的 mch_id 将公众号应用与微信支付帐号进行了绑定。

微信 JSAPI 支付功能的实现过程

  • 用户发起支付请求。
  • 公众号后端,生成商户自己的订单数据(商户订单号),保存到数据库订单表。
  • 调用微信统一下单API,得到预付单信息(prepay_id)。下单成功后更新数据库订单表。
  • 生成公众号页面调用 JSAPI 支付接口需要的参数并签名(paySign),将参数返回给前端页面。
  • 公众号前端页面,调用 JSAPI 支付接口请求支付。
  • 微信支付系统验证参数的合法性,若参数合法则弹出微信的确认支付的页面。用户输入支付密码,密码验证通过后会跳转到微信的支付成功页面,并同时发起微信支付的回调。
  • 在支付成功页面点击返回商家,跳转到商户指定的页面。商户系统后端调用微信订单查询 API,查询支付结果,生成商户自己的支付结果页面。
  • 公众号后端,处理微信支付的回调。进行业务处理后,返回处理结果给微信支付系统。

详细业务流程可参考微信支付官方文档:JSAPI 支付业务流程时序图

公众号网页调用 JSSDK 支付接口(调起微信支付)

可以使用微信 JSSDK 的支付 API。也可以使用微信支付封装的JS方法。

1)JSSDK 发起支付请求

wx.ready(function(
// auto execution
wx.chooseWXPay({
timestamp: 0, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
nonceStr: '', // 支付签名随机串,不长于 32
package: '', // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
signType: '', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: '', // 支付签名
success: function (res) {
// 支付成功后的回调函数
}
});
));

2)微信支付平台封装的方法

<script>
function onBridgeReady(){
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId":"wx2421b1c4370ec43b", //公众号名称,由商户传入
"timeStamp":"1395712654", //时间戳,自1970年以来的秒数
"nonceStr":"e61463f8efa94090b1f366cccfbbb444", //随机串
"package":"prepay_id=u802345jgfjsdfgsdg888",
"signType":"MD5", //微信签名方式:
"paySign":"70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名
},
function(res){
if(res.err_msg == "get_brand_wcpay_request:ok" ){
// 使用以上方式判断前端返回,微信团队郑重提示:
//res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
}
});
}

if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
}
}else{
onBridgeReady();
}
</script>

注意事项

微信支付需要在微信APP中调试,不能在微信开发者工具中调试。

References

[1] 微信支付V2版API接口文档

[2] 微信支付开发文档3.0

0%