The Complete Guide to WordPress Performance Optimization

Ecommerce software stats by

WordPress can thank its simplicity and a low barrier to entry for this pervasiveness. It’s easy to set up, and requires next to no technical knowledge. Hosting for WordPress can be found for as little as a couple of dollars per month, and the basic setup takes just a half hour of clicking. Free themes for WordPress are galore, some with included WYSIWYG page builders.

Many look down on it, but in many ways we can thank WordPress for the growth of the internet and PHP, and many internet professionals have WP’s gentle learning curve to thank for their careers.

But this ease of entry comes at a cost. Plenty of websites that proudly wear the WordPress badge were not done by professionals but by the cheapest developers. And often, it shows. Professional look and professional performance were afterthoughts.

One of the main points of feedback the owner of an aspiring high-quality website will get from a grudging professional is that performance and a professional look and feel shouldn’t be afterthoughts. You can’t easily paint or stick them over a website. Professional websites should be premeditated.

A famous UK used car dealer, Ling’s Cars, tried a unique way to make a kitsch marketing punchline. Unless you’re REALLY sure about what you’re doing, DO NOT try this at home.

And this starts with…

Choice of Hosting

Typically, new users will go with products that are on the low-cost side, with most of beginner-friendly bells and whistles. Considering the shady business practices by some big industry players in this arena, and the complaints and demands for site migration professionals coming from clients, this is a part of website setup that requires due attention.

We can divide WordPress hosting vendors into a few tiers.

Premium, WordPress-dedicated vendors like Kinsta whose plans start at $100 per month, or even higher-grade managed hosting like WordPress VIP by Automattic, may be worth their salt, but also may be out of reach for many website owners.

Medium tier FlywheelA2 hostingSiteground and Pantheon are among those considered reliable and performance oriented, offering acceptable speed and a managed hosting service for those more price-conscious. Users here may get a bit less hand-holding, but these services usually strike an acceptable balance between a solid setup, price, and options for more advanced users. Not to forget, there is Cloudways, which is a hybrid between VPS and managed hosting. Those with their audience in Europe may look into Pilvia, as it offers a performant server stack and is pretty affordable.

There’s an interesting survey of customer satisfaction with more prominent hosting vendors, published by Codeinwp.

For those of us not scared of the command line, there are VPS and dedicated-server vendors like Digital OceanVultrLinode, Amazon’s LightsailHetzner in Europe, and OVH. Hetzner is a German vendor known for its quality physical servers on offer, somewhat above the price of virtual servers, while OVH offers very cost-efficient virtual servers. For the price-conscious, OVH’s subsidiary Kimsufi in Europe and Canada also offers bargain physical dedicated servers, and Host US has very affordable virtual servers.


With managed hosting, things to look for are a good server stack, good CDN integration, and of course SSD storage. Guaranteed resources, like with A2, are a big plus. The next thing to look for is SSH-access. Tech-savvy users may profit from WP-CLI availability.

When choosing a VPS, the thing to look for is XEN or KVM virtualization over OpenVZ, because it mitigates the overselling of resources, helping guarantee that the resources you bought are really yours. It also provides better security.

Easy Engine is software that can make your entire VPS/WordPress installation a one-hour job.

Regarding the server stack, Nginx is preferred to Apache if we’re pursuing performance, and PHP 7 is a must. If we really need Apache, using Nginx as a reverse proxy is a plus, but this setup can get complex.

Tests performed give PHP 7 a big edge over the previous version. According to

WordPress 4.1 executed 95% more requests per second on PHP 7 compared to PHP 5.6.

When choosing your hosting, be aware of negative experiences with some providers that have become notorious.

Software Considerations

Things that usually slow down WordPress websites are bulky, bloated front ends with a lot of static resources and database queries. These issues arise from the choice of theme (and its page builders, huge sliders, etc) — which not only slow down initial loading due to many requests and overall size, but often slow down the browser due to a lot of JavaScript, and stuff to render, making it unresponsive.

The golden rule here is: don’t use it unless there’s a good reason to.

This may seem like a rule coming from the mouth of Homer Simpson, but if you can skip any of the bells and whistles, do so. Be conservative. If you must add some shiny functionality or JS eye candy, always prefer those tailored and coded as specifically as possible for your exact need. If you’re a skilled coder, and the project justifies the effort, code it yourself with minimalism in mind.

Review all the plugins your website can’t live without — and remove the others.

And most importantly: back up your website before you begin pruning!

Data model

If you have a theme where you use a lot of custom posts or fields, be warned that a lot of these will slow down your database queries. Keep your data model as simple as possible, and if not, consider that WordPress’ original intended purpose was as a blogging engine. If you need a lot more than that, you may want to consider some of the MVC web frameworks out there that will give you greater control over your data model and the choice of database.


In WordPress we can build a rich custom data model by using custom post typescustom taxonomies and custom fields, but be conscious of performance and complexity costs.

If you know your way around the code, inspect your theme to find unnecessary database queries. Every individual database trip spends precious milliseconds in your TTFB, and megabytes of your server’s memory. Remember that secondary loops can be costly — so be warned when using widgets and plugins that show extra posts, like in sliders or widget areas. If you must use them, consider fetching all your posts in a single query, where it may otherwise slow down your website. There’s a GitHub repo for those not wanting to code from scratch.

Meta queries can be expensive

Using custom fields to fetch posts by some criteria can be a great tool to develop sophisticated things with WP. This is an example of a meta query, and here you can find some elaboration on its costs. Summary: post meta wasn’t built for filtering, taxonomies were.

get_post_meta is a function typically called to fetch custom fields, and it can be called with just the post ID as an argument, in which case it fetches all the post’s meta fields in an array, or it can have a custom field’s name as a second argument, in which case it returns just the specified field.

If using get_post_meta()for a certain post multiple times on a single page or request (for multiple custom fields), be aware that this won’t incur extra cost, because the first time this function is called, all the post meta gets cached.

Database hygiene

Installing and deleting various plugins, and changing different themes over the lifetime of your website, often clutters your database with a lot of data that isn’t needed. It’s completely possible to discover — upon inspecting why a WordPress website is sluggish, or why it won’t even load, due to exhausted server memory — that the database has grown to hundreds and hundreds of megabytes, or over a gigabyte, with no content that explains it.

wp-options is where a lot of orphaned data usually gets left behind. This includes, but is not limited to, various transients (this post warns of best practices regarding deletion of transients in plugins). Transients are a form of cache, but as with any other caching, if misused, it can do more harm than good. If your server environment provides it, wp-cli has a command set dedicated to transients management, including deletion. If not, there are plugins in the WordPress plugins repo that can delete expired transients, but which offer less control.

If deleting transients still leaves us with a bloated database without any tangible cause, WP-Sweep is an excellent free tool that can do the job of cleaning up the database. Another one to consider is WP Optimize.

Before doing any kind of database cleanup, it’s strongly recommended that you back up your database!

One of the plugins that comes in very handy for profiling of the whole WordPress request lifecycle is Debug Objects. It offers an inspection of all the transients, shortcodes, classes, styles and scripts, templates loaded, db queries, and hooks.

Debug Objects plugin output

After ensuring a sane, performance-oriented setup — considering our server stack in advance, eliminating the possible bloat created by theme choice and plugins and widgets overload — we should try to identify bottlenecks.

If we test our website in a tool like Pingdom Speed Test, we’ll get a waterfall chart of all the resources loaded in the request:


Pingdom Waterfall Chart

