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.

Implementation of CRUD operations for database entity with AngularJS, Spring Boot and Spring-Data-JPA

In this article, thanks to Veselin Pavlov, we will see how to implement CRUD (Create, Read, Update, Delete) functionality for a database entity. We will start by creating the tables in the database, after that we will define the entity in the java code. We will use spring-data-jpa to implement JPA repositories and we will define a RestController with Restful services for the entity. After that we will implement user interface for the REST API, with the help of the AngularJS framework. The whole project is available in the following github repository.

Implementation of the back-end

We will start the implementation of the back-end by preparing the database. After that we will create a maven project with Spring Tool Suite and we will implement the rest of the back-end functionality.

Create the database tables

Let’s create the following tables: Department and Employee with relation many to one between them. Many employees can be in the same department but one employee has only one department. For the example I will use PostgreSQL instead of the in memory database, because I want to show you how to configure the database in the Spring ecosystem. Below are listed the queries that create the two tables:

Setup the project with maven

Ok we are ready with the database setup, now let’s create a maven project in the STS(Spring Tool Suite) IDE.

1. Download and install Spring Tool Suite.
2. Once you run it, go to File -> New -> Maven Project
3. Check “Create a simple project (skip archetype selection)” and click Next
4. Populate Group Id with package name like: eu.dreamix.crud, and populate Artifact Id with just the last of the package name – crud. The part in the Group Id with name “crud” is the name of the application. This link here describes the naming convention for Group Id and Artifact Id: https://maven.apache.org/guides/mini/guide-naming-conventions.html
5. Change the packaging to war and click Finish.
6. The first thing that we can notice is that we have an error in our pom file. This is because we chose war packaging but there is no web.xml file. We don’t need web.xml because we will use Spring Boot, so we simply have to add the necessary configuration and dependencies in the pom.xml file.
7. Change the pom file to include:

8. Call maven update by clicking with the right button on the project -> Maven -> Update Project (or simply press alt + F5). The error should disappear now.
9. The last step is to create a class with main method that will run our application. Create a package eu.dreamix.crud. Add a new class with a name CrudApp, check the checkbox to create main method. Modify the class according to the code below:

10. Now we have fully setup spring boot application. If we run the application it will start embedded tomcat server and we will be able to access it at localhost:8080. However we don’t have any actions implemented yet, so let’s create a simple rest controller to show a greeting message. I like to put the rest controllers in a sub package, so create a sub package eu.dreamix.crud.rest and create a class GreetingController:

11. If we run the application and access http://localhost:8080/ we will see our “Greetings!” message. We are ready with the initial setup of the application.

Implement JPA Entities

We have our application up and running, we can now create the JPA entities reflecting the tables that we created in the database.

1. The first step is to add the spring-data-jpa dependency in our pom file. Add the following dependency under the dependencies tag:

2. Now we have all the annotations that will allow us to define the entity. Firstly, create another package eu.dreamix.crud.domain. In this package we will put our entities which define the domain of the application. Create a class Department as follows:

As you can see the class is annotated with @Entity, which marks it as database entity. The field id of type Integer is marked with annotation @Id which is used to specify the primary key for the entity. The annotation @GeneratedValue marks the field to use auto increment and GeneretionType.IDENTITY defines the auto increment strategy. The other two fields are annotated with @NotNull which is very descriptive. It forces the fields to not accept null values.

3. Let’s create the Employee entity. It is a bit more complex, because we will implement many-to-one relationship with the department entity. Create a class Employee as follows:

Here we use @ManyToOne annotation to implement a many-to-one relationship between Employee and Department. With @JoinColumn we point the field that relates to the other table. In “name” we write the name of the column in the employee table and in “referencedColumnName” we write the name of the column in the department table. With @Table and @UniqueConstraint we implement a composite unique constraint for the fields department_id and name. This creates a restriction to prevent inserting same Employee in different Department.

4. We will continue by configuring the database connection. In order to connect the database with our project, we must create a configuration file that Spring can find. Spring can find the configuration from a lot of places but I like to put it in the resources folder. In this Spring Reference of Spring Boot, we can see all the places where we can put our confguration: http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#boot-features-external-config-application-property-files

So create a file in the the folder src/main/resources/config with the name application.yml, like it is shown in the screenshot.

CRUD

The content of the file is as follows:

We can also create a .properties file, but I find the yml format more pretty. So as you can see we configure the jdbc url, username, password and driver class. As you can notice we are using a postgres driver but we don’t have it yet in our project. In order to add the driver to our application we must add another dependency in the pom file. Add the following between the <dependencies> tag.

Note that if you are using other database, you need to add the driver for the particular database that you use. For example if you use MySQL, you must configure the MySQL driver.

