Tag: CSS3

HTML App Launcher

HTML App Launcher

App Launcher
App Launcher

    
I love web technology for one simple reason; making GUIs that are useful and have great logic flow is easy to do and virtually universal for platform access. I’m a lazy guy and want to launch apps quickly and through my browser than having to go to a Start Menu or search for the proper cli command. Today, I’ll show you how to make it so you can launch your favorite apps through a web page. First, we need to get all the necessary programs and setup our project folder structure.


To Top


To Bottom

Programs & Project Structure

Installs

 sudo apt-get install sqlite3 php-sqlite3 sqlitebrowser php firefox 

The first few programs (sqlite3, php-sqlite3, and sqlitebrowser) are pretty straightforward for why we need them. These deal with our database and sqlitebrowser is a quick way of viewing, editing, and adding data entries to our database. PHP will be the server side language which we are using to interact with the database and run the programs we have. Firefox is the browser I’m using to view the app launcher and has a plugin you can install to set your default New Tab page. Now that we have these installed, let’s create our project folder and the skeletal structure.

Folder & File Setup

mkdir appRunner

cd appRunner

mkdir -p resources/{css,js,php,db}

touch index.html resources/css/base.css resources/css/main.css \
                 resources/js/events.js resources/js/launcher.js \
				 resources/php/launcher.php resources/php/dbController.php

    
Since I’m using Linux, I like running easy commands that’ll get the layout built quickly. We are simply making a folder called appRunner and then changing directory to it. We then make a parent folder called resources with the respective sub folders: css, js, php, and db. Once that is completed, we create a new index file plus a slew of files for the application itself. With the base layout created, we still have some preliminary work to do before writing code. Let’s get the database up and running with some app entries.

Database Setup & Enteries

cd resources/db/

sqlite3 apps.db

CREATE TABLE Apps(id INTEGER, app MAX, icon BLOB, command MAX);

    
INTEGER is just that, a number. MAX means that the field can take the largest string possible and BLOB means the field is able to store binary data such as the image itself. Now, let’s insert initial app data so we have reference info to work off of. Here I have added 4 entries using sqlitebrowser‘s interface. Note: You can add your own apps and their commands than use mine since you may or may not have what I have.

App data
App data

OK, we have the base application setup and we are ready to code. But, first, we are gunna review what our logic will be and why we setup everything the way we did.

Logic & Code Flow

HTML

<body onload="getApps()">

<div class="container">
    <div id="appsMenu">

    </div>

    <div id="message">

    </div>
</div>

<script src="resources/js/events.js" charset="utf-8"></script>
<script src="resources/js/launcher.js" charset="utf-8"></script>

     For this quick setup, the main focus is about the application list and a message field. We also want an onload event on the body to make a request to the server to return all stored apps in the database. In addition, we are splitting up the JavaScript scripts into two files to keep things cleaner. The events.js will handle user interactions while launcher.js is the meat of the client side logic. Code and the logic breakdown for these js files are further down.

CSS

.container {
    display: table;
    margin: 0 auto;
}

.app {
    float: left;
    padding: 0em 2em;
}

.app:hover {
    cursor: pointer;
    background-color: rgba(43, 126, 144, 1);
    color: rgba(255, 255, 255, 1);
}

.icon {
    width: 72px;
    height: 72px;
}

     Here is the most important part of our CSS files. We have two files but main.css has the core logic while base.css has some house cleaning logic. Here, we setup a container with a display of table and margins set to center align the div. Our .app sets our div elements to float left so that apps are listed in a row than column. We do padding to make things look nice and a hover part to indicate what’s being selected. The .icon CSS sets our app icon images to be 72×72 pixles.

JS

// What we are working from with our JavaScript logic
<div name="34::Leafpad" class="app">
<img class="icon" src="" />
<p class="appName">Leafpad</p>
</div>

document.ondblclick = (event) => {
    let elm = event.target;

    // left-click detect
    if (event.which == 1) {
        if (elm.className.includes("app")) {
            launchApp(elm.getAttribute("name"));
        } else if (elm.className.includes("icon") ||
                   elm.className.includes("appName")) {
                       launchApp(elm.parentElement.getAttribute("name"));
        }
    }
}

     Here is the double click logic when clicking on our listed application. Basically, we check to see if there are any class names and from there if we are clicking on the root or sub element of our HTML structure for our listed application. We could make this cleaner by having an internal div that’s absolute positioned and is z-indexed above the image and paragraph tag. Then, we would look for just that; but, this method is a little more robust if you want controls for the app such as deletion, hiding, renaming, or something else. We then call a command in our launcher.js file to run the application by sending info to the server. The info we send is the id and name which we get by pulling the name attribute info from the app’s root div.

const launchApp = (app) => {
    let args = app.split("::");
    doAjax("launchApp=true&id=" + args[0] + "&app=" + args[1]);
}

const doAjax = (data) => {
    let xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            // Send the returned data to further process
            if (this.responseXML != null) {
                handleXMLReturnData(this.responseXML);
            } else {
                alertMessage("error", "No content returned. No apps in database.");
            }
        }
    };

    xhttp.open("POST", "resources/php/appManager.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.overrideMimeType('application/xml'); // Force return to be XML
    xhttp.send(data);
}

     You will note that here we are splitting the passed string from the events.js into its respective id and app name to pass to our doAjax command. I’ve setup the data this way to try and insure there will be no duplicates in the database query return info. So, even if there is a duplicate id value the app name makes sure we get the correct one. The rest here is simple AJAX logic where we pass the arguments and an identifying argument to the server script to determine the proper action to take. We then process the XML return data from the server as a message or the application data we queried for.

const handleXMLReturnData = (xml) => {
    let rootTag = xml.children[0];
    if (rootTag.tagName.includes("LIST")) {
        //<APP>
        //  <ID><ID></ID>
        //  <NAME><APP_NAME></NAME>
        //  <ICON><BASE64_ENCODED_ICON></ICON>
        //</APP>

        let apps = rootTag.getElementsByTagName("APP");
        let size = apps.length;
        for (var i = 0; i < size; i++) {
            let app  = apps[i];
            let id   = app.children[0].innerHTML;
            let name = app.children[1].innerHTML;
            let icon = app.children[2].innerHTML;
            createAppRef(id, name, icon);
        }
    } else if (rootTag.tagName.includes("SERV_MSG")) {
        alertMessage(rootTag.className, rootTag.innerHTML);
    }
}

const createAppRef = (id, appName, icon) => {
    let divTag  = document.createElement("DIV");
    let imgTag  = document.createElement("img");
    let pTag    = document.createElement("P");
    let text    = document.createTextNode(appName);

    divTag.setAttribute("name", id + "::" + appName);
    divTag.className = "app";
    imgTag.className = "icon";
    pTag.className   = "appName";
    imgTag.src       = "data:image/png;base64," + icon;

    pTag.append(text);
    divTag.append(imgTag);
    divTag.append(pTag);
    document.getElementById('appsMenu').append(divTag);
}

Now, handleXMLReturnData is parsing the return data and either displaying a server message or returning the list of apps in the database. The listed apps are parsed from a loop and we create the proper HTML for each using createAppRef. Note that we simply create a div, img, and p tag and then setup proper class names and the root’s name attribute. For the image, b/c it’s stored as a BLOB we return a BASE64 encoded string which we assign to the src attribute of img. We are identifying them as png type images since that’s what I’m using for each. This keeps things quick ‘n dirty but isn’t the best setup long term. OK, let’s finish this up by looking at our main PHP file.