This gives us details about the request-response lifecycle, which we can analyze for bottlenecks. For instance:

  • If the pink DNS time above is too big, it could mean we should consider caching our DNS records for a longer period. This is done by increasing the TTL setting in our domain management/registrar dashboard.
  • If the SSL part is taking too long, we may want to consider enabling HTTP/2 to benefit from ALPN, adjusting our cache-control headers, and finally switching to a CDN service. “Web Performance in a Nutshell: HTTP/2, CDNs and Browser Caching” is a thorough article on this topic, as is “Analyzing HTTPS Performance Overhead” by KeyCDN.
  • ConnectSend, and Receive parts usually depend on network latency, so these can be improved by hosting close to your intended audience, making sure your host has a fast uplink, and using a CDN. For these items, you may want to consider a ping tool too (not to be confused with the Pingdom tools mentioned above), to make sure your server is responsive.
  • The Wait part — the yellow part of the waterfall — is the time your server infrastructure takes to produce or return the requested website. If this part takes too much time, you may want to return to our previous topics of optimizing the server, WordPress installation, and database stack. Or you may consider various layers of caching.

To get a more extensive testing and hand-holding tips on improving the website, there’s a little command line utility called webcoach. In an environment with NodeJS and npm installed (like Homestead Improved), installing it is simple:

npm install webcoach -g

After it’s been installed, we can get detailed insights and advice on how to improve our website’s various aspects, including performance:

webcoach command


Caching can make all the difference when managing a WordPress website. There are a few layers and possible ways of caching.

Page Caching

Page caching is caching of the entire HTML output of a web application.

If we can, we should try to test the server-level solutions first, like NGINX caching, or Varnish, or caching systems offered by managed host vendors like Kinsta, Siteground, and others.

Siteground Optimizer

If this doesn’t turn out to be as helpful as we’d like, we may want to consider plugins like WP Super CacheWP Fastest Cache, or the overhauled W3 Total Cache from GitHub. All of these can improve performance, but usually require some experimenting. Badly configured caching solutions can actually harm the site’s performance. W3TC, for example — at least before the overhaul — is known to be maybe the best free caching solution, doing real wonders … when it works. When it doesn’t, it can take your website offline.

WP Rocket is known to be maybe the most praised of the premium caching solutions.

Page caching can improve performance drastically, serving entire websites from RAM, but be aware that it can introduce complications if you have a dynamic website with a cart, or parts that depend on cookies or a personalized front end. It can serve one user’s UI parts to another user, so it usually needs to be tested before being put into production. This especially applies to solutions on non-managed servers, like Varnish or Cloudflare page cache.

Fragment caching

Fragment caching is a solution to think about when dynamic, cookie-dependent websites become hard to cache with a full-page approach, or when we are caching Ajax requests. A good introduction is available here.


Object cache

Object cache means compiling and storing in-memory all the database queries and PHP objects. Some caching plugins try to manage object-cache back ends for us. The back ends used are usually APCu, Memcached and Redis.
They need to be installed on the server.

To go deeper into benchmarking our PHP code and the performance of our object caching, a valuable tool which requires shell access and wp-cli installed is the profile command. We can install it with:

wp package install


wp package install wp-cli/profile-command

(You may need to add the --allow-root flag, depending on the installation.)

Then we can profile the whole load cycle, or drill down to specific hooks, files and classes, their load time and caching ratio.

wp profile command

Browser caching

Browser caching means forcing visitors’ browsers to keep static files in their cache, so they don’t need to get them from our server on repeat visits. cache-control and expires headers are used here. Caching plugins often manage browser caching and setting the headers. Technumero made a guide that goes into more depth.

Static Files

Static files are images, stylesheets, JS code, fonts, media files, etc. We should make sure we compress them, and that we’re leveraging HTTP/2 to serve these files if possible. If our managed hosting doesn’t support HTTP/2, or moving our unmanaged VPS to HTTP/2 is out of reach, the easiest way is to implement a CDN into our stack. CDNs serve our static files from data centers closest to our audience. This decreases latency and usually means taking advantage of their highly tuned infrastructure.

Autooptimize is one plugin that can help manipulate our static assets, and reduce the number of requests, concatenating JS and stylesheet files, minifying them and thus shrinking the page output.

Regarding media files, we should consider compressing/encoding our videos to reduce their size, and serving them through providers like YouTube, to reduce the strain on our servers. Cloud storage providers like Amazon S3 are another good option. Video hosting is out of scope of this article, but WPMUDEV made a handy guide about the topic.

Regarding images, these are often too big for the web. Sometimes the only solution that will allow our server to breathe — and might take a lengthy amount of time — is batch compression through the shell. Imagemagick on Linux has a useful convert tool that allows us to batch compress our images. This example does it recursively with all JPGs in a folder, reducing JPEG quality to 80%, along with other small enhancements, and resizing the images (it should be self-explanatory):

for file in *.jpg; do convert "${file}" -resize 20% -sharpen 3 -sharpen 2 -brightness-contrast "0x26" -quality 80 thumb."${file}"; done

WP Bullet has two excellent guides to batch compress JPG and PNG files.

Apart from that, there’s the Imagify service and the accompanying WordPress plugin to reduce image sizes, EWWW image optimizer, and others…