Here I also want to mention that you can configure the application to use the so called code-first approach. Code-first means that we first design our entities as java classes and then the application creates the tables by itself. In order to configure this behavior in our application we need to add the following configuration under spring tag:

This key: hibernate.hbm2ddl.auto is from the hibernate library that spring-data-jpa uses. There are other values that can be configured. The update will only update or create the tables if they don’t exist.
One last thing about the configuration, we can change the type of the DataSource. Spring has several default choices if they are available in the classpath. You can read more about production DataSources in the Spring Boot Reference here: http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#boot-features-connect-to-production-database

That was all about the entities, there are a lot more useful annotations, however they are not included in this article. For example we often need to exclude some fields when we represent the objects in JSON and there is an annotation that can help us with this.

Implement JPA Repository

Now that we have all entities implemented, we can use them to map data from the tables as java objects. This is implemented with repositories. We will start by creating a simple employee repository.

1. Create a new package eu.dreamix.crud.repository. We will put all our repositories in this package.

2. Create an interface EmployeeRepository as follows:

That is all we need to create, update, read and delete records from the database programmatically. To be honest I was really surprised when I found out that I don’t need to implement any logic at all in order to communicate with the database. Spring is so smart that only from this code, it knows how to implement the interface and offer us the functionality. Here it is probably good to mention that we can add other methods that Spring will implement for us out of the box. For example we can add a method,  findByName(String name) and that will be enough to get the record with the given name. You can read more about this in Spring Boot Reference here: http://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/#boot-features-spring-data-jpa-repositories

3. Let’s create one more repository for the Department entity. Create an interface DepartmentRepository as follows:

You can notice here that we implemented one query method that makes searches by description.
That was all about the repositories. Pretty easy right?

Implement Services

This part is not really necessary but I like to create services in order to separate the business logic. For our simple example we don’t have a lot of business logic, however in a real project we will probably need the service layer. This is pretty standard architecture of a web application. We have a persistence layer, a business/service layer and presentation layer. Let’s create a simple service that will make all interactions with the repositories.

1. Create a new package eu.dreamix.crud.service. We will put all services in this package.

2. Create a class EmployeeService as follows:

In this service we have all methods that we need to create, update, delete and read records. We marked the class with @Service annotation, in order to inform spring that this is a service. We use @Autowired annotation in the constructor to autowire the EmployeeRepository. Note that this @Autowired annotation is not necessary if we have only one constructor as of spring 4.3 version, however I put it anyway because it is more descriptive that we use constructor injection. The implementation is very simple, we use the methods provided by the repository to manipulate the records. The Repository doesn’t offer an update method. The method save will update a record if it already exists and will create a new one if there is no such record yet. That is why for the save and update methods we first check if there is such an entry in the database. We throw appropriate exceptions for the situations that we are interested in. Later on we will handle them in the REST controllers.

3. Create a class DepartmentService as follows:

We are now ready with the services. The department service is a lot like the employee service, so I am not going to describe the implementation.

Implement REST Controller

Let’s implement now the rest controllers that our front-end will use to manipulate the entities. We will start with the employee resource.

1. Create a new class under eu.dreamix.crud.rest called EmployeeResource with the following content:

In order to define the class as a rest controller we use the @RestController annotation. With @RequestMapping(“/api”) we define a root path that all methods will go under. We use the same annotation @RequestMapping when we define the methods as well, but there we define specific path only applied for the method. With the same annotation we define the method type ( GET, POST, PUT, DELETE etc.) and the returned media type. With @RequestBody we mark that a method parameter should be expected in the body of the request. With @PathVariable we mark that a method parameter should be retrieved from the requested path. Check the path for the delete method, there we define a variable {id} in the path itself. There is one more kind of parameters called query parameters, they are defined with @RequestParam and they are retrieved again from the url path but after the question mark (for example /api/employee?name=John). The rest of the implementation is self descriptive, we call the methods from the EmployeeService and we handle the exceptions. Note that for the update method I make one validation if the employee id is null. This logic should be implemented in the service as well. Basically when I develop rest services I try to minimize the code in the rest controller and put everything in the services. Here I will mention that we can even get rid of the code that handles the exceptions with the aspect oriented concepts implemented in spring. We can define a behavior, in event of an exception, for all rest controllers. Then we won’t need to implement try and catch for every method in every rest controller. The annotation used for this is @ControllerAdvice but it is not part of this article.

2. Create a new class under eu.dreamix.crud.rest called DepartmentResource with the following content:

Again I won’t go into details about the implementation for DepartmentResource because it is very much similar to the EmployeeResource implementation.
With this we are finished with the the back-end and we can start implementing a client for our application.

Implementation of the front-end