PHP

function launchApp($ID, $APP) {
    $db = new SQLite3('apps.db');

    if($db === false) {
        $message = "Server: [Error] --> Database connection failed!";
        serverMessage("error", $message);
        die("ERROR: Could not connect to db.");
    }

    $stmt = $db->prepare('Select command FROM Apps WHERE id = :id AND app = :app');
    $stmt->bindValue(":id", $ID, SQLITE3_INTEGER);
    $stmt->bindValue(":app", $APP, SQLITE3_TEXT);
    $res = $stmt->execute();

    $row = $res->fetchArray(SQLITE3_ASSOC);
    $command = 'nohup ' . $row['command'] . ' > /dev/null &';
    shell_exec($command);

    $message = "Server: [Success] --> Launched " . $APP . "!";
    serverMessage("success", $message);
}


// Determin action
chdir("../db/");
if (isset($_POST['getData'])) {
    getData();
} elseif (isset($_POST['launchApp'],
                $_POST['id'],
                $_POST['app'])) {
    launchApp($_POST['id'], $_POST['app']);
} else {
    $message = "Server: [Error] --> Illegal Access Method!";
    serverMessage("error", $message);
}

?>

     When we launch an app, all that we are really doing is passing the id and app name to the PHP scriopt. The script queries the database and returns the command that is stored. Then, the script will run a shell_exec command with the returned string. This is what launchApp is doing here. It then return a server message of success or failure which our JavaScript handles and puts onto our page. Look at the Full PHP section to see how the apps list is returned and how messages are handled.

Conclusion

Discussion

     And that’s it for this tut. It is a simple way of making a personalized launcher for your favorite apps so that you don’t need to go to the Start Menu each time. You can use this by running a quick and dirty server through this guide:


Servers
Quick Test Server

If you are using Firefox and want it as your default tab when you open new tabs then please check out my plugin: Alt Tab Page

Full Code

Full HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>App Runner</title>
    <link rel="stylesheet" href="resources/css/base.css">
    <link rel="stylesheet" href="resources/css/main.css">
</head>
<body onload="getApps()">

<div class="container">
    <div id="appsMenu">

    </div>

    <div id="message">

    </div>
</div>

<script src="resources/js/events.js" charset="utf-8"></script>
<script src="resources/js/launcher.js" charset="utf-8"></script>
</body>
</html>

Full CSS

base.css
html, body {
    margin: 0em;
	padding: 0em;
}

ul, ol, li {
    list-style: none;
}
main.css
.container {
    display: table;
    margin: 0 auto;
}

.app {
    float: left;
    padding: 0em 2em;
}

.app:hover {
    cursor: pointer;
    background-color: rgba(43, 126, 144, 1);
    color: rgba(255, 255, 255, 1);
}

.icon {
    width: 72px;
    height: 72px;
}


/* Messages coloring */
.error, .warnning, .success {
    float: left;
    clear: both;
    width: 100%;
    text-align: center;
}


.error { color: rgb(255, 0, 0); }
.warnning { color: rgb(255, 168, 0); }
.success { color: rgb(136, 204, 39); }

Full JS

events.js
document.ondblclick = (event) => {
    let elm = event.target;

    // left-click detect
    if (event.which == 1) {
        if (elm.className.includes("app")) {
            launchApp(elm.getAttribute("name"));
        } else if (elm.className.includes("icon") ||
                   elm.className.includes("appName")) {
                       launchApp(elm.parentElement.getAttribute("name"));
        }
    }
}
launcher.js
const getApps = () => {
    doAjax("getData=true");
}

const launchApp = (app) => {
    let args = app.split("::");
    doAjax("launchApp=true&id=" + args[0] + "&app=" + args[1]);
}

const doAjax = (data) => {
    let xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
            // Send the returned data to further process
            if (this.responseXML != null) {
                handleXMLReturnData(this.responseXML);
            } else {
                alertMessage("error", "No content returned. No apps in database.");
            }
        }
    };

    xhttp.open("POST", "resources/php/appManager.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.overrideMimeType('application/xml'); // Force return to be XML
    xhttp.send(data);
}

const handleXMLReturnData = (xml) => {
    let rootTag = xml.children[0];
    if (rootTag.tagName.includes("LIST")) {
        let apps = rootTag.getElementsByTagName("APP");
        let size = apps.length;
        for (var i = 0; i < size; i++) {
            let app  = apps[i];
            let id   = app.children[0].innerHTML;
            let name = app.children[1].innerHTML;
            let icon = app.children[2].innerHTML;
            createAppRef(id, name, icon);
        }
    } else if (rootTag.tagName.includes("SERV_MSG")) {
        alertMessage(rootTag.className, rootTag.innerHTML);
    }
}

const createAppRef = (id, appName, icon) => {
    let divTag  = document.createElement("DIV");
    let imgTag  = document.createElement("img");
    let pTag    = document.createElement("P");
    let text    = document.createTextNode(appName);

    divTag.setAttribute("name", id + "::" + appName);
    divTag.className = "app";
    imgTag.className = "icon";
    pTag.className   = "appName";
    imgTag.src       = "data:image/png;base64," + icon;

    pTag.append(text);
    divTag.append(imgTag);
    divTag.append(pTag);
    document.getElementById('appsMenu').append(divTag);
}

const alertMessage = (type, message) => {
    document.getElementById('message').innerHTML =
        "<p class=\"" + type +"\">" + message + "</p>";
}

Full PHP

appManager.php
<?php
include_once 'serverMessanger.php';

function getData() {
    $db = new SQLite3('apps.db');

    if($db === false) {
        $message = "Server: [Error] --> Database connection failed!";
        serverMessage("error", $message);
        die("ERROR: Could not connect to db.");
    }

    $res = $db->query('Select id, app, icon FROM Apps');
    $GeneratedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><LIST>";
    while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
        $GeneratedXML .= "<APP>" .
               "<ID>"   . $row['id'] . "</ID>" .
               "<NAME>" . $row['app'] . "</NAME>" .
               "<ICON>" . base64_encode($row['icon']) . "</ICON>" .
           "</APP>";
    }
    $GeneratedXML .= "</LIST>";
    echo $GeneratedXML;
}

function launchApp($ID, $APP) {
    $db = new SQLite3('apps.db');

    if($db === false) {
        $message = "Server: [Error] --> Database connection failed!";
        serverMessage("error", $message);
        die("ERROR: Could not connect to db.");
    }

    $stmt = $db->prepare('Select command FROM Apps WHERE id = :id AND app = :app');
    $stmt->bindValue(":id", $ID, SQLITE3_INTEGER);
    $stmt->bindValue(":app", $APP, SQLITE3_TEXT);
    $res = $stmt->execute();

    $row = $res->fetchArray(SQLITE3_ASSOC);
    $command = 'nohup ' . $row['command'] . ' > /dev/null &';
    shell_exec($command);

    $message = "Server: [Success] --> Launched " . $APP . "!";
    serverMessage("success", $message);
}


// Determin action
chdir("../db/");
if (isset($_POST['getData'])) {
    getData();
} elseif (isset($_POST['launchApp'],
                $_POST['id'],
                $_POST['app'])) {
    launchApp($_POST['id'], $_POST['app']);
} else {
    $message = "Server: [Error] --> Illegal Access Method!";
    serverMessage("error", $message);
}