Other random tips

  • Memorymake sure your installation has enough.

  • XML-RPC and login page can often suffer from automated, scripted brute-force attacks — even if one isn’t a big fish. Even without breaking in, they can waste the CPU cycles. We should try to stop them on the server-level, before our WordPress installation is loaded. If we don’t need the access to xml-rpc.php, we can put this snippet inside our virtual host block on nginx:

    location = /xmlrpc.php {    
        deny all;    

    In Apache:

    <Files xmlrpc.php>
        deny from all

    Plugins like iThemes SecurityWPS Hide login and others can help with this and with changing our login page URL.

    If you’re under brute force attacks and you aren’t protected by a CDN like Cloudflare — or a managed host’s protection — consider a firewall like fail2ban (you should probably have a firewall in place whether under attack or not).

  • WordPress Heartbeat: polling the server while WordPress dashboard is open can slow your server, and make your dashboard unresponsive. Especially if it’s open in multiple browser tabs or by several users. The HeartBeat plugin can help solve that.

  • MAX_INPUT_VARS: when saving posts with lots of meta fields, or variable products with WooCommerce, we may reach a limit of maximum allowed request variables (variables sent by complex WooCommerce products can go into thousands). This can bring down your server. Here’s how to fix it.

  • If your WordPress installation with a big database — especially a WooCommerce installation — starts having issues with speed that you can’t solve otherwise, consider ElasticPress. Some have had luck with it.

  • If you use WordFence, make sure to turn off the Live View feature. It can bring to a halt even a VPS with couple of gigabytes of memory.

  • If you’re logging access to your website — particularly in debug.log in your wp-content directory — mind its size. It can grow to the level of gigabytes and crash your server.

  • If you have system crashes on your server/hosting, core dumps will fill up your storage. Have someone analyze the reasons of those crashes, and then delete those files. You’ll recognize them by patterns that look like core.XXXXXX.

All this said, a repeat warning is in order: before you do any changes to your website, back it up!


I hope this compilation of WordPress optimization tips will come in handy. As sites grow in size, the tricks are harder and harder to retroactively apply. That’s why it’s best to start early, and strive for a maximum effect: apply as many of these techniques before you launch, and you’ll not only have a smooth launch, but also a performant app from day 1 — surely a fantastic experience for all new users.

Make sure you also check out SitePoint’s PWA guide. Making your WP site as PWA as possible from day 0 will help users install it on the home screens of their devices, priming them for repeat visits.

Originally found here .

Veliki Market

U poslednjih nekoliko dana smo realizovali spontanu ideju neformalne grupe stručnih ljudi, te vam ponosno predstavljamo Veliki market – web aplikaciju na WordPress platformi, gde možete potpuno besplatno oglasiti i pretražiti samostalne proizvođače hrane. Usluga je potpuno besplatna i takva će i ostati, a posebnu zahvalnost izražavamo mCloud-u na nesebičnoj donaciji hostinga i registracije domena.

Getting Started with Web Applications

A web application is a dynamic extension of a web or application server. There are two types of web applications:

Web Applications

In the Java 2 platform, web components provide the dynamic extension capabilities for a web server. Web components are either Java servlets, JSP pages, or web service endpoints. The interaction between a web client and a web application is illustrated in Figure 3–1. The client sends an HTTP request to the web server. A web server that implements Java Servlet and JavaServer Pages technology converts the request into an HTTPServletRequest object. This object is delivered to a web component, which can interact with JavaBeans components or a database to generate dynamic content. The web component can then generate an HTTPServletResponse or it can pass the request to another web component. Eventually a web component generates a HTTPServletResponse object. The web server converts this object to an HTTP response and returns it to the client.

Figure 3–1 Java Web Application Request Handling
Diagram of web application request handling. Clients
and web components communicate using HttpServletRequest and HttpServletResponse.

Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. Although servlets and JSP pages can be used interchangeably, each has its own strengths. Servlets are best suited for service-oriented applications (web service endpoints are implemented as servlets) and the control functions of a presentation-oriented application, such as dispatching requests and handling nontextual data. JSP pages are more appropriate for generating text-based markup such as HTML, Scalable Vector Graphics (SVG), Wireless Markup Language (WML), and XML.

Since the introduction of Java Servlet and JSP technology, additional Java technologies and frameworks for building interactive web applications have been developed. Figure 3–2 illustrates these technologies and their relationships.

Figure 3–2 Java Web Application Technologies
Diagram of web application technologies. JavaServer Pages,
the JSP Standard Tag Library, and JavaServer Faces rest on JavaServlet technology.

Notice that Java Servlet technology is the foundation of all the web application technologies, so you should familiarize yourself with the material in Chapter 4, Java Servlet Technology even if you do not intend to write servlets. Each technology adds a level of abstraction that makes web application prototyping and development faster and the web applications themselves more maintainable, scalable, and robust.

Web components are supported by the services of a runtime platform called a web container. A web container provides services such as request dispatching, security, concurrency, and life-cycle management. It also gives web components access to APIs such as naming, transactions, and email.

Certain aspects of web application behavior can be configured when the application is installed, or deployed, to the web container. The configuration information is maintained in a text file in XML format called a web application deployment descriptor (DD). A DD must conform to the schema described in the Java Servlet Specification.

This chapter gives a brief overview of the activities involved in developing web applications. First it summarizes the web application life cycle. Then it describes how to package and deploy very simple web applications on the Application Server. It moves on to configuring web applications and discusses how to specify the most commonly used configuration parameters. It then introduces an example, Duke’s Bookstore, which illustrates all the Java EE web-tier technologies, and describes how to set up the shared components of this example. Finally it discusses how to access databases from web applications and set up the database resources needed to run Duke’s Bookstore.

Web Application Life Cycle

A web application consists of web components, static resource files such as images, and helper classes and libraries. The web container provides many supporting services that enhance the capabilities of web components and make them easier to develop. However, because a web application must take these services into account, the process for creating and running a web application is different from that of traditional stand-alone Java classes.

  1. Develop the web component code.
  2. Develop the web application deployment descriptor.
  3. Compile the web application components and helper classes referenced by the components.
  4. Optionally package the application into a deployable unit.
  5. Deploy the application into a web container.
  6. Access a URL that references the web application.

Developing web component code is covered in the later chapters. Steps 2 through 4 are expanded on in the following sections and illustrated with a Hello, World-style presentation-oriented application. This application allows a user to enter a name into an HTML form (Figure 3–3) and then displays a greeting after the name is submitted (Figure 3–4).

Figure 3–3 Greeting Form
Screen capture of Duke's greeting, "Hello, my name is
Duke. What's yours?" Includes a text field for your name and Submit and Reset
Figure 3–4 Response
Screen capture of Duke's response, "Hello, Charlie!"

The Hello application contains two web components that generate the greeting and the response. This chapter discusses two versions of the application: a JSP version called hello1, in which the components are implemented by two JSP pages (tut-install/javaeetutorial5/examples/web/hello1/web/index.jsp and tut-install/javaeetutorial5/examples/web/hello1/web/response.jsp) and a servlet version called hello2, in which the components are implemented by two servlet classes (tut-install/javaeetutorial5/examples/web/hello2/src/servlets/ and tut-install/javaeetutorial5/examples/web/hello2/src/servlets/ The two versions are used to illustrate tasks involved in packaging, deploying, configuring, and running an application that contains web components. The section Chapter 2, Using the Tutorial Examples explains how to get the code for these examples.

After you install the tutorial bundle, the source code for the examples is in the following directories:

  • tut-install/javaeetutorial5/examples/web/hello1/
  • tut-install/javaeetutorial5/examples/web/hello2/

Web Modules

In the Java EE architecture, web components and static web content files such as images are called web resources. A web module is the smallest deployable and usable unit of web resources. A Java EE web module corresponds to a web application as defined in the Java Servlet specification.

In addition to web components and web resources, a web module can contain other files:

  • Server-side utility classes (database beans, shopping carts, and so on). Often these classes conform to the JavaBeans component architecture.
  • Client-side classes (applets and utility classes).

A web module has a specific structure. The top-level directory of a web module is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static web resources, such as images, are stored.

The document root contains a subdirectory named WEB-INF, which contains the following files and directories:

  • web.xml: The web application deployment descriptor
  • Tag library descriptor files (see Tag Library Descriptors)
  • classes: A directory that contains server-side classes: servlets, utility classes, and JavaBeans components
  • tags: A directory that contains tag files, which are implementations of tag libraries (see Tag File Location)
  • lib: A directory that contains JAR archives of libraries called by server-side classes

If your web module does not contain any servlets, filter, or listener components then it does not need a web application deployment descriptor. In other words, if your web module only contains JSP pages and static files then you are not required to include a web.xml file. The hello1example, first discussed in Packaging Web Modules, contains only JSP pages and images and therefore does not include a deployment descriptor.

You can also create application-specific subdirectories (that is, package directories) in either the document root or the WEB-INF/classes/directory.

A web module can be deployed as an unpacked file structure or can be packaged in a JAR file known as a web archive (WAR) file. Because the contents and use of WAR files differ from those of JAR files, WAR file names use a .war extension. The web module just described is portable; you can deploy it into any web container that conforms to the Java Servlet Specification.

To deploy a WAR on the Application Server, the file must also contain a runtime deployment descriptor. The runtime deployment descriptor is an XML file that contains information such as the context root of the web application and the mapping of the portable names of an application’s resources to the Application Server’s resources. The Application Server web application runtime DD is named sun-web.xml and is located in the WEB-INF directory along with the web application DD. The structure of a web module that can be deployed on the Application Server is shown in Figure 3–5.

Figure 3–5 Web Module Structure
Diagram of web module structure. WEB-INF and web pages
are under the root. Under WEB-INF are descriptors and the lib, classes, and
tags directories.

Packaging Web Modules

A web module must be packaged into a WAR in certain deployment scenarios and whenever you want to distribute the web module. You package a web module into a WAR by executing the jar command in a directory laid out in the format of a web module, by using the Ant utility, or by using the IDE tool of your choice. This tutorial shows you how to use NetBeans IDE or Ant to build, package, and deploy the sample applications.

  1. Select File->Open Project.
  2. In the Open Project dialog, navigate to:
  3. Select the hello1 folder.
  4. Select the Open as Main Project check box.
  5. Click Open Project.
  6. In the Projects tab, right-click the hello1 project and select Build.
  1. In a terminal window, go to tut-install/javaeetutorial5/examples/web/hello1/.
  2. Type ant. This command will spawn any necessary compilations, copy files to the tut-install/javaeetutorial5/examples/web/hello1/build/ directory, create the WAR file, and copy it to the tut-install/javaeetutorial5/examples/web/hello1/dist/ directory.

Deploying a WAR File

You can deploy a WAR file to the Application Server in a few ways:

  • Copying the WAR into the domain-dir/autodeploy/ directory.
  • Using the Admin Console.
  • By running asadmin or ant to deploy the WAR.
  • Using NetBeans IDE.

All these methods are described briefly in this chapter; however, throughout the tutorial, you will use ant and NetBeans IDE for packaging and deploying.

Setting the Context Root

context root identifies a web application in a Java EE server. You specify the context root when you deploy a web module. A context root must start with a forward slash (/) and end with a string.

In a packaged web module for deployment on the Application Server, the context root is stored in sun-web.xml.

  1. Expand your project tree in the Projects pane of NetBeans IDE.
  2. Expand the Web Pages and WEB-INF nodes of your project.
  3. Double-click sun-web.xml.
  4. In the editor pane, click Edit As XML.
  5. Edit the context root, which is enclosed by the context-root element.

Deploying a Packaged Web Module

If you have deployed the hello1 application, before proceeding with this section, undeploy the application by following one of the procedures described in Undeploying Web Modules.

Deploying with the Admin Console

  1. Expand the Applications node.
  2. Select the Web Applications node.
  3. Click the Deploy button.
  4. Select the radio button labeled “Package file to be uploaded to the Application Server.”
  5. Type the full path to the WAR file (or click on Browse to find it), and then click the OK button.
  6. Click Next.
  7. Type the application name.
  8. Type the context root.
  9. Select the Enabled box.
  10. Click the Finish button.

Deploying with asadmin

To deploy a WAR with asadmin, open a terminal window or command prompt and execute

asadmin deploy full-path-to-war-file

Deploying with Ant

To deploy a WAR with the Ant tool, open a terminal window or command prompt in the directory where you built and packaged the WAR, and execute

ant deploy

Deploying with NetBeans IDE

  1. Select File->Open Project.
  2. In the Open Project dialog, navigate to your project and open it.
  3. In the Projects tab, right-click the project and select Undeploy and Deploy.

Testing Deployed Web Modules

Now that the web module is deployed, you can view it by opening the application in a web browser. By default, the application is deployed to host localhost on port 8080. The context root of the web application is hello1.

  1. Open a web browser.
  2. Enter the following URL in the web address box:
  3. Enter your name, and click Submit.

The application should display the name you submitted as shown in Figure 3–3 and Figure 3–4.

Listing Deployed Web Modules

The Application Server provides two ways to view the deployed web modules: the Admin Console and the asadmin command.

  1. Open the URL http://localhost:4848/asadmin in a browser.
  2. Expand the nodes Applications->Web Applications.

Use the asadmin command as follows:

asadmin list-components

Updating Web Modules

  1. Recompile any modified classes.
  2. If you have deployed a packaged web module, update any modified components in the WAR.
  3. Redeploy the module.
  4. Reload the URL in the client.

Updating a Packaged Web Module

This section describes how to update the hello1 web module that you packaged.

First, change the greeting in the file tut-install/javaeetutorial5/examples/web/hello1/web/index.jsp to

<h2>Hi, my name is Duke. What’s yours?</h2>

To update the project in NetBeans IDE:

  • Right-click on the project and select Build.
  • Right-click on the project and select Undeploy and Deploy.

To update the project using the Ant build tool:

  • Type ant to copy the modified JSP page into the build directory.
  • Type ant deploy to deploy the WAR file.

To view the modified module, reload the URL in the browser.

You should see the screen in Figure 3–6 in the browser.

Figure 3–6 New Greeting
Screen capture of Duke's new greeting, "Hi, my name is
Duke. What's yours?" Includes a text field for your name and Submit and Reset

Dynamic Reloading

If dynamic reloading is enabled, you do not have to redeploy an application or module when you change its code or deployment descriptors. All you have to do is copy the changed JSP or class files into the deployment directory for the application or module. The deployment directory for a web module named context-root is domain-dir/applications/j2ee-modules/context-root. The server checks for changes periodically and redeploys the application, automatically and dynamically, with the changes.

This capability is useful in a development environment, because it allows code changes to be tested quickly. Dynamic reloading is not recommended for a production environment, however, because it may degrade performance. In addition, whenever a reload is done, the sessions at that time become invalid and the client must restart the session.

  1. Select the Applications Server node.
  2. Select the Advanced tab.
  3. Check the Reload Enabled box to enable dynamic reloading.
  4. Enter a number of seconds in the Reload Poll Interval field to set the interval at which applications and modules are checked for code changes and dynamically reloaded.
  5. Click the Save button.
  1. Create an empty file named .reload at the root of the module:
  2. Explicitly update the .reload file’s time stamp each time you make these changes. On UNIX, execute
    touch .reload

For JSP pages, changes are reloaded automatically at a frequency set in the Reload Poll Interval field. To disable dynamic reloading of JSP pages, set the Reload Poll Interval field value to –1.

Undeploying Web Modules

You can undeploy web modules in four ways: you can use NetBeans IDE, the Admin Console, the asadmin command, or the Ant tool.

  1. Ensure the Sun Java System Application Server is running.
  2. In the Runtime window, expand the Sun Java System Application Server instance and the node containing the application or module.
  3. Right-click the application or module and choose Undeploy.
  1. Open the URL http://localhost:4848/asadmin in a browser.
  2. Expand the Applications node.
  3. Select Web Applications.
  4. Click the check box next to the module you wish to undeploy.
  5. Click the Undeploy button.

Use the asadmin command as follows:

asadmin undeploy context-root

To use the Ant tool, execute the following command in the directory where you built and packaged the WAR:

ant undeploy

Configuring Web Applications

Web applications are configured by means of elements contained in the web application deployment descriptor.

The following sections give a brief introduction to the web application features you will usually want to configure. A number of security parameters can be specified; these are covered in Chapter 30, Securing Web Applications.

In the following sections, examples demonstrate procedures for configuring the Hello, World application. If Hello, World does not use a specific configuration feature, the section gives references to other examples that illustrate how to specify the deployment descriptor element.

Mapping URLs to Web Components

When a request is received by the web container it must determine which web component should handle the request. It does so by mapping the URL path contained in the request to a web application and a web component. A URL path contains the context root and an alias:


Setting the Component Alias

The alias identifies the web component that should handle a request. The alias path must start with a forward slash (/) and end with a string or a wildcard expression with an extension (for example, *.jsp). Since web containers automatically map an alias that ends with *.jsp, you do not have to specify an alias for a JSP page unless you wish to refer to the page by a name other than its file name.

  1. Select File->Open Project.
  2. In the Open Project dialog, navigate to:
  3. Select the hello2 folder.
  4. Select the Open as Main Project check box.
  5. Click Open Project.
  6. Expand the project tree in the Projects pane.
  7. Expand the Web pages node and then the WEB-INF node in the project tree.
  8. Double-click the web.xml file inside the WEB-INF node.

The following steps describe how to make the necessary edits to the web.xml file, including how to set the display name and how to map the servlet components. Because the edits are already in the file, you can just use the steps to view the settings.

  1. Click General at the top of the editor to open the general view.
  2. Enter hello2 in the Display Name field.
  1. Click Servlets at the top of the editor to open the servlets view.
  2. Click Add Servlet.
  3. In the Add Servlet dialog, enter GreetingServlet in the Servlet Name field.
  4. Enter servlets.GreetingServlet in the Servlet Class field.
  5. Enter /greeting in the URL Pattern field.
  6. Click OK.
  7. Repeat the preceding steps, except enter ResponseServlet as the servlet name, servlets.ResponseServlet as the servlet class, and /response as the URL pattern.

If you are not using NetBeans IDE, you can add these settings using a text editor.

  1. Select File->Open Project.
  2. In the Open Project dialog, navigate to:
  3. Select the hello2 folder.
  4. Select the Open as Main Project check box.
  5. Click Open Project.
  6. In the Projects tab, right-click the hello2 project and select Build.
  1. In a terminal window, go to tut-install/javaeetutorial5/examples/web/hello2/.
  2. Type ant. This target will build the WAR file and copy it to the tut-install/javaeetutorial5/examples/web/hello2/dist/directory.

To deploy the example using NetBeans IDE, right-click on the project in the Projects pane and select Undeploy and Deploy.

To deploy the example using Ant, type ant deploy. The deploy target in this case gives you an incorrect URL to run the application. To run the application, please use the URL shown at the end of this section.

To run the application, first deploy the web module, and then open the URL http://localhost:8080/hello2/greeting in a browser.

Declaring Welcome Files

The welcome files mechanism allows you to specify a list of files that the web container will use for appending to a request for a URL (called a valid partial request) that is not mapped to a web component.

For example, suppose you define a welcome file welcome.html. When a client requests a URL such as host:port/webapp/directory, where directory is not mapped to a servlet or JSP page, the file host:port/webapp/directory/welcome.html is returned to the client.

If a web container receives a valid partial request, the web container examines the welcome file list and appends to the partial request each welcome file in the order specified and checks whether a static resource or servlet in the WAR is mapped to that request URL. The web container then sends the request to the first resource in the WAR that matches.

If no welcome file is specified, the Application Server will use a file named index.XXX, where XXX can be html or jsp, as the default welcome file. If there is no welcome file and no file named index.XXX, the Application Server returns a directory listing.

  1. Open the project if you haven’t already.
  2. Expand the project’s node in the Projects pane.
  3. Expand the Web Pages node and then the WEB-INF node.
  4. Double-click web.xml.
  5. Do one of the following, making sure that the JSP pages you specify are actually included in the WAR file:
    1. Click Pages at the top of the editor pane and enter the names of the JSP pages that act as welcome files in the Welcome Files field.
    2. Click XML at the top of the editor pane, specify the JSP pages using welcome-file elements and include these elements inside a welcome-file-list element. The welcome-file element defines the JSP page to be used as the welcome page.The example discussed in Encapsulating Reusable Content Using Tag Files has a welcome file.

Setting Initialization Parameters

The web components in a web module share an object that represents their application context (see Accessing the Web Context). You can pass initialization parameters to the context or to a web component.

  1. Open the project if you haven’t already.
  2. Expand the project’s node in the Projects pane.
  3. Expand the Web Pages node and then the WEB-INF node.
  4. Double-click web.xml.
  5. Click General at the top of the editor pane.
  6. Select the Context Parameters node.
  7. Click Add.
  8. In the Add Context Parameter dialog, do the following:
    1. Enter the name that specifies the context object in the Param Name field.
    2. Enter the parameter to pass to the context object in the Param Value field.
    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

  • A param-name element that specifies the context object
  • A param-value element that specifies the parameter to pass to the context object
  • A context-param element that encloses the previous two elements

For a sample context parameter, see the example discussed in The Example JSP Pages.

  1. Open the project if you haven’t already.
  2. Expand the project’s node in the Projects pane.
  3. Expand the Web Pages node and then the WEB-INF node.
  4. Double-click web.xml.
  5. Click Servlets at the top of the editor pane.
  6. After entering the servlet’s name, class, and URL pattern, click the Add button under the Initialization Parameters table.
  7. In the Add Initialization Parameter dialog:
    1. Enter the name of the parameter in the Param Name field.
    2. Enter the parameter’s value in the Param Value Field.
    3. Click OK.

Alternatively, you can edit the XML of the web.xml file directly by clicking XML at the top of the editor pane and using the following elements to add a context parameter:

  • A param-name element that specifies the name of the initialization parameter
  • A param-value element that specifies the value of the initialization parameter
  • An init-param element that encloses the previous two elements

Mapping Errors to Error Screens

When an error occurs during execution of a web application, you can have the application display a specific error screen according to the type of error. In particular, you can specify a mapping between the status code returned in an HTTP response or a Java programming language exception returned by any web component (see Handling Servlet Errors) and any type of error screen.

  1. Open the project if you haven’t already.
  2. Expand the project’s node in the Projects pane.
  3. Expand the Web Pages node and then the WEB-INF node.
  4. Double-click web.xml.
  5. Click Pages at the top of the editor pane.
  6. Expand the Error Pages node.
  7. Click Add.
  8. In the Add Error Page dialog:
    1. Click Browse to locate the page that you want to act as the error page.
    2. Enter the HTTP status code that will cause the error page to be opened in the Error Code field.
    3. Enter the exception that will cause the error page to load in the Exception Type field.
    4. Click OK.

Alternatively, you can click XML at the top of the editor pane and enter the error page mapping by hand using the following elements:

  • An exception-type element specifying either the exception or the HTTP status code that will cause the error page to be opened.
  • A location element that specifies the name of a web resource to be invoked when the status code or exception is returned. The name should have a leading forward slash (/).
  • An error-page element that encloses the previous two elements.

You can have multiple error-page elements in your deployment descriptor. Each one of the elements identifies a different error that causes an error page to open. This error page can be the same for any number of error-page elements.

Note –

You can also define error screens for a JSP page contained in a WAR. If error screens are defined for both the WAR and a JSP page, the JSP page’s error page takes precedence. See Handling JSP Page Errors.

For a sample error page mapping, see the example discussed in The Example Servlets.

Declaring Resource References

If your web component uses objects such as enterprise beans, data sources, or web services, you use Java EE annotations to inject these resources into your application. Annotations eliminate a lot of the boilerplate lookup code and configuration elements that previous versions of Java EE required.

Although resource injection using annotations can be more convenient for the developer, there are some restrictions from using it in web applications. First, you can only inject resources into container-managed objects. This is because a container must have control over the creation of a component so that it can perform the injection into a component. As a result, you cannot inject resources into objects such as simple JavaBeans components. However, JavaServer Faces managed beans are managed by the container; therefore, they can accept resource injections.

Additionally, JSP pages cannot accept resource injections. This is because the information represented by annotations must be available at deployment time, but the JSP page is compiled after that; therefore, the annotation will not be seen when it is needed. Those components that can accept resource injections are listed in Table 3–1.

This section describes how to use a couple of the annotations supported by a servlet container to inject resources. Chapter 25, Persistence in the Web Tier describes how web applications use annotations supported by the Java Persistence API. Chapter 30, Securing Web Applicationsdescribes how to use annotations to specify information about securing web applications.Table 3–1 Web Components That Accept Resource Injections

Component  Interface/Class 
Servlets  javax.servlet.Servlet
Servlet Filters  javax.servlet.ServletFilter
Event Listeners  javax.servlet.ServletContextListenerjavax.servlet.ServletContextAttributeListenerjavax.servlet.ServletRequestListenerjavax.servlet.ServletRequestAttributeListenerjavax.servlet.http.HttpSessionListenerjavax.servlet.http.HttpSessionAttributeListenerjavax.servlet.http.HttpSessionBindingListener
Taglib Listeners  Same as above 
Taglib Tag Handlers  javax.servlet.jsp.tagext.JspTag
Managed Beans  Plain Old Java Objects 

Declaring a Reference to a Resource

The @Resource annotation is used to declare a reference to a resource such as a data source, an enterprise bean, or an environment entry. This annotation is equivalent to declaring a resource-ref element in the deployment descriptor.

The @Resource annotation is specified on a class, method or field. The container is responsible for injecting references to resources declared by the @Resource annotation and mapping it to the proper JNDI resources. In the following example, the @Resource annotation is used to inject a data source into a component that needs to make a connection to the data source, as is done when using JDBC technology to access a relational database:

@Resource javax.sql.DataSource catalogDS;
public getProductsByCategory() {
    // get a connection and execute the query
    Connection conn = catalogDS.getConnection();

The container injects this data source prior to the component being made available to the application. The data source JNDI mapping is inferred from the field name catalogDS and the type, javax.sql.DataSource.

If you have multiple resources that you need to inject into one component, you need to use the @Resources annotation to contain them, as shown by the following example:

@Resources ({
    @Resource (name="myDB" type=java.sql.DataSource),
    @Resource(name="myMQ" type=javax.jms.ConnectionFactory)

The web application examples in this tutorial use the Java Persistence API to access relational databases. This API does not require you to explicitly create a connection to a data source. Therefore, the examples do not use the @Resource annotation to inject a data source. However, this API supports the @PersistenceUnit and @PersistenceContext annotations for injecting EntityManagerFactory and EntityManager instances, respectively. Chapter 25, Persistence in the Web Tier describes these annotations and the use of the Java Persistence API in web applications.

Declaring a Reference to a Web Service

The @WebServiceRef annotation provides a reference to a web service. The following example shows uses the @WebServiceRefannotation to declare a reference to a web service. WebServiceRef uses the wsdlLocation element to specify the URI of the deployed service’s WSDL file:

public class ResponseServlet extends HTTPServlet {
static HelloService service;

Duke’s Bookstore Examples

In Chapters Chapter 4, Java Servlet Technology through Chapter 15, Internationalizing and Localizing Web Applications a common example, Duke’s Bookstore, is used to illustrate the elements of Java Servlet technology, JavaServer Pages technology, the JSP Standard Tag Library, and JavaServer Faces technology. The example emulates a simple online shopping application. It provides a book catalog from which users can select books and add them to a shopping cart. Users can view and modify the shopping cart. When users are finished shopping, they can purchase the books in the cart.

The Duke’s Bookstore examples share common classes and a database schema. These files are located in the directory tut-install/javaeetutorial5/examples/web/bookstore/. The common classes are packaged into a JAR. Each of the Duke’s Bookstore examples must include this JAR file in their WAR files. The process that builds and packages each application also builds and packages the common JAR file and includes it in the example WAR file.

The next section describes how to create the bookstore database tables and resources required to run the examples.

Accessing Databases from Web Applications

Data that is shared between web components and is persistent between invocations of a web application is usually maintained in a database. To maintain a catalog of books, the Duke’s Bookstore examples described in Chapters Chapter 4, Java Servlet Technology through Chapter 15, Internationalizing and Localizing Web Applications use the Java DB database included with the Application Server.

To access the data in a database, web applications use the new Java Persistence API (see Chapter 24, Introduction to the Java Persistence API). See Chapter 25, Persistence in the Web Tier to learn how the Duke’s Bookstore applications use this API to access the book data.

To run the Duke’s Bookstore applications, you need to first populate the database with the book data and create a data source in the application server. The rest of this section explains how to perform these tasks.

Populating the Example Database

  1. In a terminal window, go to the books directory or any one of the bookstore1 through bookstore6 example directories.
  2. Start the Java DB database server. For instructions, see Starting and Stopping the Java DB Database Server. You don’t have to do this if you are using NetBeans IDE. It starts the database server automatically.
  3. Type ant create-tables. This task runs a command to read the file tutorial.sql and execute the SQL commands contained in the file.
  4. At the end of the processing, you should see the following output:


181 of 181 SQL statements executed successfully

When you are running create-tables, don’t worry if you see a message that an SQL statement failed. This usually happens the first time you run the command because it always tries to delete an existing database table first before it creates a new one. The first time through, there is no table yet, of course.

Creating a Data Source in the Application Server

A DataSource object has a set of properties that identify and describe the real world data source that it represents. These properties include information such as the location of the database server, the name of the database, the network protocol to use to communicate with the server, and so on.

Data sources in the Application Server implement connection pooling. To define the Duke’s Bookstore data source, you use the installed Derby connection pool named DerbyPool.

  1. Expand the Resources node.
  2. Expand the JDBC node.
  3. Select the JDBC Resources node.
  4. Click the New… button.
  5. Type jdbc/BookDB in the JNDI Name field.
  6. Choose DerbyPool for the Pool Name.
  7. Click OK.

Further Information about Web Applications

For more information on web applications, see:




Full list of HTML elements

As a reminder, in most browsers you can right-click on a page and select View Source to see the HTML code used to render the page.

Basic HTML

<html>All content of your webpage must go inside <html></html> tags. 
<head>Contains information about the webpage.
The title tag goes inside <head></head> tags.
<title>Title of the webpage (what appears in the window/tab of your browser).
The text itself does not appear on webpage.
<body>Everything that appears on the webpage should go between these tags 
<p>Defines a paragraph (text with some space on the bottom and top).<p>This is a paragraph.</p>

This is a paragraph.

<h1>Heading tag, bold and bigger text.
You can use any number from <h1> to <h6> with <h1> being the largest heading and <h6> being the smallest.
<h3>larger heading</h3>
<h6>smaller heading</h6>

larger heading

smaller heading
<b>Apply bold formatting to text<b>bold</b>
<em>Apply emphasis to text<em>emphasis</em>

Inserts an image.

  • src is the link specifying the image to display (it is a required attribute)
  • width (and height) specifies the size of the image (it is an optional attribute)

Unlike most other tags, this start tag does not have a corresponding end tag.

<img src="" width="100px">

Links to another webpage.

  • href specifies the URL of the page to link to (it is a required attribute).

There must be some text between the start and end tags to be the anchor of the link.

<a href="">Duke University</a>
Duke University
<div>Defines a section of the web page.<div><p>This paragraph is inside a div.</p></div>


<li>List item.
List items can go inside unordered list, <ul>, or ordered list, <ol> tags.
<ul>Unordered list, each item has a bullet point.<ul>
  • HTML
  • CSS
<ol>Ordered list, each item has a number.<ol>
  1. HTML
  2. CSS


<table>Defines a table.
By default a table has no borders and is only as wide as the text it contains.
<tr>Defines a table row (only has value within <table> tag).
Table rows can contain either table data elements or table header cells.
<td>Table data element (standard table cell).
Can contain many types of data including text, images, links, lists, or even a table.
   cell 1
   cell 2
cell 1cell 2
<th>Table header cell (a table cell with bold text).<table>


Because the attributes used with input elements varies so much depending on the type of input you want to use, we have provided several specific examples of using different types of input.

<input type = "button"
       value = "change"
       onclick = "alert('clicked button')">
  • type is button
  • value is text that appears on button
  • onclick is event handler, specifies to call alert function when button is clicked
<input type = "color"
       value = "#001A57"
       id = "clr"
       onchange = "docolor()">
  • type is color picker
  • value is default color value
  • id lets us refer to input element in JavaScript
  • onchange is event handler, specifies to call docolor function when color is changed
<input type = "range"
       min = "10"
       max = "100"
       value = "10"
       id = "sldr"
       oninput = "dosquare()">
  • type is slider
  • min is minimum value, max is maximum value
  • value is default value
  • id lets us refer to input element in JavaScript
  • oninput is event handler, specifies to call dosquare function when slider is changed
<input type = "text"
       id = "finput">
  • type is text
  • id lets us refer to input element in JavaScript
<input type = "file"
       multiple = "false"
       accept = "image/*"
       id = "finput"
       onchange = "upload()">
  • type is file
  • multiple = "false" indicates user cannot select multiple files
  • accept = "image/*" indicates user can only select image files
  • value is default value
  • id lets us refer to input element in JavaScript
  • onchange is event handler, specifies to call upload function when input changes


Full list of CSS properties
Mozilla color picker tool

This website challenges people to use CSS to make as many different stylized versions as possible using the same HTML code.

Common CSS Properties and Values

PropertyExample ValuesUse withExample
text: paragraphs, links, list elements, table cells, headings
h1 {
    color: rgb(0,0,255);
p {
    font-size: 14pt;
td {
    text-align: center;
table, table cell, page backgrounds
body {
    background-color: #00FF00;
table cells
th {
    vertical-align: top;
img {
    float: right;
width100pxtables, table cells, images
img {
    width: 80px;
height100pxtables, table cells, images
td {
    height: 10px;
border-width5pxtables, table cells, images
table {
    border-width: 2px;
tables, table cells, images
table {
    border-style: solid;
tables, table cells, images
table {
    border-color: red;
10px dotted
5px dashed green
tables, table cells, images
table {
    border: 2px solid red;
table {
    border-collapse: collapse;

Course Specific JavaScript Functions


For these examples, assume

  • pix1 is a pixel at coordinate (100, 200) representing the color Duke blue, with RGBA values of (0, 26, 87, 255) 
  • pix2 is a pixel at coordinate (300, 400) representing the color white, with RGBA values of (255, 255, 255, 255) 
Function nameDescriptionExample
getX()returns the pixel’s x-coordinate within the imagepix1.getX() is 100
getY()returns the pixel’s y-coordinate within the imagepix1.getY() is 200
getRed()returns the value of the pixel’s red component (always in the range 0-255)pix1.getRed() is 0
getGreen()returns the value of the pixel’s green component (always in the range 0-255)pix1.getGreen() is 26
getBlue()returns the value of the pixel’s blue component (always in the range 0-255)pix1.getBlue() is 87
getAlpha()returns the value of the pixel’s alpha, or transparency, component (always in the range 0-255)pix1.getAlpha() is 255
setRed(newR)changes the value of the pixel’s red component to newR (if newR is not in the range of 0-255 it is changed to be in that range)pix1.setRed(255) changes the color to (255, 26, 87, 255) 
setGreen(newG)changes the value of the pixel’s green component to newG (if newG is not in the range of 0-255 it is changed to be in that range)pix1.setGreen(255) changes the color to (0, 255, 87, 255) 
setBlue(newB)changes the value of the pixel’s blue component to newB (if newB is not in the range of 0-255 it is changed to be in that range)pix1.setBlue(255) changes the color to (0, 26, 255, 255) 
setAlpha(newA)changes the value of the pixel’s alpha, or transparency, component to newA (if newA is not in the range of 0-255 it is changed to be in that range)pix1.setAlpha(100) changes the color to (0, 26, 87, 100) 
setAllFrom(otherPixel)changes the value of all of the pixel’s components (its red, green, blue, and alpha) to match otherPixel‘s valuespix2.setAllFrom(pix1) changes the color of pix2 to (0, 26, 87, 255) 


For these examples, assume the variable logo has the value of the image “devil.png” below. It is 100 pixels wide and 85 pixels tall.

Duke Blue Devil

Function nameDescriptionExample
new SimpleImage(filename)creates a SimpleImage to represent the image in filenamenew SimpleImage("devil.png") is
new SimpleImage(width, height)creates a SimpleImage whose dimensions are width by height. All the pixels in this image are black (0, 0, 0, 255)new SimpleImage(100, 100) is
new SimpleImage(fileInputElement)creates a SimpleImage to represent the image selected by the user using the fileInputElement given from the web pagevar input = document.getElementById("fileLoader");
var img = new SimpleImage(input);

assuming the user selected that image from their computer.
getWidth()returns the image’s width, or number of pixels in the X directionlogo.getWidth() is 100
getHeight()returns the image’s height, or number of pixels in the Y directionlogo.getHeight() is 85
getPixel(x,y)returns the pixel in this image at the coordinate (xy)logo.getPixel(0, 0) is the pixel (255, 255, 255, 255) 
setPixel(x,y,pixel)copies the RGBA values from the given pixel into pixel at the (x,y) coordinates givenlogo.setPixel(50, 42, pix2) changes the color to white 
setSize(width, height)resizes the image to be width by height. The image is scaled to fit into the new dimensions.logo.setSize(300, 85) is
values()returns all the pixels in the image, starting in the upper-left corner and moving down to the lower-right corner, providing a way to access each pixel in turn
for (var pixel of logo.values()) {
// modify pixel
drawTo(canvas)draws the image to canvas, for drawing images on web pagesvar canvas = document.getElementById("canvas");


Function nameDescriptionExample
print(something)displays something in the main “See It” area of the pageprint(image) shows the image
debug(something)displays something in the small area at the bottom of the “See It” area of the pagedebug(x) shows the value of the variable x

Standard JavaScript

Arithmetic Operations

+addition4 + 5 is 9
-subtraction9 - 5 is 4
*multiplication3 * 5 is 15
/division6 / 3 is 2
6 / 4 is 1.5
%mod/remainder5 % 3 is 2

Comparing Two Numbers

==is equal to3 == 3 is true
!=is not equal to3 != 3 is false
>=is greater than or equal to4 >= 3 is true
<=is less than or equal to4 <= 3 is false
>is strictly greater than4 > 3 is true
<is strictly less than3 < 3 is false

Combining Comparisons – Logic Operators

For these examples, assume the variable x has the value 5.

||returns true if at least one part of the comparison is true(x < 3 || x > 7) is false
(x < 3 || x < 7) is true
&&returns true only if both parts of the comparison are true(x > 3 && x < 7) is true
(x > 3 && x > 7) is false
!reverses the boolean value of a comparison(! x == 5) is false

Math Functions

Function nameDescriptionExample
abs(x)returns absolute value of xMath.abs(-3.6) is 3.6
Math.abs(3.2) is 3.2
ceil(x)returns x, rounded upwards to the nearest integerMath.ceil(3.6) is 4
Math.ceil(3.2) is 4
floor(x)returns x, rounded downwards to the nearest integerMath.floor(3.6) is 3
Math.floor(3.2) is 3
round(x)returns x, rounded x to the nearest integerMath.round(3.6) is 4
Math.round(3.2) is 3

Random Functions

Function nameDescriptionExample
random()returns a random number between 0 and 1Math.random() might return 0.523
Math.random() might return 0.983

Background Information

What is a Pixel?

Digital images are made of pixels. A pixel is a small point of colored light. When you look at a computer monitor, the image you see is actually made of a grid of these tiny dots of light. They are so small and so close together that it looks like one continuous picture. To get an idea of how small a pixel is, the monitor that I happen to be using as I write this has a resolution of 1440 x 900 (read as “1440 by 900”). That means that there are 1,440 pixels across the top and 900 pixels down one side, for a total of almost 1.3 million pixels.

This is what pixels might look like if they were magnified. This is an example of a 5×4 image because it is 5 pixels wide and 4 pixels tall.

Each pixel has a color value. We need a way to represent colors so that we can tell the computer which color to make each pixel. There are many color representations, but JavaScript uses a scheme called the RGBA color model. Basically, it means that a color is represented by four numbers:

  • R (the amount of red light)
  • G (the amount of green light)
  • B (the amount of blue light) and
  • A (called “alpha”, this number tells how transparent the color should be)

So each color is represented by these four numbers (“Everything’s a number”, remember?). Moreover, each of these number slots must have a value between 0 and 255. You may be wondering whether or not only 256 possibilities for each slot is enough to make all the many colors that we might want. If you have 256 possibilities for each of the R, G, and B values, (ignoring the transparency number for now) then the total number of colors available is over 16 million! It is estimated that the human eye can only detect 10 million different colors, so there’s no worry that you won’t be able to make any color you want.

Since the computer uses light to make a picture, the RGBA model is an additive color model. This means that the more the medium is added, the closer the color gets to white. Contrast this with using paint as a medium. That is a subtractive color model because the more paint you add, the further you get from white. So it should come as no surprise then that a color with R, G, and B values all 0 is black (no light) and a color with R, G, B values all 255 is white (pure light). Think of these numbers as knobs that you can turn up or down. If you turn on the red and blue lights and leave off the green light, you have shades of purple (R = 150, G = 0, B = 150, for example). The more you turn up the light, the higher the number goes and the brighter the color gets. How will you know what values to use for R, G, and B to make the color you want? If you search for “RGB color chart” on the Internet you will find lots of sites with palettes of colors and their corresponding values.

Transparency: Alpha Channel

The last value, called alpha, is also a number whose value must be between 0 and 255. This time the value of the number does not change the color’s hue, but rather the transparency of the color. If a pixel has an alpha value of 0, it is completely transparent, or invisible. If it has a value of 255, it is completely opaque. Using this transparency value allows you to have layers of color on the screen, or shapes that can be partially seen through other shapes.

Image Coordinate System

Finally, it is important to be able to distinguish one pixel from another. We do this by referring to each pixel’s location on the screen or image. Each pixel gets an X and Y value, where (0,0) is the top left corner of the screen. (This can take some getting used to as it’s not the way a Cartesian Plane is drawn in math class!)

The X value refers to how far right the pixel is, and the Y value refers to how far down the pixel is. For my computer monitor, which is 1440 x 900, the top left corner is (0,0), the top right is (1439,0), the bottom left is (0,899), the bottom right is (1439,899), and the middle is (720, 450).


Spring Boot and WordPress CMS Integration


There are a lot of excellent open source content management systems available today,  WordPress being one of them, which is widely used. WordPress is a PHP based CMS so not a lot of cohesion is available with other technologies like Java, and is simply ignored as a viable content management option just for being non-Java.

In this post I will demonstrate how WordPress can be integrated with Spring Boot applications, all made possible with WordPress REST plugin and a Spring client. Both of these are open source and available for free. Below is a simple design diagram that explains how this integration works. This post assumes that the reader has prior knowledge of WordPress and Spring Boot.

First install and activate WP-API v2 plugin on the WordPress site. After activation, you could verify that the plugin is working by accessing http://yoursite/wp-json/wp/v2/posts, which should display all the posts in JSON format.In the spring boot application add the following dependency in order to include the Spring WP-API client.

Below is a sample configuration we need in the file, so that we can connect our Spring Boot application to our WordPress site.

The Spring WP-API client needs the RestTemplate so lets create a bean in our Application and autowire the Spring client. We also need to add component scan annotation so that Spring finds and autowires all the required dependencies.

Now our spring boot application is all setup to connect to out WordPress site in order to retrieve and create content. So lets try and lookup all the posts having the keyword “Spring”, below is how we can do this.

The complete test application is available with the Spring WP-API client on Github.

This is just a small example of how we can integrate Spring Boot and WordPress. We can take this further by properly integrating WordPress in the Spring web applications platform, e.g. by enabling Single Sign On using the CAS plugin.

And we can evolve this design even further by having a second-level content storage, like a database or an in-memory caching solution etc. This storage can serve as a cache and can also be used for additional configuration, so that we display relevant content faster in our Spring applications.

For more information please see the documentation of the WordPress REST plugin and Spring WP-API client.

How to Create Spring Boot Application Step by Step


How to Create Spring Boot Application Step by Step

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this pageShare on TumblrShare on Reddit

Spring Boot had been built for Rapid Application Development. In this tutorial we will learn How to Create Spring Boot Application using some easy examples. We will also focus on How to deploy spring boot application in different application servers.

Here are the following topics that we will cover in this series:

  1. Create Spring Boot Application using
    • Eclipse STS
    • IntelliJ IDEA STS
  2. Run Spring Boot Application using
    • Java CLI
    • Eclipse/IntelliJ IDEA
  3. Create a Basic Spring Boot application using REST
  4. How to use Spring Actuator
  5. Deploy Spring Boot application in
    • IBM Liberty Profile
    • IBM Application Server 8.5

If you need an introduction of Spring Boot please find my previous post below.

Create Spring Boot Application using

The best way of bootstrapping Spring Boot application is by using Spring Initializr. Let’s first start by opening http// you already know, you can use either Maven or Gradle to build, however we will use Maven in this tutorial. Click on Switch to the full Version and you will be able to see the below screen.

Software Needed

  • JDK 1.8 (You can use 1.7 or 1.6)
  • Maven 3.x

Steps :

  • Select Maven Project
  • If you want, change the Group/Package name. We will use com.adeveloperdiary
  • Change the Artifact to SpringBoot, Name will automatically change to the same
  • Leave the packaging to Jar, Java Version to 1.8 (Make sure you have JDK 1.8 in your local or use 1.7 )
  • Either type the Dependencies or select them below. We will add Web and Actuator here
  • Click on Generate Project button to download the zip file

How to Create Spring Boot Application Step by Step

Now Extract the zip and you will have the following files.

How to Create Spring Boot Application Step by Step

Open Terminal and navigate to the above folder. Type mvn clean packageand press enter. The Build will start now.

How to Create Spring Boot Application Step by Step

Once the build has been completed, you will have the SpringBoot-0.0.1-SNAPSHOT.jar created inside the target folder.

The Size of the jar would be around 13MB since it will have the embedded Tomcat server in it.

How to Create Spring Boot Application Step by Step

Create Spring Boot Application using Eclipse

We will use STS Toolkit to bootstrap when using eclipse. I am using eclipse MARS .1 version. We will first install the STS (SpringSource Tools Suite). Open Eclipse Marketplace, Type STS in Find and install the STS.

How to Create Spring Boot Application Step by Step

Then open Spring perspective.

How to Create Spring Boot Application Step by Step

Create a New -> Spring Starter Project.

How to Create Spring Boot Application Step by Step

Enter the following details. Click Next.

How to Create Spring Boot Application Step by Step

Select Web and Actuator. Click on Next.

How to Create Spring Boot Application Step by Step

Click on Finish.

How to Create Spring Boot Application Step by Step

This should create the Spring Boot Project in Eclipse.

How to Create Spring Boot Application Step by Step

Create Spring Boot Application using IntelliJ IDEA

We will now use IntelliJ IDEA to create our Spring Boot Application.I recommend to use the latest version of IntelliJ. Create a New Project. Select Spring Initializr. Click on Next.

How to Create Spring Boot Application Step by Step

Enter the following details. Click Next.

How to Create Spring Boot Application Step by Step

Select Web and Actuator. Click Next.

How to Create Spring Boot Application Step by Step

Enter the project Name and click Finish.

How to Create Spring Boot Application Step by Step

Your Spring Boot Project has been created now.

How to Create Spring Boot Application Step by Step

Run Spring Boot Application using CLI

We had created the jar file, now we will run it from Command Line by executing this line

You should be able to see Spring Boot in the Command Line.

How to Create Spring Boot Application Step by Step

The server should have started and the default port number will also be displayed as below.

How to Create Spring Boot Application Step by Step

Run Spring Boot Application in Eclipse

Its much easier to run the Spring Boot app in eclipse. Select the project, Right Click and, move to Run As and click on Spring Boot App. Again, remember you need to select the project to get this option, not the pom file.

How to Create Spring Boot Application Step by Step

Here is the output.

How to Create Spring Boot Application Step by Step

Run Spring Boot Application in IntelliJ IDEA

Its probably most easy, click on the run icon.

How to Create Spring Boot Application Step by Step

You should be able to see the logs that the application has started.

How to Create Spring Boot Application Step by Step


Hope this Step by Step approach will help you. Next we will learn how to create RESTServices and use Actuator in Spring Boot. Later we will also learn how to deploy Spring Boot Application in IBM Liberty Profile and IBM WAS 8.5 Server.

This is the 2nd part of Getting Started with Spring Boot Series. Find all the parts here.

  1. An Introduction to Spring Boot
  2. How to Create Spring Boot Application Step by Step
  3. How to create RESTFul Webservices using Spring Boot
  4. How to deploy Spring Boot application in IBM Liberty and WAS 8.5