The front-end will be implemented with AngularJS. We communicate with the back-end by making requests only for data. As comparison with other technologies, with JSF we prepare the UI in the back-end as well and we send the whole HTML to the client. However with the technology stack of this article we send the HTML only once and through JavaScript, we make asynchronous HTTP requests to retrieve data from the back-end. Then with the help of the JavaScript framework AngularJS we update the HTML accordingly.

Setup the AngularJS

Firstly we need to add new index.html file under /src/main/webapp and delete the GreetingController. By doing this we will make the spring boot load our index.html page at root, instead of the greeting message.

In order to use the AngularJS we simply have to add the dependency in our HTML. Since we will be making Http requests, we need to add another javascript to our project – angular-resource.js. I also include bootstrap in order to style and structure the UI, however this is not required. I use google CDN to add the javascripts in my project, but for a real project it is better to download the minified versions of the files and include them in the project. Those are the files that I include in the <head> of the html.

The jQuery is added because it is required by bootstrap. In order to create angular application I created another javascript under /webapp/app/ folder called app.js with the following content:

Note that every new javascript file that we create must be added in index.html as well. This code defines a new angular application, it is just one line but I like to keep the things separated. The ngResource is a module that our application uses. It comes from the file angular-resource.js. There is one last step, we must put ng-app attribute in our html <body> like this:

By doing this we define the scope of our application to be over the whole body.

Creating Angular Service to access the REST API

All the logic can be implemented in an angular controller, however it is a good idea to separate the logic that is not responsible for updating of the HTML in an angular service. We will put the logic that makes requests to the back-end in two services.

1. Create a file under webapp/app/ called employee.service.js and add it to the index.html. Below is the content of the file:

This code will create a service Employee. You probably noticed that we called again angular.module(), however this time we didn’t pass an array in the function. If we don’t pass an array of dependencies in the angular.module(), the function will return an already existing module with this name instead of creating new one. With the factory method we define a service, and with $Inject we include dependencies that we will use in our service. Here we are using the $resource factory which allows us to make REST calls to the back-end. It is a wrapper around $http and offers us more convenient way to implement our logic. You can read more about $resource in the angular documentation here: https://docs.angularjs.org/api/ngResource/service/$resource

2. Create a file under webapp/app/ called department.service.js with the following content:
angular.module(‘crudApp’).factory(‘Department’, Department);

This code will create a Department service. It is similar to the employee service.

Creating a controller

The logic in the controller should be only concerned with the flow of user actions and the displayed content. For the example I created only one controller called, GeneralController. Create a file in the folder webapp/app/general.controller.js and include the file in index html. Below is the content of the file:

With the controller() function we create an angular controller. In order to use our controller we must define it in the HTML as well. I want this controller to operate over the whole html so I added it in the body tag as follows:

You will probably notice that we use a lot $scope in the code. The $scope is used to attach variables and functions that we can use in the HTML. Through the scope we implement two way binding, meaning that if some variable gets updated in the controller, it will be reflected in the UI and if some value in the HTML changes it will be reflected in the controller as well. I won’t go over every method in the controller because they are pretty straight forward. Only the updating of a record consist of two actions. The first one is when we initialize the updating, this will put the content of the record that we want to update in the input fields and when we click submit it will save them in the database.

Creating the user interface

For the user interface as I mentioned I use the bootstrap library. The UI is very simple and it only demonstrates the functionality. It is implemented in the index.html file. Here is a screenshot of how it looks:

CRUD

Creating UI for Departments

Below is the html code to create, read, update and delete department entities. This code is located right under the body opening tag.

 

In this implementation we use several angular directives to attach the HTML with the javascript. One of them is ng-submit which takes function that is executed when the form is submitted. With ng-model we bind a javascript variable to html input field or select field. One interesting directive is ng-repeat. It is like a foreach loop and it repeats the html content defined inside it for every record. The ng-click again takes a function that is executed on every click of the component. We can use the curly brackets to write angular expressions, which are javascript code inside the HTML. For example {{department.name}} will display the field name of the object department.

Creating UI for Employees

The UI for Employees is very similar to the departments UI. Below is the code:

There is only one different part here, the select tag. Again with the help of angular, we can bind variable in which we want to save the selected value with ng-model and we can bind another variable from where the list of values are taken.

That was everything about the UI

Data Access Object (DAO) design pattern in Java

Data Access Object (DAO) design pattern in Java – Tutorial Example