?>
serverMessanger.php
<?php
function serverMessage($TYPE, $MESSAGE) {
    $GeneratedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
    $GeneratedXML .= "<SERV_MSG class='" . $TYPE . "'>" . $MESSAGE ."</SERV_MSG>";
    echo $GeneratedXML;
}
?>
HTML Fun & Random Tutorial

HTML Fun & Random Tutorial

I wash watching a show and it had a scene with a challenger board that had a honeycomb pattern in it with a gradient. I randomly thought to myself that I could do that with HTML and even animate it if I wished. So, for giggles, I decided to do just that and make a quick tutorial about it.

naruto_challenger_board
naruto_challenger_board

Thought Process

Let’s first cover my thought process. I immediately thought that I could do this with a PNG that had a honeycomb pattern. It’s cells would be black with the lines being transparent. From there, I could use CSS’s linear-gradient to get the two colors in the image. Doing some googling got me a tillable honeycomb image but I did have to use Gimp to get the transparent parts and color exchange from white to black. Here is the end result of that: Honeycomb Image From there all I had to do was get two divs and set one of the with the image as the background and the other as a linear-gradient. OK, so we are set with the logic. Let’s look at the CSS.

CSS

The CSS is pretty straightforward. We first make sure that the entire page is filled when we have our elements in it. So, we set padding and margins to zero for the html and body tags. We then define some base parameters for our two core div elements. I identafy them with IDs and they are overElm and underElm. We simply set their width and height settings to 100%. In addition, we set their positions fixed so that we can use z-index to place them in the proper top and bottom order.

Now, the overElm has its background set to url(“honeycomb.png”); and repeat is set for both x and y ordinates. Then, underElm has its z-index set to -100 to make certain it is below overElm. That covers the CSS section. We will do one other CSS related thing but it will be referenced in our JavaScript section. Let’s cover our body tabs we need.

html, body {
    margin: 0em 0em 0em 0em;
    padding: 0em 0em 0em 0em;
}

#overElm, #underElm {
     width: 100%;
     height: 100%;
     position: fixed;
}

#overElm {
     background-image: url("honeycomb.png");
     background-repeat: repeat;
}

#underElm {
    z-index: -100;
}

 

Tags

This part is super straightforward and so we an quickly go to the JavaScript section in a moment. Here is the breakdown. We have two div tags and they each have their respective IDs. See? Easypeasy. See below:

<div id="overElm"></div>
<div id="underElm"></div>

 

JavaScript

OK, this is the most meaty part of the logic. We are going to use the setInterval JavaScript function and to create the animation. In addition, we will check to see if we want an animation at all. Before we do this we want to create a number of variables for use.

First, we get the element reference for underElm. Then, we create two color variables to be used in our linear-gradient setting. In addition, we create two color percent variables in order to drive how much gradient there actually is. Here we will use 50% for both so that they equally consume space and that there actually isn’t any gradation.

We also will create a degree variable and interval rate variable. Interval rate will dictate if we want to have a static color split or animated one. From there, we setup an if check and see if our interval rate is less than 0. If it is, it sets a static linar-gradient. Or if greater than, it will animate via the setInterval function. We pass our arguments to it for usage. And we are done! You can chnge the clors, its opacity, speed, and more to get a cool look for an HTML page or even video if you manage it right. Full code and video is below.

var elm = document.getElementById("underElm");
var color1        = "#09c759";
var color2        = "#c82f46";
var color1Percent = "50%";
var color2Percent = "50%";
var degInt        = 45;
var intervalRate  = -1;  // - number means do static than intervaled degree change
                         // 20 is nice and fast  500 is gradual and lower

if (intervalRate < 0) {
    elm.style.background = "linear-gradient(" + degInt + "deg,"
                           + color1 + " " + color1Percent +","
                           + color2 + " " + color2Percent + ")";
} else {
    var interval = setInterval(function () {
        elm.style.background = "linear-gradient(" + degInt + "deg,"
                               + color1 + " " + color1Percent +","
                               + color2 + " " + color2Percent + ")";

        degInt = (degInt <= 405) ? degInt += 5 : degInt = 45;

    }, intervalRate, elm, color1, color1Percent,
                          color2, color2Percent);
}

 

Full HTML & Code

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Honeycomb Gradient</title>

        <style media="screen">
            html, body {
                margin: 0em 0em 0em 0em;
                padding: 0em 0em 0em 0em;
            }

            #overElm, #underElm {
                width: 100%;
                height: 100%;
                position: fixed;
            }

            #overElm {
                background-image: url("honeycomb.png");
                background-repeat: repeat;
            }

            #underElm {
                z-index: -100;
            }
        </style>
    </head>
    <body>
        <div id="overElm"></div>
        <div id="underElm"></div>

         <script type="text/javascript">
             var elm           = document.getElementById("underElm");
             var color1        = "#09c759";
             var color2        = "#c82f46";
             var color1Percent = "50%";
             var color2Percent = "50%";
             var degInt        = 45;
             var intervalRate  = -1; // - number means do static than intervaled degree change
                                     // 20 is nice and fast  500 is gradual and lower

             if (intervalRate < 0) {
                 elm.style.background = "linear-gradient(" + degInt + "deg,"
                                        + color1 + " " + color1Percent +","
                                        + color2 + " " + color2Percent + ")";
             } else {
                 var interval = setInterval(function () {
                     elm.style.background = "linear-gradient(" + degInt + "deg,"
                                            + color1 + " " + color1Percent +","
                                            + color2 + " " + color2Percent + ")";

                     degInt = (degInt <= 405) ? degInt += 5 : degInt = 45;

                 }, intervalRate, elm, color1, color1Percent,
                                       color2, color2Percent);
             }

         </script>
    </body>
</html>

 

Video

 

Java – JSP File Uploader Tutorial

Java – JSP File Uploader Tutorial

JSP Image
jsp image

Java is one of my favorite programming languages due to its straightforward nature and plethora of built-in options. It has a robust tie with web related technologies such as HTML, CSS, and JavaScript and is made easy to leverage through its server Tomcat. In addition to all that, the community is strong and provides additional functionality through Java ARchives (JARs).

Now, if you have a web application and want dynamic pages and to leverage Java, you can use Java Server Pages (JSP) to create dynamic interfaces and data streams/access. This tutorial will be on how to upload a file through an HTML Form and JSP processing it to save to the server. To do this, you’ll need to use Tomcat with or without Apache/Nginx and Java 8 or up. For this example, I’ll be using Tomcat in standalone than coupling it with one of the other options. I’m programing on an Ubuntu based distribution so be aware of how your system interacts with Java and vise versa.


To Top


To Bottom

Setup

Tomcat Download

Let’s start off by getting Tomcat and setting it up. Go to Tomcat 9 Download page and look under Binary Distributions. There, click on either the 32bit or 64 bit “core” zip for Windows if on Windows or simply select the first “core” zip in the list if on Linux.
From there, unzip it to a location you want to work from. Mine is in my home directory under a folder called
“Portable_Apps”. I unzip it and called it “Tomcat-9”.

Tomcat Setup

