CORS – How to allow origin by domain using wildcard operator

Create a filter class for enabling CORS

CORS ( Cross-Origin Resource Sharing ) is a mechanism provided by modern web browser to allow cross-site HTTP requests like XmlHttpRequest (Ex. Ajax).

This article does not cover discussions and articles about the CORS standard, – for which we refer to Wikipedia or MSDN article – instead we’ll show an example in Java on how dinamically enable CORS and send back the information to the client browser.

an XmlHttpRequest request

According the above scenario, our CORS filter must intercept the Origin value contained on the HEAD part of the request sent by the client.

Configure allowed site or domains

On the web application’s properties file, add a dedicated key where insert thrusted domain.

Something like this:

cors.domain.supported = *

Then consider writing a class that implements a javax.servlet.Filter.

public class ApiOriginFilter implements Filter {

	ConfigService config;
	Logger logger;
	static String origins;
	static Pattern pattern;
	public void init(FilterConfig filterConfig) throws ServletException {
		origins = config.getProperty("cors.domain.supported");
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException 
		if (StringUtils.isNotEmpty(origins))
			String[] list = origins.split(",");
			HttpServletRequest httpServletRequest = (HttpServletRequest)request;
			String origin = httpServletRequest.getHeader("Origin");
			logger.debug("origin: {}", origin);
			if (StringUtils.isNotEmpty(origin))
				for (String item : list) {
					String input = item.trim();
					String regex = "^"   input.replace("*", ".*")   "(?::d )$";
					Pattern pattern = Pattern.compile(regex);
					Matcher matcher = pattern.matcher(origin);
					if (matcher.find())
						String output =;
			"origin allowed: {}", output);
						HttpServletResponse httpServletResponse = (HttpServletResponse) response;
						httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
						httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
						httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");
		chain.doFilter(request, response);


	public void destroy() {


Notice that if you are developting with REST API and JAX-RS 2.0, a better choice would be to implement ContainerResponseFilter class instead.

Test on local environment

In order to test ajax call on the same local environment, a simple way is to edit OS host’s file by adding a line:

Then every XHRequest will point to[service_address].

Ractive.js – Create a droppable image div component with configurable size property

This example shows how to create a drag & drop image container with a configurable width and height; example’s requirements are jQuery and Ractive.js.

Download code

First off, let’s make a preview of what the user see when the page load:



To display the page above, the developer has just to write the following code:

Ractive.js allows creating component for reusing in any web application.

The code for the image drag & drop div component is the following:


The viewmodel will initialize the component and the page itself with the data to display; furthermore, the component fires an event ‘imagerefused’ in case the image dropped does not satisfy the width / height requirements specified in the imageuploader component, so it’s up to the viewmodel to catch and display a properly message.


Here’s the final result:


image uploader


Ractive.js – Tutorial for applying templating and viewmodel pattern

Decouple view and model layer with Ractive.js

I recently needed a javascript template library for some projects in which I am involved, so I gave a look into web for some suggestions.

I must say Ractive.js impressed me for the ease of use as well as the small learning curve; furthermore is not invasive and can be used with other libraries.

With Ractive.js is possible to apply the ViewModel pattern and apply the separation of view and model layer throught binding; it is also possible to build decorators, components and other stuff that incapsulate the logic inside a reusable script code.

In order to show what are the main differences between the code with and without RactiveJS, I’ll show a simple example:

An html page that contains

two input text
a submit button
a warning message on empty value

The validation rules are simple:
the submit message is disabled until the two input are empty


Code without Ractive.js

This is the html body section, nothing to say about it 🙂

The logic script code shown below basically check if name and surname values are empty, and if not, the submit button enable itself; there is also a message for each input that warn the user to enter some value.

If your take a look to the comments //, you will agree that there are pieces of code that are coupled with the view layer, because it is needed to take value from elements by their id and either because of the call to jQuery UI functions (i.e. node.button() ).

In a typical MVVM pattern situation, this doesn’t happen, because viewmodel must NOT know of the view part.

This is where Ractive.js does the matter.

Code with Ractive.js

Take a look to the following code:

You will notice some expressions inside braces {{ }}; looking with a more accurate eye, some id element’s attributes disappeared, more likely because they are not referenced anymore.

{{name}} and {{surname}} are the binded name (or keypath) that belongs from the viewmodel object, that is the effective datacontext of this view.
An inverted section begins with a caret (hat) and ends with a slash. So {{^name}} can be traslated in (if not name then), that is all the code within the bracets will be displayed ONLY if name is empty.

Finally, there is a odd attribute named “decorator” inside the submit button; we’ll take care ahead this article.

The logic section is pretty interesting because totally avoids any reference to the view part, instead it only takes care of the model and pure logic part (if any).

Notice the ractive observe directive watch for any change of the value, and not for the change event of the node (in which  you should use proxy events like on-change).

All logic that involve the view components (like showing or disabling elements) is relied only on the html and not the model so the two layers are good decoupled.

Now you are wondering where are the calls to jQuery UI buttons; for this purpose I created a dedicated decorator to deal with jQuery UI components that is reusable for most of my future web applications.

The code for jQuery button decorator is the following:

Basically, once the button element is rendered this decorator call button() to its attached node.

Internally, a MutationObserver check for any change in the state of the node, in this case properly filtered with ‘disabled’ attribute, and then call for button(‘enable|disable’).

Final considerations

Learning fundamentals of Ractive.js can be more easier with the  interactive tutorial that provides to user a valid base to begin. Separation of layer concepts, data binding and build of components make it sometimes fun and challenging. Try it!

Learning RactiveJS – Create a RactiveJS component based on jQuery UI

Create a RactiveJS component

One of the strong points of RactiveJS is for sure the capacity of live together with other frameworks / libraries without being invasive at all – like many and well famous javascript libraries do, but it’s another story –

In this example, I’ll reuse the autocomplete jQuery UI widget and I will distribuite it as a ractive component with its binding properties and my custom preferences; the output page will be the following:

For downloading the example code, use the link at the bottom of the page

First off, import all the common javascript and css files that we use for this project.

for the making of the autocomplete component I’ll create a separate js.

This autocomplete is a simple editable combobox input; therefore, despite it shows me all the suggested values I load in there, it is possible to put any value I want.

Notice that component can load its template also in a more readable way throught ractive load plugin ; for this purpose refer at page ractive load. The attached example is already configured to use this plugin by just adjusting a few lines of code.

Now I can load this component in the main page:

The output page is the following:

Download code 1442252194_floppy_disk_save

DataTables examples: Having fun with table data and Java


  • Any web application server java compatible
  • Java 1.7 (because of the use of some features like switch string statements)
  • jQuery and dateformat plugin
  • Guava
  • Apache commons lang
  • Jstl 1.2
  • Log4J

Download demo

The simple example

DataTables simple example

Server code
Javascript code
Html code:

Some notes:

With this option

Render the column not searchable and orderable for all the columns with class = not-search-orderable.

CreatedRow is a callback for the generated row. It’s a good place to put the the code for generating the progressive number on the first column

When user do a sort or search action, the progressive number must rigenerate itself. This callback function do the needed job:

The Ajax example

Ajax sample


Server code

Javascript code


From the server code, we can notice that data is put on a map that is converted to Json and sent to response

The request values belongs from the serialized form, then are decodified and splitted (using the Guava Splitter class).

The crux steps are:

The way the person’s notes are shown is slightly different from the simple example, because there’s a single div in the page that is dinamically filled by clicking on the specified column.

The date column can be formatted in this way

In order to use $ function, the dateFormat plugin is required.

The Pipeline example

The pipeline example is similar to ajax example, except for the fact that the table uses a cache control before the ajax call; the cache works for paging. Every time a new search or sorting is requested, the cache must be cleared.

The Send example


This example shows how to elaborate the existent data of a datatable and process it through the server using a form hidden field in which is a json string value is set; data is sent through a standard form post method but can be done using ajax as well.

HTML Form code
Javascript code
Server code

Add a loading box between web pages

Let’s add a loading box that appears everytime a button with a certain class is clicked and prevent the user to do any operation before it disappears:

css file:

js file:
html file:

Create an image link using jQuery and css

Suppose to have a web site with generic icon for doing some operations.

It would be handy to use a specific class to show the wanted icon, instead of writing several times the same code as below

Solution with jQuery

By using jQuery it’s possible to automatically generate the image inside the anchor.

Put this code on the load event of the document:

whenever you need to display the detail image on a link, the code to write is simple:

Solution with css

Without using jQuery, is a common practice to use the background-image property of css

Create an image link in this way is maybe more clean than using jQuery, although width and height property of the image must be specified