Data Access Object or DAO design pattern is a popular design pattern to implement persistence layer of Java application. DAO pattern is based on abstraction and encapsulation design principles and shields rest of application from any change in the persistence layer e.g. change of database from Oracle to MySQL, change of persistence technology e.g. from File System to Database. For example, if you are authenticating the user using a relational database and later your company wants to use LDAP to perform authentication. If you are using DAO design pattern to access database, it would be relatively safe as you only need to make a change on Data Access Layer. DAO design pattern also keeps coupling low between different parts of an application. By using DAO design pattern your View Layer is completely independent of DAO layer and only Service layer has the dependency on it which is also abstracted by using DAO interface.

Btw, DAO or Data Access Object Pattern is not a GOF design pattern as prescribed by Gang of Four on the classic book, Design Patterns: Elements of Reusable Object-Oriented Software.  It’s not one of the object oriented design pattern but something which arises from the use of Encapsulation. By keeping data access code together, away from business logic so that it can be developed, optimized and change without impacting other layers of application e.g. Model and View layer.

You can further use Generics to template your DAO layer. If you are using Spring then you can leverage JdbcTemplate for performing JDBC calls which save a lot of boilerplate coding. Using DAO pattern to access database is one of the JDBC best practices to follow. 

What is Data Access Object (DAO) pattern in Java




Data access object design patter or DAO pattern in Java with ExampleIn short Data Access Object or DAO design pattern is a way to reduce coupling between Business logic and Persistence logic. Application business logic often needs domain objects which are persisted in either Database, File System or any other persistence storage. DAO pattern allows you to encapsulate code for performing CRUD operation against persistence from rest of application. Which means any change on persistence logic will not affect other layers of application which are already tested. DAO pattern enables an application to cope with any change in database provider or persistence technology.In next section, we will What are the main benefits of using DAO design pattern in Java application. If you are a J2EE developer, you should read Real World Java EE patterns and best practices, one of the best books to learn Java EE patterns for experienced Java JEE programmers.

 

Good book to learn Java EE Patterns

 

 

Benefits of using DAO design pattern
DAO or Data Access Object design pattern is a good example of abstraction and encapsulation object oriented principles. It separates persistence logic is a separate layer called Data access layer which enables application to react safely to change in Persistence mechanism. For example, if you shift from File-based persistence mechanism to Database, your change will be limited to data access layer and won’t impact Service layer or domain Objects. Data Access Object or DAO pattern is pretty much standard in Java application being it core Java, web application or enterprise application. Following are couple of more benefits of using DAO pattern in Java application:



 

1) DAO design pattern allows JUnit test to run faster as it allows to create Mock and avoid connecting to database to run tests. It improves testing because it’s easy to write test with Mock objects, rather than an Integration test with the database. In the case of any issue, while running Unit test, you only need to check code and not database. Also shields with database connectivity and environment issues.
2) Since DAO pattern is based on interface, it also promotes Object oriented design principle “programming for interface than implementation” which results in flexible and quality code.

 

How to use DAO Pattern in Java JEE Application

Here is a nice diagram how to implement Data Access Pattern in a Java and J2EE application. You can see that your DAO classes e.g. AddressDAO, PersonDAO, and CompanyDAO are accessing database and populating data into a Contact object.

A Client Service is not directly accessing these classes instead it is accessing it via a ContactDAO interface and object are created using ContactDAOFactory class which returns the DAO implementation based on the database vendor e.g. here it is returning classes which can interact with HSQL DB. You can return classes which can interact with Oracle, SQL Server or MySQL database as well.




 

Data Access Object Pattern in Java

 

 

DAO design pattern Example

In the core of Data Access Object or DAO pattern is a Java interface, which defines a various method to perform CRUD operation e.g. Create, Read, Update, and Delete. Based on your application back-end technology you can create different implementation of this interface e.g. JdbcDAOImpl to connect database using JDBC, HibernateDAOImple to use hibernate or FileDAOImpl if you are using the File system for persistence. Service layer which uses this Data Access Object will use interface to interact with Data access layer. Here is how a typical DAO Interface looks like:
public interface AccountDAO{
public boolean save(Account account);
public boolean update(Account account);
public boolean findByAccountNumber(int accountNumber);
public boolean delete(Account account);
}

it defines various methods to perform CRUD operation. Now you can create different implementation of this AccountDAO interface e.g. JdbcAccountDAOImpl or HibernateAccountDAOImpl. Your JdbcAccountDAOImpl will use JDBC API or Spring JdbcTemplate along with SQL Queries to perform CRUD operations.
That’s all on what is Data Access Object or DAO pattern in Java and what are benefits of using DAO pattern in Java application. We have also seen a simple example of How to implement Data Access Object pattern with AccountDAO interface. It’s standard and one of the standard JDBC practices to use DAO pattern to create the persistent layer in Java application.

Further Learning
Design Pattern Library
From 0 to 1: Design Patterns – 24 That Matter – In Java
Java Design Patterns – The Complete Masterclass

Other Java design pattern tutorials from Javarevisited blog

 