Once unzipped and located where you want it, you will want to change its setting in order to use it fully. So, head into the directory and you will see many folders. Of them, there are four key folders to really pay attention to for this task. They are “bin”, “conf”, “lib”, and “webapps”. First, head to “conf” and edit the tomcat-users.xml file. In general, you’ll want to add a user that can access the “manager-gui” application that allows you to control what web applications are present. To do this, head to the bottom of the file where the commented out accounts are. Copy or type out an account that isn’t commented out.

Mine looks looks so:

<user username="admin" password="1234" roles="tomcat,manager-gui"/>

Please note that the password needs to be something that is actually strong and in addition to that you should try to name the user as something that can’t be guessed by others. Anyway, go ahead and save the file. From there, take a look at the server.xml file.

Find:

<Connector port="8080" protocol="HTTP/1.1"
                    connectionTimeout="20000"
                    redirectPort="8443"
                    address="0.0.0.0" />

You can change the port or add multiple Connector sections to have multiple ports accessible for multiple applications. Please note that I have added the “address” part and it is by default not present. The addition let’s my network connect to the application after I’ve allowed the port to be accessed through the firewall rules. In Linux, for me, this was as simple as making sure UFW was installed and up and then in a terminal doing “sudo ufw allow <portNumber>/tcp”.

OK, before we start Tomcat, we will want to get some additional libraries so that we can handle a file being sent to the JSP file. Go to these links and find the newest versions.

Links: FileUpload and Commons IO

Once downloaded, simply unzip them and ignore all but the JAR that has the name and version number. Move these JARs to the “lib” folder that I mentioned earlier. If you started Tomcat before this step, stop it and then start it so the libraries will load. If not, we are then ready to start Tomcat. To do this, open a command line or terminal and change directories to the “bin” folder.

From there, do:

// Linux
./catalina.sh start

// Windows
.\catalina.bat start

You might need to make the shell file executable and you can do this by running “chmod +x catalina.sh” from the folder in the terminal. If everything went well, you should see “Tomcat started.” as part of the output. You can now go to your webbrowser and type localhost:8080. If you see “If you’re seeing this, you’ve successfully installed Tomcat. Congratulations!” then we are set. To stop the server, simply replace “start” with “stop”. It’s time we managed our applications a bit.

Tomcat Manage Applications

On the page, to your right, you’ll see a button called “Manager App”. Click it and login using the user information you created earlier. Here, we’ll see all the applications that are present. This coincides with the “webapps” folder I mentioned. In manager, the paths math the folder names in the “webapps” folder. Only “ROOT” doesn’t follow the naming scheme since it is just a forward slash. “ROOT” also is the container for what you saw when you loaded the page. We’ll want to move its contents to another location. In the “webapps” folder add a new folder called “toor”. Then, in the manager page, find the “Deploy” section and type toor into the “Context Path” section. Click “Deploy” and the section will be added. The rest is up to you but I’d Undeploy the “docs” and “examples” section to clear up space. Note, the folders will be deleted if you do this.

OK, move the “ROOT” contents to the “toor” folder and then create two folders in the “ROOT” folder. They are “data” and “WEB-INF”. In the “WEB-INF” folder add a file called “web.xml”.

In it, add:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

  <display-name>File Uploader & Downloader</display-name>
  <description>
     File Uploader & Downloader
  </description>
</web-app>

OK, it’s time we write some code.

Code Breakdown

HTML

There are really only two parts to this section, a form and an iframe. The rest is just fluff that HTML pages need for proper setup. Simply create the structure in an “index.html” file and insert the below into the “body” tag.

This is the important code:

<h2>File Uploader</h2>
    <form action="Uploader.jsp" method="post" enctype="multipart/form-data" target="FormSubmitter">
        <input type="reset" value="Clear">
        <input type="submit" name="submit"  value="Upload" />
        <input type="file" name="file" multiple />
    </form>
<iframe name="FormSubmitter" frameborder="0" style="width:100%;height:35em"></iframe>

Let’s break this down and understand the parts. We have a form and its action is the JSP file, “Uploader.jsp”. The JSP file will process the submitted info to it and save it. The method used is “post” because what is being submitted is a file or files. The encode type is “multipart/form-data” because we will have to submit files and this setting is what is used to do so. From there, to avoid redirecting the page on submission, we send the process to the iframe.

In the form part, we have three input tags. The first simply clears the form data. The second submits the form or in this case the files. The third is the file selector. Reference the Full HTML section if you need to know the structure of the rest of the file. OK, we can now look at our JSP file, the good meaty Java code that glues this whole thing together.

JSP

Go ahead and create a JSP file called “Uploader.jsp”. In the beginning, there was imports. In this beginning, we need a few of them.
Let’s look at them:

<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.io.File" %>

If we look at the imports, we already can get an idea of the structure of the program or take guesses as to how it might be written. We will iterate through a list of the uploaded file(s) and probably use the File object to write the selected file to a location. The other imports handle the actual receiving of the data. Now that we have the needed imports, let’s get some initial stuff set up.

Here is the start of the code:

<%
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String dirPath = getServletContext().getRealPath("/").replace('\\', '/') +
                                                                      "data/";
    String itemName;
    File file;


    out.println(
        "<!DOCTYPE html>"
        + "<html><head>"
        + "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
        + "<title>Results</title>"
        + "</head> <body>"
    );

Let’s break this down and understand the parts. The first is a boolean that we will check against to see if the data being sent is of multipart/form-data. The next part is the proper path to the “data” folder we created a while back. For Windows, I’m pretty sure you don’t need the “replace” part. We then setup a String called “itemName” that’ll be used to get the file name from the iterated data to then join with the “dirPath” so we can save it in the proper location. We also setup a File object we’ll use later. After all that, we print out the initial HTML syntax for return of the listed out “data” folder in HTML. We are well on our way to being able to upload files to our server. Let’s cover the middle meat of our JSP.

Here is the code:

    // Save file if present
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List list = null;

        try { list = upload.parseRequest(request);
        } catch (FileUploadException e) { out.println(e); }

        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (!item.isFormField()) {
                try {
                    itemName = item.getName();
                    file = new File(dirPath + itemName);
                    item.write(file);
                } catch (Exception e) { }
            }
        }
    } else {
        out.println("<h2>Not multi-part transmitted...</h2>");
    }

As was stated, we first check to see if the data being sent is of multipart/form-data. If not we just return a message saying it’s incorrectly submitted. If it’s correct, we do some initial setting up processes by creating a FileItemFactory object. This is an interface for creating FileItem instances which are themselves a representation of the file or formfield data which will be stored in memory or on disk as temporary files. Files are stored in memory if small and on disk if too large when checked against the default size or the one you specify (We aren’t specifying size for this guide.). We then use a high level API for processing file uploads by way of the ServletFileUpload object.

To determine files, we use the “parseRequest” method to get a list of files that are then sent to the previously created List object that is null. We do as previously mentioned and set up an Iterator object and traverse it with a while loop. In the while loop we create our FileItem which represents our listed file. We check to see if the FileItem instance represents a simple form field or an actual file. If it’s a file, we then get its name and then merge that name with the previously determined directory path. (Some of these settings can be setup in the “web.xml” we created but in this case we hard coded it.) This all is set in a new File object. We then use the FileItem object to write its data to the new File object we created and thus “upload” the file. Let’s finish the JSP code by returning a list of the files in the directory.