How to Read, Write XLSX File in Java – Apache POI Example

No matter how Microsoft is doing in comparison with Google, Microsoft Office is still the most used application in software world. Other alternatives like OpenOffice and LiberOffice have failed to take off to challenge MS Office. What this mean to a Java application developer? Because of huge popularity of MS office products you often need to support Microsoft office format such as word, Excel, PowerPoint and additionally Adobe PDF. If you are using JSP Servlet, display tag library automatically provides Excel, Word and PDF support. Since JDK doesn’t provide direct API to read and write Microsoft Excel and Word document, you have to rely on third party library to do your job. Fortunately there are couple of open source library exists to read and write Microsoft Office XLS and XLSX file format, Apache POI is the best one. It is widely used, has strong community support and it is feature rich.

You can find lot of examples of how to do with Excel using Apache POI online, which means you will never feel alone and has instant Google support if you stuck there. In this article, we will learn how to read and write excel files in Java. As I said, Excel files has two popular format .XLS (produced by Microsoft Officer version prior to 2007 e.g. MS Office 2000 and 2003) and .XLSX (created by Microsoft Office 2007 onwards e.g. MS Office 2010 and 2013).Fortunately Apache POI supports both format, and you can easily create, read, write and update Excel files using this library. It uses terms like workbook, worksheet, cell, row to keep itself aligned with Microsoft Excel and that’s why it is very easy to use. Apache POI also provides different implementation classes to handle both XLS and XLSX file format.One interesting thing with POI is that (I don’t know whether it’s intentional, accidentally or real) it has got some really funny names for its workbook implementations e.g.
How to read and write Excel file in Java

  1. XSSF (XML SpreadSheet Format) – Used to reading and writting Open Office XML (XLSX) format files.
  2. HSSF (Horrible SpreadSheet Format) – Use to read and write Microsoft Excel (XLS) format files.
  3. HWPF (Horrible Word Processor Format) – to read and write Microsoft Word 97 (DOC) format files.
  4. HSMF (Horrible Stupid Mail Format) – pure Java implementation for Microsoft Outlook MSG files
  5. HDGF (Horrible DiaGram Format) – One of the first pure Java implementation for Microsoft Visio binary files.
  6. HPSF (Horrible Property Set Format) – For reading “Document Summary” information from Microsoft Office files.
  7. HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
  8. HPBF (Horrible PuBlisher Format) – Apache’s pure Java implementation for Microsoft Publisher files.
  9. DDF (Dreadful Drawing Format) – Apache POI package for decoding the Microsoft Office Drawing format.

It’s very important that you know full form of these acronyms, otherwise it would be difficult to keep track of which implementation is for which format. If you are only concerned about reading Excel files then at-least remember XSSF and HSSF classes e.g. XSSFWorkBook and HSSFWorkBook.

How to Read Excel File (XLSX) in Java

In our fist example we will learned about reading current popular Excel file format i.e. file with extension .XLSX. This is a XML spread sheet format and other spreadsheet software like OpenOffice and LiberOffice also use this format. In order to read Excel file, you need to first download Apache POI Jar files, without these your code will neither compiler nor execute. If you hate to maintain JARs by yourself, use Maven. In Eclipse IDE, you can download M2Eclipse plug-in to setup Maven project. Once you done that, add following dependencies in your pom.xml (project object model) file.

    
        org.apache.poi
        poi
        3.11-beta2

By the way as Norbert pointed out, The classes for OOXML format (such as XSSF for reading .xlsx format) are in a different Jar file. You need to include the poi-ooxml jar in your project, along with the dependencies for it. When you add poi-ooxml JAR as dependency via Maven, it will also add other required dependencies by itself. For example adding below XML snippet in pom.xml will download four JAR files

        org.apache.poi
        poi-ooxml
        3.11-beta2

poi-ooxml-3.11-beta2.jar
poi-ooxml-schemas-3.11-beta2.jar
xmlbeans-2.6.0.jar
stax-api-1.0.1.jar

If you are not using Maven then add following JAR files in your Java program’s classpath
poi-3.11-beta2.jar
commons-codec-1.9.jar
poi-ooxml-3.11-beta2.jar
poi-ooxml-schemas-3.11-beta2.jar
xmlbeans-2.6.0.jar
stax-api-1.0.1.jar

Here is how our sample Excel 2013 File look like, remember this has saved in .xlsx format.

How to read write XLS and XLSX file format in Java

add here is code to read that Excel file. First two lines are very common, they are to read file from file system in Java, real code starts from 3rd line. Here we are passing a binary InputStream to create instance of XSSFWorkBook class, which represent a Excel workbook. Next line gives us a worksheet from book, and from there we are just going through each row and then each column. Cell represent a block in Excel, also known as cell. This is where we read or write data. Cell can be any type e.g. String, numeric or boolean. Before reading value you must ascertain correct type of cell. After that just call corresponding value method e.g. getStringValue() or getNumericValue() to read data from cell. This how exactly you read rows and columns from Excel file in Java. You can see we have used two for loop, one to iterate over all rows and inner loop is to go through each column.

 File myFile = new File("C://temp/Employee.xlsx");
            FileInputStream fis = new FileInputStream(myFile);

            // Finds the workbook instance for XLSX file
            XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
           
            // Return first sheet from the XLSX workbook
            XSSFSheet mySheet = myWorkBook.getSheetAt(0);
           
            // Get iterator to all the rows in current sheet
            Iterator rowIterator = mySheet.iterator();
           
            // Traversing over each row of XLSX file
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();

                // For each row, iterate through each columns
                Iterator cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t");
                        break;
                    default :
                 
                    }
                }
                System.out.println("");
            }

Let me know if you have trouble to understand any of line. They are very simple and self-explanatory but if you need additional detail, just drop us a comment.

How to write XLSX File in Java

 

Writing  into Excel file is also similar to reading, The workbook and worksheet classes will remain same, all you will do is to create new rows, columns and cells. Once you are done creating new rows in your Excel file in memory, you need to open an output stream to write that data into your Excel File. This will save all update you made in existing file or in a new file which is created by Java’s File class. Here is step by step code of updating an existing Excel file in Java. In first couple of lines we are creating rows in form of object array and storing them as value in HashMap with key as row number. After that we loop through HashMap and insert each row at the end of last row, in other word we are appending rows in our Excel file. Just like before reading we need to determine type of cell, we also need to do the same thing before writing data into cell. This is done by using instanceof keyword of Java. Once you are done with appending all rows form Map to Excel file, save the file by opening a FileOutputStream and saving data into file system.

// Now, let’s write some data into our XLSX file

            Map<String, Object[]> data = new HashMap<String, Object[]>();
            data.put("7", new Object[] {7d, "Sonya", "75K", "SALES", "Rupert"});
            data.put("8", new Object[] {8d, "Kris", "85K", "SALES", "Rupert"});
            data.put("9", new Object[] {9d, "Dave", "90K", "SALES", "Rupert"});
         
            // Set to Iterate and add rows into XLS file
            Set newRows = data.keySet();
         
            // get the last row number to append new data          
            int rownum = mySheet.getLastRowNum();         
         
            for (String key : newRows) {
             
                // Creating a new Row in existing XLSX sheet
                Row row = mySheet.createRow(rownum++);
                Object [] objArr = data.get(key);
                int cellnum = 0;
                for (Object obj : objArr) {
                    Cell cell = row.createCell(cellnum++);
                    if (obj instanceof String) {
                        cell.setCellValue((String) obj);
                    } else if (obj instanceof Boolean) {
                        cell.setCellValue((Boolean) obj);
                    } else if (obj instanceof Date) {
                        cell.setCellValue((Date) obj);
                    } else if (obj instanceof Double) {
                        cell.setCellValue((Double) obj);
                    }
                }
            }
         
            // open an OutputStream to save written data into XLSX file
            FileOutputStream os = new FileOutputStream(myFile);
            myWorkBook.write(os);
            System.out.println("Writing on XLSX file Finished ...");


Output
Writing on XLSX file Finished ...

Here is how our updated Excel file looks after adding three more rows

How to read Excel File in Java using Apache POI

How to read Excel (XLS) file in Java

Reading XLS file is no different than reading an XLSX format file, all you need to do is to use correct workbook implementation for XLS format e.g. instead of using XSSFWorkbook and XSSFSheet , you need to use HSSFWorkbook and HSSFSheet classes from Apache POI library.  As I said before, POI has got some really funny names for different XLS formats e.g. Horrible SpreadSheet Format to represent old Microsoft Excel file format (.xls). Remembering them can be hard but you can always refer to their online Javadoc. You can reuse rest of code given in this example, for example you can use same code snippet to iterate over rows, columns and from reading/writing into a particular cell. Given they are two different format, some features will not be available on XLS file processors but all basic stuff remain same.

Error and Exception

If you happen to use incorrect classes e.g. instead of using XSSFWorkbook  to read XLSX file, if you use HSSFWorkbook then you will see following error :

Exception in thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
 at org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:131)
 at org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:104)
 at org.apache.poi.poifs.filesystem.POIFSFileSystem.(POIFSFileSystem.java:128)
 at org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:361)
 at org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:342)
 at App.main(App.java:25)

Java Program to Read/Write Excel Files using Apache POI