Here is the code:

    // List directory
    File curentDir = new File(dirPath);
    String[] list = curentDir.list();
    out.println("<ol>");
    for (int i=0; i<list.length; i++) {
            out.print("<li><a href='data/" + list[i] + "'/>" + list[i] + "</a></li>");
    }
    out.println("</ol>");
    out.println("</body></html>");
%>

This last part is a bit of an added bonus. We will list the directory containing our files. Let’s break it down. We first create a new File Object and reference the “data” directory path. We list it out in a newly created String array object which we will use below. But next, we print out the “ordered list” tag. We then loop through the String array and printout HTML that has the “list item” tag and an anchor” tag nested in it that references the path and name of the file. We then close out all tags and party like it’s 1941.

Conclusion

Discussion

At this point, you should add some CSS to get things styled the way you want it to. There isn’t too much I’m aware of that needs covering given the simplicity of the task. Upload file, process file, return data, and that’s it. You might want to look at other tasks like filling a database up with user input or make a directory traverser to view videos, images, or text files. It’s all up to you. If you know Java, then JSP is pretty much that but with web technologies.

For Next Time

For next time, one should look at limiting upload sizes. In this example and for my personal usage, I don’t want a limitation since I’m working with my own files. In production though, it is IMPERATIVE that files be limited in size and there needs to be checks so as the server’s disk space isn’t by accident consumed entirely by a person uploading a file. Other than that, I have no other thoughts on the matter.

Full Code

HTML

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>File Uploader</title>
</head>
<body>


<h2>File Uploader</h2>
    <form action="Uploader.jsp" method="post" enctype="multipart/form-data" target="FormSubmitter">
        <input type="reset" value="Clear">
        <input type="submit" name="submit"  value="Upload" />
        <input type="file" name="file" multiple />
    </form>

<iframe name="FormSubmitter" frameborder="0" style="width:100%;height:35em"></iframe>
</body>
</html>

JSP

<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.List" %>
<%@ page import="java.io.File" %>

<%
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String dirPath = getServletContext().getRealPath("/").replace('\\', '/') +
                                                                      "data/";
    String itemName;
    File file;


    out.println(
        "<!DOCTYPE html>"
        + "<html><head>"
        + "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />"
        + "<title>Results</title>"
        + "</head> <body>"
    );

    // Save file if present
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List list = null;

        try { list = upload.parseRequest(request);
        } catch (FileUploadException e) { out.println(e); }

        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (!item.isFormField()) {
                try {
                    itemName = item.getName();
                    file = new File(dirPath + itemName);
                    item.write(file);
                } catch (Exception e) { }
            }
        }
    } else {
        out.println("<h2>Not multi-part transmitted...</h2>");
    }

    // List directory
    File curentDir = new File(dirPath);
    String[] list = curentDir.list();
    for (int i=0; i<list.length; i++) {
        String name = list[i].toLowerCase();
        if (name.contains(".png") || name.contains(".jpg")||
            name.contains(".gif") || name.contains(".jpeg")) {
                out.print("<div>" +
                          "<img src='data/" + list[i] + "'/></div>");
        } else {
            out.print("<a href='data/" + list[i] + "'/><div>" + list[i] + "</div></a>");
        }
    }

    out.println("</body></html>");
%>

Images

before file select
before file select
file select
file select
file uploaded
file uploaded
file playing
file playing

If you liked this article, please check out the others I have written. One I recommend is my reference cheat sheet for HTML, CSS, and JavaScript. You can use it while styling your JSP file uploader application.

Web Technologies
Web Technologies

HTML, CSS, JavaScript Useful Cheat Sheet!

HTML, CSS, JavaScript Useful Cheat Sheet!


To Top


To Bottom

Web Technologies
Web Technologies

I love web technologies because they provide a quick return on interest (ROI) and for the beginner gives immediate feedback in terms of accomplishment and sense of progress. There are many frameworks that one can use for a web based project but knowing the base elements these frameworks are comprised from is still important. Here is a reference list/cheat sheet of some of the most common HTML tags, CSS, and JavaScript one will likely use. This is great for Web Devs, Web Admins, coders, programmers, and the like.

HTML Tags

Most HTML tags are setup as open and close tags. This means that most tags are a pare/set and denote where they start and end. The end tag has a forward slash (/) to indicate the tag is the end tag.

<tag>Stuff in tag...</tag>
(open tag)content(/end tag)

<!--Some tags end like this-->
<tag/>

<div>

Div tags are considered devision tags and are used to section data on a page. CSS will then be used to style the tag by setting its position, setting the background color, setting the text color, etc. Think of the div as a container and your scaffolding for the page. Div tags are block elements.

<p>

The P tag stands for paragraph tag and this is like a sub container for the div tag. It often holds text but can contain images, links, and other non-block tags. Browsers will automatically add some space (margin) before and after each <p> element. This behavior can be modified with CSS using the margin properties. P tags are block elements.

<span>

The span tag is pretty much like the div tag. The difference between the two is that div is a block element which puts it on a separate line. A span tag, however, is an inline element, meaning that it can be on a line with other elements.


<img>

The img tag stands for images. People like images and I like images.

<img src="https://www.itdominator.com/wp-content/uploads/2017/07/wp-cli.jpg" alt="If image doesn't render, this text will show instead." />

<a>

Anchor tags link to parts on the same page or to new pages entirely. They are essentially links.

<!--To an external page...-->
<a href="http://www.google.com" target="_blank">Google</a>

<!--This will jump to the content that is wrapped with another anchor tag on the same page.-->
<a href="#colors">Colors</a>

<a name="colors">
<p>Colors are cool. The primary colors are red, green, and blue.</p>
</a>

<table>

Table is a block element that denotes there will be sub elements of th, tr, td. There are others but these are the core parts. Th stands for table header and
is inset within a tr (table row). Tr is table row which makes a row for the table. Td is table data which is like a column and is inset in a table row too.

border-collapse: separate (default):

Firstname Lastname
Tom Gar
Lois Griffin

border-collapse: collapse:

Firstname Lastname
Peter Griffin
Lois Matt

form

A form is used to submit data to the server. There are many form objects one can use. Below is a table covering all HTML5 form objects and their code and examples.

Object Preview HTML 5 code
Label

<label>Texte</label>
Button

<input type=”button” name=”name” value=”Bouton”>
Image button


<input type=”image” src=”image/bimage.jpg”>
Text field

<input type=”text” name=”text” value=”empty”>
Password

<input type=”password” name=”monpass” value=”12345″>
Date

<input type=”date” name=”date” value=”<?php echo $today?>”>
Date and time

<input type=”datetime” name=”time” value=”<?php echo $now?>”>
Time <time>2013-06-27</time>
Number

<input type=”number” name=”num” value=”12345″>
Color

<input type=”color” name=”color” value=””>
Search input

<input type=”search” name=”” list=”datalist” value=””>
Data
Dix
<data value=”10″>Ten</data>
Check box

<input type=”checkbox” name=”checkbox1″ value=”checkbox”>
Radio group



<label>Choice 1
<input type=”radio” name=”radio1″ value=”radio1″>
</label>
<label>Choice 2
<input type=”radio” name=”radio1″ value=”radio2″>
</label>
Textarea

<textarea name=”textarea”>content</textarea>
Range