Here is our full Java program to read/write from existing Excel file in Java. If you are using Eclipse IDE, just create a Java Project, copy the code and paste it there. No need to create proper package structureand Java source file with same name, Eclipse will take care of that. If you have Maven and Eclipse plugin installed, instead create a Maven Java project, this will also help you to download Apache POI Jar files.

 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * Sample Java program to read and write Excel file in Java using Apache POI
 *
 */
public class XLSXReaderWriter {

    public static void main(String[] args) {

        try {
            File excel = new File("C://temp/Employee.xlsx");
            FileInputStream fis = new FileInputStream(excel);
            XSSFWorkbook book = new XSSFWorkbook(fis);
            XSSFSheet sheet = book.getSheetAt(0);

            Iterator itr = sheet.iterator();

            // Iterating over Excel file in Java
            while (itr.hasNext()) {
                Row row = itr.next();

                // Iterating over each column of Excel file
                Iterator cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {

                    Cell cell = cellIterator.next();

                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t");
                        break;
                    default:

                    }
                }
                System.out.println("");
            }

            // writing data into XLSX file
            Map<String, Object[]> newData = new HashMap<String, Object[]>();
            newData.put("7", new Object[] { 7d, "Sonya", "75K", "SALES",
                    "Rupert" });
            newData.put("8", new Object[] { 8d, "Kris", "85K", "SALES",
                    "Rupert" });
            newData.put("9", new Object[] { 9d, "Dave", "90K", "SALES",
                    "Rupert" });

            Set newRows = newData.keySet();
            int rownum = sheet.getLastRowNum();

            for (String key : newRows) {
                Row row = sheet.createRow(rownum++);
                Object[] objArr = newData.get(key);
                int cellnum = 0;
                for (Object obj : objArr) {
                    Cell cell = row.createCell(cellnum++);
                    if (obj instanceof String) {
                        cell.setCellValue((String) obj);
                    } else if (obj instanceof Boolean) {
                        cell.setCellValue((Boolean) obj);
                    } else if (obj instanceof Date) {
                        cell.setCellValue((Date) obj);
                    } else if (obj instanceof Double) {
                        cell.setCellValue((Double) obj);
                    }
                }
            }

            // open an OutputStream to save written data into Excel file
            FileOutputStream os = new FileOutputStream(excel);
            book.write(os);
            System.out.println("Writing on Excel file Finished ...");

            // Close workbook, OutputStream and Excel file to prevent leak
            os.close();
            book.close();
            fis.close();

        } catch (FileNotFoundException fe) {
            fe.printStackTrace();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
}
Output
ID NAME SALARY DEPARTMENT MANGER 
1.0 John 70K IT Steve 
2.0 Graham 80K DATA Carl 
3.0 Sodhi 60K IT Ram 
4.0 Ram 100K IT Alex 
5.0 Carl 150K DATA Alex 
7.0 Sonya 75K SALES Rupert 
9.0 Dave 90K SALES Rupert 
8.0 Kris 85K SALES Rupert 
Writing on Excel file Finished ...
That’s all about how to read and write Excel file in Java. We have learned to read/write both XLSand XLSX format in Java, which is key to support old Microsoft Excel files created using Microsoft Office version prior to 2007. Though there are couple of other alternative libraries to read Excel files from Java program, but Apache POI is the best one and you should use it whenever possible. Let me know if you face any problem while running this program in your Eclipse IDE or from command prompt. Just make sure to include right set of JAR in your CLASSPATH, alternatively used Maven to download JAR.
 

Source: https://www.java67.com/2014/09/how-to-read-write-xlsx-file-in-java-apache-poi-example.html#ixzz5HDAJrtG2

And one more time…

Java Program To write Data In Excel File

In this instructional exercise, you will perceive how to compose on an exceed expectations sheet by utilizing Java. Or in easy words, you will learn, how to write data or insert data into excel file in Java. For this, you need a library called POI which will peruse and write in exceed expectations sheet.

POI is a noticeable API that empowers programming specialists to make, change, and show MS Office records using Java programs.

Java Program To Write Data In Excel File

We need certain container documents to get to the POI library. We essentially need four container records that can work the exceed expectations sheet utilizing java. At that point, import the required bundles from container documents. The required container document bundles are:

  1. import org.apache.poi.ss.usermodel.Cell;
  2. import org.apache.poi.ss.usermodel.Row;
  3. import org.apache.poi.ss.usermodel.Sheet;
  4. import org.apache.poi.ss.usermodel.Workbook;

Then you have to create particular objects.
The following objects you need is:

public static Workbook wb;
public static Sheet s;
public static FileInputStream fi;
public static FileOutputStream fo;

once you mentioned all the files we need to open the file in the main function. Suppose we have one excel file named data.xlsx
First, create one excel file by-

  1. fi=new FileInputStream(“data.xlsx”);

Once you are done with accessing file name create the workbook by  command:

wb=WorkbookFactory.create(fi);

Then write below command to access a sheet:

s=wb.getSheet("sheet");

Now, you need to clarify how many rows you need to enter in excel file. You can enter as many of the data you need to write in an excel file by using for loop.
you can create a row by using CreateRow() function and to set the value in that row use SetCellValue() function.

The below code will help you to write a data in an excel file:

  1. import java.io.FileInputStream;
  2. import java.io.FileOutputStream;
  3. import java.io.FileNotFoundException;
  4.  
  5. import org.apache.poi.ss.usermodel.*;
  6.  
  7. public class ExcelDemo
  8. {
  9. public static Workbook wb;
  10. public static Sheet s;
  11. public static FileInputStream fi;
  12. public static FileOutputStream fo;
  13. public static Row r;
  14. public static Cell c;
  15.  
  16. public static void main(String[] args) throws Exception
  17. {
  18. fi=new FileInputStream(“data.xlsx”);
  19. wb=WorkbookFactory.create(fi);
  20. s=wb.getSheet(“sheet”);
  21. //create one row
  22. r=s.createRow(1);
  23. c=row.createCell(0);
  24. c.setCellValue(“Raj”);
  25. System.out.println(c.getStringCellValue());
  26. fo=new FileOutputStream(“data.xlsx”);
  27. wb.write(fo);
  28. fo.flush();
  29. fo.close();
  30.  
  31. System.out.println(“Data entered in a Data excel file”);
  32. }
  33. }

I hope, this tutorial gives you a clear idea on how to insert data into excel file in Java.

Source:  https://www.codespeedy.com/java-program-to-write-data-in-excel-file/

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
buttons.
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/GreetingServlet.java and tut-install/javaeetutorial5/examples/web/hello2/src/servlets/ResponseServlet.java). 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:
    tut-install/javaeetutorial5/examples/web/
  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:
    http://localhost:8080/hello1
  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
buttons.

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:
    domain-dir/applications/j2ee-modules/context-root/.reload
  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:

http://host:port/context-root/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:
    tut-install/javaeetutorial5/examples/web/
  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:
    tut-install/javaeetutorial5/examples/web/
  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:

...
import javax.xml.ws.WebServiceRef;
...
public class ResponseServlet extends HTTPServlet {
@WebServiceRef(wsdlLocation=
    "http://localhost:8080/helloservice/hello?wsdl")
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:

[sql]

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:

Source:
https://docs.oracle.com/cd/E19879-01/819-3669/bnadr/index.html

HTML

HTML

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

TagDescriptionExample
<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>
bold
<em>Apply emphasis to text<em>emphasis</em>
emphasis
<img>

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="http://bit.ly/1QfkvVw" width="100px">
<a>

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="https://www.duke.edu/">Duke University</a>
Duke University
<div>Defines a section of the web page.<div><p>This paragraph is inside a div.</p></div>

Lists

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

Tables

TagDescriptionExample
<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.
<table>
 <tr>
  <td>
   cell 1
  </td>
  <td>
   cell 2
  </td>
 </tr>
</table>
cell 1cell 2
<th>Table header cell (a table cell with bold text).<table>
 <tr>
  <th>
   heading
  </th>
 </tr>
 <tr>
  <td>
   content
  </td>
 </tr>
</table>
heading
content

Input

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.

ExampleDescription
<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

CSS

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
colorblue
rgb(0,0,255)
#0000FF
text: paragraphs, links, list elements, table cells, headings
h1 {
    color: rgb(0,0,255);
}
font-size12pt
16px
100%
text
p {
    font-size: 14pt;
}
text-alignleft
right
center
justify
text
td {
    text-align: center;
}
background-colorblue
rgb(0,0,255)
#0000FF
table, table cell, page backgrounds
body {
    background-color: #00FF00;
}
vertical-aligntop
middle
bottom
table cells
th {
    vertical-align: top;
}
floatleft
right
images
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;
}
border-stylesolid
dotted
dashed
tables, table cells, images
table {
    border-style: solid;
}
border-colorblue
rgb(0,0,255)
#0000FF
tables, table cells, images
table {
    border-color: red;
}
border5px
10px dotted
5px dashed green
tables, table cells, images
table {
    border: 2px solid red;
}
border-collapsecollapsetable
table {
    border-collapse: collapse;
}

Course Specific JavaScript Functions

SimplePixel

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) 

SimpleImage

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);
 is

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");
logo.drawTo(canvas);

Printing

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

OperatorDescriptionExample
+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

OperatorDescriptionExample
==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.

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