<input type=”range” min=”-100″ max=”100″
value=”0″ step=”2″ name=”power” list=”powers”>
<datalist id=”powers”>
<option value=”0″>
<option value=”-30″>
<option value=”30″>
<option value=”+50″>
</datalist>
Data list To be used with input
<datalist id=”identifier”>
<option value=”1″>
<option value=”2″>
<option value=”3″>
</datalist>
Select

<select name=”select”>
<option>Alpha</option>
<option>Beta</option>
<option>Delta</option>
</select>
Select list

<select name=”select2″ size=”3″>
<option>Alpha</option>
<option>Beta</option>
<option>Delta</option>
</select>
Menu

  • New
  • Open
  • Save
  • <menu type=”context”>
    <li>New</li>
    <li>Open</li>
    <li>Save</li>
    </menu>
    Toolbar

  • <menu type=”toolbar”>
    <li><button type=”button” onclick=”fnew()”>New</button></li>
    <li><button type=”button” onclick=”fopen()”>Open</button></li>
    <li><button type=”button” onclick=”fsave()”>Save</button></li>
    </menu>
    Combo box


    <input type=”text” list=”comboid”>
    <datalist id=”comboid”>
    <option value=”0″>
    <option value=”-30″>
    <option value=”30″>
    <option value=”+50″>
    </datalist>
    File upload

    <input type=”file” name=”file”>
    Image & caption

    Caption

    <figure>
    <img src=”image/image.gif”>
    <figcaption>Caption</figcaption>
    </figure>
    Fieldset
    Title

    …Content…

    <fieldset>
    <legend>Title </legend>

    <p>Content</p>
    </fieldset>

    Output

    <output onforminput=”value = 2 + 2″></output>
    Meter
    12 units
    <meter min=0 max=24 value=12>12 units</meter>
    Progress 0%
    <progress id=”prog” max=100>
    Summary

    Overview
    term
    definition

    <details>
    <summary>
    Presentation
    </summary>
    <dl>
    <dt>term</dt>
    <dd>definition</dd>

    </dl>
    </details>

    Submit button

    <input type=”submit” name=”submit” value=”Submit”>
    Clear/Reset button

    <input type=”reset” name=”clear” value=”Clear”>

    HTML Entities

    HTML entities are used in place of reserved characters in HTML. Characters that are not present on your keyboard can also be replaced by entities as well. The most common are listed in a table below.

    Result Description Entity Name Entity Number
    non-breaking space &nbsp; &#160;
    < less than &lt; &#60;
    > greater than &gt; &#62;
    & ampersand &amp; &#38;
    double quotation mark &quot; &#34;
    single quotation mark (apostrophe) &apos; &#39;
    ¢ cent &cent; &#162;
    £ pound &pound; &#163;
    ¥ yen &yen; &#165;
    euro &euro; &#8364;
    © copyright &copy; &#169;
    ® registered trademark &reg; &#174;

    HTML Notes

    Recommended Default HTML Markup Before Content Is Added

    <!DOCTYPE html> <!--Tells a browser its an html page-->
    <html lang="en">
    <head>
      <meta charset="utf-8">  <!--Encoding model-->
      <title>Title seen on its tab</title>
      <link rel="stylesheet" href="/css/master.css"> <!-- Attach CSS through a path -->
    
    
    
    
    </head>
    <body>
    
    <!-- content goes here... -->
    
    
    <script src="resources/scripts/script.js" charset="utf-8"></script>  <!-- Attach Javascript File through path -->
    </body>
    </html>
    

    Block Elements

    In general, HTML elements can be divided into two categories : block level and inline elements. HTML block level elements can appear in the body of an HTML page. It can contain another block level as well as inline elements. By default, block-level elements begin on new lines. Block level elements create larger structures (than inline elements).

    • p
    • h1, h2, h3, h4, h5, h6
    • ol, ul
    • pre
    • address
    • blockquote
    • dl
    • div
    • fieldset
    • form
    • hr
    • noscript
    • table

    Inline Elements

    HTML inline elements can appear in the body of an HTML page. They can contain data and other inline elements. By default, inline elements do not begin on new lines. Inline elements create shorter structures (than block elements).

    • b, big, i, small, tt
    • abbr, acronym, cite, code, dfn, em, kbd, strong, samp, var
    • a, bdo, br, img, map, object, q, script, span, sub, sup
    • button, input, label, select, textarea

    Margins

    Margins are the spacing around an element.

    This span tag has 2em margin set…

    Padding

    Padding is the spacing internal to an element and its “walls”.

    This span tag has 2em padding set…

    CSS

    Examples/Logic

    Selector Example Example description
    .class .intro Selects all elements with class=”intro”
    #id #firstname Selects the element with id=”firstname”
    * * Selects all elements
    element p Selects all <p> elements
    element,element div, p Selects all <div> elements and all <p> elements
    element element div p Selects all <p> elements inside <div> elements
    element>element div > p Selects all <p> elements where the parent is a <div> element
    element+element div + p Selects all <p> elements that are placed immediately after <div> elements
    element1~element2 p ~ ul Selects every <ul> element that are preceded by a <p> element
    [attribute] [target] Selects all elements with a target attribute
    [attribute=value] [target=_blank] Selects all elements with target=”_blank”
    [attribute~=value] [title~=flower] Selects all elements with a title attribute containing the word “flower”
    [attribute|=value] [lang|=en] Selects all elements with a lang attribute value starting with “en”
    [attribute^=value] a[href^=”https”] Selects every <a> element whose href attribute value begins with “https”
    [attribute$=value] a[href$=”.pdf”] Selects every <a> element whose href attribute value ends with “.pdf”
    [attribute*=value] a[href*=”w3schools”] Selects every <a> element whose href attribute value contains the substring “w3schools”
    :active a:active Selects the active link
    ::after p::after Insert something after the content of each <p> element
    ::before p::before Insert something before the content of each <p> element
    :checked input:checked Selects every checked <input> element
    :disabled input:disabled Selects every disabled <input> element
    :empty p:empty Selects every <p> element that has no children (including text nodes)
    :enabled input:enabled Selects every enabled <input> element
    :first-child p:first-child Selects every <p> element that is the first child of its parent
    ::first-letter p::first-letter Selects the first letter of every <p> element
    ::first-line p::first-line Selects the first line of every <p> element
    ype.asp”>:first-of-type p:first-of-type Selects every <p> element that is the first <p> element of its parent
    :focus input:focus Selects the input element which has focus
    :hover a:hover Selects links on mouse over
    sp”>:in-range input:in-range Selects input elements with a value within a specified range
    :invalid input:invalid Selects all input elements with an invalid value
    :lang(language) p:lang(it) Selects every <p> element with a lang attribute equal to “it” (Italian)
    sp”>:last-child p:last-child Selects every <p> element that is the last child of its parent
    ype.asp”>:last-of-type p:last-of-type Selects every <p> element that is the last <p> element of its parent
    :link a:link Selects all unvisited links
    :not(selector) :not(p) Selects every element that is not a <p> element
    sp”>:nth-child(n) p:nth-child(2) Selects every <p> element that is the second child of its parent
    hild.asp”>:nth-last-child(n) p:nth-last-child(2) Selects every <p> element that is the second child of its parent, counting from the last child
    f-type.asp”>:nth-last-of-type(n) p:nth-last-of-type(2) Selects every <p> element that is the second <p> element of its parent, counting from the last child
    ype.asp”>:nth-of-type(n) p:nth-of-type(2) Selects every <p> element that is the second <p> element of its parent
    ype.asp”>:only-of-type p:only-of-type Selects every <p> element that is the only <p> element of its parent
    sp”>:only-child p:only-child Selects every <p> element that is the only child of its parent
    :optional input:optional Selects input elements with no “required” attribute
    ange.asp”>:out-of-range input:out-of-range Selects input elements with a value outside a specified range
    sp”>:read-only input:read-only Selects input elements with the “readonly” attribute specified
    sp”>:read-write input:read-write Selects input elements with the “readonly” attribute NOT specified
    :required input:required Selects input elements with the “required” attribute specified
    :root :root Selects the document’s root element
    ::selection ::selection Selects the portion of an element that is selected by a user
    :target #news:target Selects the current active #news element (clicked on a URL containing that anchor name)
    :valid input:valid Selects all input elements with a valid value
    :visited a:visited Selects all visited links

    IDs

    ID selectors are supposed to be unique within the HTML document. When queried with JavaScript it should return a single element but it can return an array/list if the web developer set the document with multiple IDs of the same type. Standards dictate this is poor form if done.

    <!-- The IDs are arbitrary. -->
    
    <div id="left-container"> <!-- Content --> </>
    <div id="middle-container"> <!-- Content --> </>
    <div id="right-container"> <!-- Content --> </>
    

    Classes

    Class selectors don’t have to be unique within the HTML document. When queried with JavaScript it usually returns an array/list.

    <!-- The Class is arbitrary. -->
    
    <div class="book"> <!-- Content --> </>
    <div class="book"> <!-- Content --> </>
    <div class="book"> <!-- Content --> </>
    

    CSS Button Generator Button Generator

    Quickly make buttons…

    Button













    JavaScript

    Get Elements By ID/Class/TagName/CSS Selector

    Getting elements by id, class, and tag among other options is a sizeable chunk of the JavaScripting one will do. This allows us to interact with the DOM

    // Get HTML element(s) with specified id.
      var x = document.getElementById('id');
    
    // Get HTML elements with specified class.
      var x = document.getElementsByClassName('className');
    
    // Get HTML elements with specified tag.
      var x = document.getElementsByTagName('tagName');
    
    // Get HTML elements tht matches a specified CSS selector
    // This example returns a list of all  elements with class="icon".
      var x = document.querySelectorAll("img.icon"); 
    

    Function

    The basic block of coding we all know and have come to love. Yes…the function.

    function sum(a, b) {
        return a + b;      // The function returns the sum of a and b
    }
    var sumVal = sum(2,4);
    alert(sumVal);  // Will pop-up saying 6
    

    If Statement

    Check the conditions.

    if (condition) {
    }
    

    Loops

    Loops baby, they’re needed and these will meet your needs.

    // Standard loop
    for (var i=0; i<array.length; i++) {
       array[i].innerHTML;
    }
    
    // For In Loop
    for (var tag in elements) {
        // Do stuff while there are tags to work on
    }
    
    // While Loop
    while (condition) {
        // Do stuff while condition is met
    }
    
    // Do While
     do {
        // One at least one and keep doing stuff while condition is met
    }
    while (condition);
    

    Switch/Case Statement

    Good for menu stuff, switch/case statements are ready for the job.

    var day;
    switch (new Date().getDay()) {
        case 0:
            day = "Sunday";
            break;
        case 1:
            day = "Monday";
            break;
        case 2:
            day = "Tuesday";
            break;
        case 3:
            day = "Wednesday";
            break;
        case 4:
            day = "Thursday";
            break;
        case 5:
            day = "Friday";
            break;
        case  6:
            day = "Saturday";
    }
    alert(day);
    

    Alert & Console Log

    Error logging is helpful. The two way to do this are through alerts and console logging. Most of the time, alert isn’t used but it can be helpful to warn the user, etc.

    // This will generate a pop-up window with the "Hello, World!" text.
    alert("Hello, World!");
    
    // This will log to the console the "Hello, World!" text.
    To access the console in Firefox, do Ctrl+Shift+J
    console.log("Hello, World!");
    

    Adding Event Listeners

    Event listeners are the next most important after getting an element. They allow us to let the user click on stuff or interact through other ways in order to create dynamic interactions.

    // This attaches a click event to the entire DOM.
    // We can then check which IDs, Classes, etc were clicked to then do other things.
    
    document.addEventListener("click", (e) => {
        if(e.target.id == "alert2")
            alert("You clicked an element with the ID of alert2");
    
    });
    
    
    // This attaches to a specific element with the ID of cars and
    // when clicked alerts us to the innerHTML text.
    
    <p id="cars">Hello, World!</p>
    
    document.getElementById('cars').addEventListener("click", (e) => {
            alert("The content is:  " + e.target.innerHTML);
    });
    
    // This attaches it in a different manner.
    document.getElementById('cars').onclick =  function(){
        // do stuff
    }
    
    // You can add it though a tag as well.
    <div onclick="myFunction()"> I am clickable! </div>
    

    Here is a list of some common HTML event attributes:

    Event Description
    onchange An HTML element has been changed
    onclick The user clicks an HTML element
    onmouseover The user moves the mouse over an HTML element
    onmouseout The user moves the mouse away from an HTML element
    onkeydown The user pushes a keyboard key
    onkeyup The user releases a keyboard key
    onload The browser has finished loading the page

    Arrays

    Arrays in JavaScript are a special object and really act like lists or vectors since we can push new values to it.

    // An empty array
    var cars = [];
    
    // Has nodes/objects
    var cars = ["Toyota", "Sab", "Mazda"];
    
    // Add to array
    cars.push("Nesan');
    
    // Remove from end of array
    cars.pop();
    

    Parent Element

    Sometimes, we need to access the element that contains the element we accessed. This could be because we want to remove the element or we want to add something next to it than in it.

    <div>
        <p id="cars" >
            Cars are cool.
        </p>
    But boats are even more cool.
    </div>
    
    var x = document.getElementById('cars').parentElement;
    alert(x.innerHTML);  // This will present an alert box with "But boats are even more cool."
    
    
    // This will remove the element we accessed from the div
    var childElm = document.getElementById('cars');
    var parentElm = childElm.parentElement;
    
    parentElm.removeChild(childElm);
    

    Cookies

    Sometimes, we need to store user information for later usage. This is where cookies come in.

    function saveAsCookie() {
        var uName = document.getElementsByName("userName")[0].value;
        var eml = document.getElementsByName("email")[0].value;
    
    
        // should set expires date: Ex -> expires=(UTC date).
        // Use secure; in argument to make sure it only transports across HTTPS or secure connections
        document.cookie = "username=" + uName  +"; path=" + document.URL;
        document.cookie = "email=" + eml + "; path=" + document.URL;
    }
    
    function displayCookies() {
        var cookiesField = document.getElementById("cookieField");
        var cookies = document.cookie.split(";");  // Set as an array to traverse....
    
        for (var i=0; i<cookies.length; i++) {
            cookiesField.innerHTML += cookies[i] + "<br/>";
        }
    }
    
    function clerCookies() {
        var expireDate = "Thu, 01 Jan 1970 00:00:00 UTC";
        document.cookie = "username=; expires=" + expireDate;
        document.cookie = "email=; expires= " + expireDate;
    }
    
    <form>
    <input type="text" title="User Name" name="userName" placeholder="User Name" value=""/>
    <input type="text" title="Email" name="email" placeholder="Email" value=""/>
    <input type="button" name="submit"  onclick="saveAsCookie()" value="loginSubmit">
    </form>
    
    <button type="button" name="button" onclick="displayCookies()">Get Cookie</button>
    <button type="button" name="button" onclick="clerCookies()">Clear Cookie</button>
    
    <div id="cookieField"></div>
    

    AJAX

    AJAX is a developer’s dream, because you can:

    • Update a web page without reloading the page
    • Request data from a server – after the page has loaded
    • Receive data from a server – after the page has loaded
    • Send data to a server – in the background
    function loadDoc() {
      var xhttp = new XMLHttpRequest();        // Create the xhttp object
      xhttp.onreadystatechange = function() {  // This is actually run after open and send are done
        if (this.readyState == 4 && this.status == 200) {  // Confirm we have a  successful connection
         // Receive the response info. For PHP it is echo that sends it. Then set into demo div
         document.getElementById("demo").innerHTML = this.responseText;  
        }
      };
      xhttp.open("GET", "ajax_info.txt", true);  // post or get, path to XML page or php script, set async 
      xhttp.send();                              // Start the process
    }
    
    
    <button type="button" name="button" onclick="loadDoc()">Load XML</button>
    <div id="demo">
    

    String Manipulation

    String Manipulation can be important when handling cookies or data. Sometimes we need to split it into an array, make it lower case or vise versa, find a sub string, or more.
    These should get you started:

    // Find sub string
    var str = "Hello world, welcome to the universe.";
    var n = str.includes("world");
    
    // Find sub string at offset
    var str = "Hello world, welcome to the universe.";
    var n = str.includes("world", 12);
    
    // Replace string 
    var str = "Windows!";
    var res = str.replace("Windows", "Linux");  // old value, new value
    
    // Replace all case sensitive
    var str = "Mr Blue has a blue house and a blue car";
    var res = str.replace(/blue/g, "red");
    
    // Replace all case-insensitive
    var str = "Mr Blue has a blue house and a blue car";
    var res = str.replace(/blue/gi, "red");
    
    // String split
    var str = "How are you doing today?";
    var arry = str.split(" ");  // Split by spaces
    
    // To Upper
    var x = "Linux";
    x.toUpperCase();
    
    // To Lower
    var x = "LINUX";
    x.toLowerCase();
    

    Conclusion

    I think this list is pretty good and fits most user’s needs. This should definitely help those who are looking for a certain tag or CSS logic or are just wanting to see a broad selection of what web technologies are based off of. Coders, website developers, Admins, etc should have most of what they need right on the page with good samples to start. Leave a commemt if you’d like me to add something else! Anyway, if you liked this reference sheet/cheat sheet, start using what you have learned by setting up a quick test server! Read my article by clicking the below image!


    Servers


    Quick Test Server

    Quick Test Server

    Server

    There are times when I need a server in order to test some feature or bit of code. I don’t like spooling up a Linux, Apache, MySQL, and PHP (LAMP) or Linux, NGINX, MySQL, and PHP (LEMP) stack because it’s tedious. Notice what I did there? I made the whole sentence tedious to get you to think it really is tedious. It really isn’t but frankly, I needed a reason to write this. Anyway, so, what is one to do? Well, there are two option that come to mind and those are Python, PHP, or Netcat. One might ask: “Whaaat? Rly?”. Yup. Really. All one needs to do is open up a terminal/cli and get ta hackin.

    Python call up the Python module SimpleHTTPServer using the switch -m and then give it a port. Make the port greater than 1024 since those are reserved and require root to use. BAM! Open your browser of poison and go to localhost:portNumber or 127.0.0.1:portNumber.

    Python Server

    python -m SimpleHTTPServer 1337
    

    I did not need to insert any index.html files to the directory. Python automatically gives a list of the directory contents when no index file is found. As a side note, Python doesn’t seem to read Php properly. I have yet to get it to work.

    For PHP all one does is use the switch -S and then give it an address (127.0.0.1) and port. Again, make the port greater than 1024 since those are reserved and require root to use. BAM! Once more, open your browser of poison and go to localhost:portNumber or 127.0.0.1:portNumber.

    PHP Server

    php -S 127.0.0.1:1337
    

    It is worth noting that with PHP I had to insert an index.php file into the directory I ran the command from. It doesn’t generate any list but does throw an error when no index is found. Additionally, this method seems to only work with PHP files. To test if the PHP server works, simply insert in the index.PHP :

    <?php
        phpinfo();
    ?>
    

     

    For the last one we will look at Netcat. Netcat is the swiss army knife of the networking tools and has an interesting way of creating a kind of server. To start off, simply create a file called serve.sh. The name is arbitrary but that’s what we will use for this example. Then, in the file add

    Netcat Server

    #!/bin/bash
    
        echo "`cat index.html`"
    

    When this is done, simply create an index.html as you would any other. In my case, I did:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Google Link</title>
    </head>
    <body>
        <h1><a href="http://www.google.com">Google</a></h1>
    </body>
    </html>
    

    After all this prep, which isn’t much we simply run in the terminal where serve.sh and index.html is:

    while true; \
    do { \
        echo -e 'HTTP/1.1 200 OK\r\n'; sh serve.sh; \
    } | nc -l 1337; \
    done
    

    One might need to press enter again to actually run it because of the \’s stating “look to next line for rest of command”. One can also just remove the \’s and put the whole command like so:

    while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; sh serve.sh; } | nc -l 1337; done
    

    One can use PHP with this by the way. All one does is rename index.html to index.php. Then one adds some code like in the PHP example above. After that, in the serve.sh, edit the cat index.php to be PHP index.php. This has PHP interpret the file which then has its output gets echoed back to the requester.
    All of this needs some explaining. So what is happening is that the while loop is checking to see if there is anything left to run. Note that the first part before the semicolon tells the browser that there is a server where one requested one. IE, it confirms the request. Then, the serve.sh is ran. In serve.sh it echos out what cat prints from index.html or what PHP prints from index.php. This is essentially sent as the file back to the requester. Thus, we can see the h1 sized Google anchor link in this example.

    Voila! A nice juicy server is ready for use in any project that needs one. If one is adventurous, one can use these simple servers to serve files on the local network. To do this, all you have to do is allow the port to accept connections using UFW and then change the address “127.0.0.1” to “0.0.0.0”. This isn’t recommended for long term use but can be useful when needing to transfer something or using an app that’s for the local network. Even then, one might be better off just using ssh or email! Still, in those rare times, all one does is allow the port to be open by using ufw.

    ufw allow portNumber/tcp
    

    To remove the rule:

    ufw status numbered
    ufw delete "the number associated with ones portNumber"
    
    ITDominator’s Github Projects

    ITDominator’s Github Projects

    Github:
    Github Cat Image
        This is my Github account. I have accumulated a good number of programs and repositories over the years. Though, much of it has now been setup in an archive repository since I no longer support the code. The ones not in the archive are my active projects and represent my current skill level barring proper try/catch handling which I am too lazy to implement at this time. Otherwise, they are my projects to improve my coding skills.

        PS – Yes, not all (probably most) properly meet OOP standards. This is a personal choice since I don’t want to create a number of files just to have code split up properly. One controller file suits my needs just fine at this time. Though, one or two will eventually get refactored and setup to meet OOP standards.

    Redirect