CMPE 280 Web UI Design and Development September 10 Class Meeting

Slides:



Advertisements
Similar presentations
Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
Advertisements

JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
Copyright © The OWASP Foundation Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
PHP Hypertext PreProcessor. Documentation Available SAMS books O’Reilly Books.
JavaScript, Fourth Edition
Integrating JavaScript and HTML5 HTML5 & CSS 7 th Edition.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Week seven CIT 354 Internet II. 2 Objectives Database_Driven User Authentication Using Cookies Session Basics Summary Homework and Project 2.
CS 174: Web Programming September 30 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 174: Web Programming September 28 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CS 174: Web Programming October 12 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
ASP-2-1 SERVER AND CLIENT SIDE SCRITPING Colorado Technical University IT420 Tim Peterson.
Node.Js 1. 2 Contents About Node.Js Web requirement latest trends Introduction Simple web server creation in Node.Js Dynamic Web pages Dynamic web page.
Introduction to JavaScript MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 2/2/2016.
CS 174: Web Programming October 28 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
World Wide Web has been created to share the text document across the world. In static web pages the requesting user has no ability to interact with the.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
Introduction to JavaScript MIS 3502, Fall 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 9/29/2016.
CMPE 280 Web UI Design and Development September 7 Class Meeting
Introduction to.
DHTML.
In this session, you will learn to:
Applied Component I Unit II Introduction of java-script
Introduction to Dynamic Web Programming
Tutorial 10 Programming with JavaScript
Web Development & Design Foundations with HTML5
Parts of Chapter 14 Key Concepts
JavaScript is a programming language designed for Web pages.
In this session, you will learn about:
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Section 17.1 Section 17.2 Add an audio file using HTML
CMPE 280 Web UI Design and Development October 26 Class Meeting
Web Development & Design Foundations with HTML5 7th Edition
CMPE 280 Web UI Design and Development October 19 Class Meeting
CMPE 280 Web UI Design and Development October 24 Class Meeting
CMPE 280 Web UI Design and Development October 26 Class Meeting
PHP / MySQL Introduction
14 A Brief Look at JavaScript and jQuery.
CMPE 280 Web UI Design and Development January 30 Class Meeting
Express with Node L. Grewe. Feature 1 Project structure.
Introduction to JavaScript
Unit 27 - Web Server Scripting
JavaScript Introduction
CS 174: Server-Side Web Programming January 29 Class Meeting
A second look at JavaScript
WEB PROGRAMMING JavaScript.
CMPE 280 Web UI Design and Development January 30 Class Meeting
Integrating JavaScript and HTML
Abel Sanchez, John R. Williams
Introduction to JavaScript
CMPE 280 Web UI Design and Development October 18 Class Meeting
CMPE 280 Web UI Design and Development January 29 Class Meeting
Web Programming Language
Tutorial 10 Programming with JavaScript
Javascript and JQuery SRM DSC.
CMPE 280 Web UI Design and Development March 19 Class Meeting
CSc 337 Lecture 27: Cookies.
Introduction to JavaScript
HTML5 and Local Storage.
Tutorial 10: Programming with javascript
Lecture 12: The Fetch Api and AJAx
JavaScript Basics What is JavaScript?
JavaScript is a scripting language designed for Web pages by Netscape.
Introduction to Programming and JavaScript
Introduction to JavaScript
CMPE 280 Web UI Design and Development August 27 Class Meeting
CSc 337 Lecture 25: Cookies.
CMPE 280 Web UI Design and Development March 19 Class Meeting
Presentation transcript:

CMPE 280 Web UI Design and Development September 10 Class Meeting Department of Computer Engineering San Jose State University Fall 2019 Instructor: Ron Mak www.cs.sjsu.edu/~mak

Sessions Each time a user requests a page from your web application, there is a separate and isolated request and response. To provide a good user experience (UX), your web app must maintain a conversation. Remember information from one request to another. Otherwise, your application has severe amnesia. For example, your application needs to remember that a user has already logged in.

Sessions, cont’d The application can keep track of a logged-in user in a session. A session records that a user is logged in so that each request doesn’t require a log in. Each logged-in user is in a separate session. When a request comes in, how can your web application determine which session (and therefore which user) the request belongs to?

Cookies The first time a user makes a request to your web app, it creates a session for the user and generates a small piece of identifying data. The data is sent back as part of the response. The browser stores the identifying data in a local file called a cookie on the client machine. Each subsequent request by the user includes the cookie data. The web app uses the cookie data to identify which session and thereby which user.

Express Session Management The Express express-session and cookie-parser packages do much of the work for us. Maintain session data for each user. Manage cookie data. Use cookie data to identify the right session.

Simple Cookie Example In this example, the express-session package keeps each user’s page visit count in a session. Sessions are stored in memory. Cookie data included with each visit (request) determines which session. When the server restarts, the counts are lost. More persistent solutions? Write the counts into a database. Write the counts into the cookies.

Simple Cookie Example, cont’d app.js var express = require('express'); var cookieParser = require('cookie-parser'); var session = require('express-session'); var app = express(); app.use(cookieParser()); app.use(session( {secret: "String for encrypting cookies."} ));

Simple Cookie Example, cont’d app.js app.get('/', function(req, res) {     if(req.session.page_views)     {         req.session.page_views++;         res.send("You visited this page " +                   req.session.page_views + " times");         console.log('Cookies: ', req.cookies);     }      else          req.session.page_views = 1;         res.send("Welcome to this page for the first time!");     } }); app.listen(3000); The express-session package uses the cookie data to determine which session to use. We add page_views to a new session. Demo

User Authentication Many applications require new users to register. You can store registered users in a database. Registered user then must log in each time to use the application. The application uses a session to record that a user is logged in. Only logged in users are allowed to do certain things, such as visit “protected pages” of the application.

User Authentication Example We introduce the use of page templates. The .jade template files are views. Express uses the Jade template engine to dynamically generate HTML pages from the page templates.

User Authentication Example, cont’d New packages: express-session cookie-parser jade   "dependencies": {     "body-parser": "~1.18.2",     "cookie-parser": "^1.4.3",     "debug": "~2.6.9",     "express": "~4.15.5",     "express-session": "^1.15.6",     "jade": "~1.11.0",     "line-reader": "^0.4.0",     "serve-favicon": "~2.4.5"   }

User Authentication Example, cont’d var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var session = require('express-session'); var index = require('./app_server/routes/index'); var app = express(); //View engine setup app.set('views', path.join(__dirname,'app_server','views')); app.set('view engine','jade'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended:true}));  app.use(express.static(path.join(__dirname,'public'))); app.use(session( {secret:"String for encrypting cookies."} )); app.use('/', index); module.exports = app; app.listen(3000); app.js

User Authentication Example, cont’d app_server/routes/index.js var express = require('express'); var router = express.Router(); var ctrlMain = require("../controllers/main"); /*  * GET home page.  */ router.get('/', ctrlMain.index);  * GET registration page. router.get('/register', ctrlMain.get_register);  * POST registration page. router.post('/register', ctrlMain.post_register);

User Authentication Example, cont’d app_server/routes/index.js /*  * GET login page.  */ router.get('/login', ctrlMain.get_login);  * POST login page. router.post('/login', ctrlMain.post_login);  * GET logout page. router.get('/logout', ctrlMain.get_logout);  * GET protected page. router.get('/protected', ctrlMain.loggedIn, ctrlMain.get_protected); module.exports = router;

User Authentication Example, cont’d app_server/controllers/main.js var registeredUsers = []; module.exports.loggedIn = function(req, res, next) {    console.log("Checking if logged in:");    if (req.session.user)    {        // Proceed if the user is logged in.        console.log("Logged in: "); console.log(req.session.user);        next();     }     else         console.log("Not logged in");        res.send("You must first log in.");    } };

User Authentication Example, cont’d app_server/controllers/main.js /*  * GET home page.  */ module.exports.index = function(req, res, next)  {    res.render('index', {title:'Authentication Demo'});    console.log('Cookies: ', req.cookies); };  * GET registration page. module.exports.get_register = function(req, res)    res.render('register',               {message:"Please register!"});

User Authentication Example, cont’d app_server/views/layout.jade doctype html html  head    title = title    link(rel='stylesheet', href='/stylesheets/style.css')  body    block content app_server/views/index.jade extends layout block content   h1= title   p Welcome to the #{title}

User Authentication Example, cont’d app_server/views/register.jade html   head      title Registration   body      if(message)         h4 #{message}         form(action = "/register" method = "POST")             input(name = "username" type = "text" required                    placeholder = "username")             input(name = "password" type = "password" required                    placeholder = "password")             button(type = "Submit") Register me!

User Authentication Example, cont’d app_server/controllers/main.js /*  * POST registration page.  */ module.exports.post_register = function(req, res) {    if (!req.body.username || !req.body.password)    {        res.status("400");        res.send("Invalid details!");    }     else         // Create an array of users with matching usernames.        var matches = registeredUsers.filter(function(user)                      {                         return user.username === req.body.username;                      });

User Authentication Example, cont’d        // If there is a match, the user has already registered.        if (matches.length > 0)        {            res.render('register', {message:"User already registered!"});        }                 // Register a new user.        else            var newUser = { username: req.body.username,                            password: req.body.password };            registeredUsers.push(newUser);            console.log("New user:"); console.log(newUser);            console.log("Registered users:"); console.log(registeredUsers);            res.redirect('/login');    } }; app_server/controllers/main.js

User Authentication Example, cont’d /*  * GET login page.  */ module.exports.get_login = function(req, res) {    res.render('login', { message:"Please log in!"}); };  * POST login page. module.exports.post_login = function(req, res)    console.log("Registered users:"); console.log(registeredUsers);    console.log("Logging in: " + req.body.username + "/" + req.body.password); app_server/controllers/main.js

User Authentication Example, cont’d    // Create an array of users with matching credentials.    var matches = registeredUsers.filter(function(user)                  {                      return    (user.username === req.body.username)                              && (user.password === req.body.password);                  });         console.log("Matching credentials: "); console.log(matches);    if (matches.length === 0)    {        res.render('login', {message:"Invalid credentials!"});    }    else        // The user is logged in for this session.        req.session.user = matches[0];        console.log("Sucessfully logged in:");         console.log(req.session.user.username);                 res.render('loggedin',                    {name: req.session.user.username}); }; app_server/controllers/main.js

User Authentication Example, cont’d html   head      title Login   body      if(message)         h4 #{message}         form(action = "/login" method = "POST")             input(name = "username" type = "text" required                    placeholder = "username")             input(name = "password" type = "password" required                    placeholder = "password")             button(type = "Submit") Login app_server/views/login.jade html   head      title Logged in page   body      p Hi, #{name}, you're now logged in.      p You may visit the protected page. app_server/views/loggedin.jade

User Authentication Example, cont’d /*  * GET logout page.  */ module.exports.get_logout = function(req, res) {    console.log("Logging out:");         if (req.session.user)    {        var name = req.session.user.username;        console.log(name);                 req.session.destroy(function()        {            console.log(name + " logged out.");        });        res.send(name + " is now logged out.");    }    else        console.log("Nobody is currently logged in!");        res.send("Nobody is currently logged in!"); }; app_server/controllers/main.js

User Authentication Example, cont’d app_server/controllers/main.js /*  * GET protected page.  */ module.exports.get_protected = function(req, res) {    res.render('protected', { name: req.session.user.username }); };

User Authentication Example, cont’d app_server/views/protected.jade html   head      title Protected page   body      p Hi, #{name}!      p Welcome to the protected page.

The Document Object Model (DOM) Your web browser represents the contents of an HTML page internally using the Document Object Model (DOM).

The DOM, cont’d Several key objects of the DOM are children of the special window object. Some important children of window: Object Represents Notes document Current HTML page Most commonly scripted object location Current page URL Change location.href to move to another page history List of recently visited pages Access to view previously visited pages status Browser status bar Use to set a message in the status bar

Chrome and the DOM Use the Chrome browser’s Developer Tools to manually manipulate the DOM. Load any web page into the Chrome browser. View  Developer  Developer Tools Console tab Enter Chrome displays the valid choices in a drop-down menu after you type each period. document.body.style.backgroundColor="yellow" Note: CSS uses background-color but DOM uses backgroundColor. Demo

JavaScript, Again Originally used only on the client side. Interpreted by the browser. Now available on the server via node.js. Open-source V8 JavaScript engine developed for Google’s Chrome browser. Syntax similar to Java. interpreted object-oriented weakly typed dynamic

JavaScript, Again, cont’d Purposes Validate user’s form input data Provide interactivity Modify existing HTML page On the client side, you can write JavaScript code that directly manipulates the DOM.

Example JavaScript Code js/backgroundcolor1.html <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Background Color #1</title> </head> <body> <form action=""> <fieldset> <legend>Color buttons</legend> <p> <input type="button" value="Red" onclick="document.body.style.backgroundColor='red'" /> <input type="button" value="Green" onclick="document.body.style.backgroundColor='green'" /> <input type="button" value="Blue" onclick="document.body.style.backgroundColor='blue'" /> </p> </fieldset> </form> </body> </html> Button events Event handlers Demo

Example JavaScript Function <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>Background Color #2</title> <script type="text/javascript"> function changeBGColor(color) { document.body.style.backgroundColor = color; } </script> </head> <body> <form action=""> <fieldset> <legend>Color buttons</legend> <p> <input type="button" value="Red" onclick="changeBGColor('red')" /> <input type="button" value="Green" onclick="changeBGColor('green')" /> <input type="button" value="Blue" onclick="changeBGColor('blue')" /> </p> </fieldset> </form> </body> </html> js/backgroundcolor2.html Demo

JavaScript Variables JavaScript variables are dynamically typed. The type of a variable’s value is determined at run time. What is the value of sum in each example? var x = "1"; var y = "2"; var sum = x + y; var x = 1; var y = 2; var sum = x + y;

Obtaining Text Input Field Values <body> <form action=""> <fieldset> <legend>User input</legend> <p> <label>First number:</label> <input id="first" type="text" /> </p> <label>Second number:</label> <input id="second" type="text" /> <input type="button" value="Add version 1" onclick="add1()" /> <input type="button" value="Add version 2" onclick="add2()" /> </fieldset> </form> </body> js/adds1.html

Obtaining Text Input Field Values, cont’d <head> <meta charset="UTF-8"> <title>Add Versions #1</title> <script type="text/javascript"> function add1() { var x = document.getElementById("first").value; var y = document.getElementById("second").value; var sum = x + y; alert(x + " + " + y + " = " + sum); } function add2() var x = parseInt(document.getElementById("first").value); var y = parseInt(document.getElementById("second").value); </script> </head> js/adds1.html Demo

Modifying the DOM <body> <form action=""> <fieldset> ... </fieldset> </form> <div id="outputDiv"> <p>Output will appear here.</p> </div> </body> js/adds2.html

Modifying the DOM, cont’d <head> ... <script type="text/javascript"> function outputSum(x, y) { var sum = x + y; document.getElementById("outputDiv").innerHTML = "<p><strong>" + x + " + " + y + " = " + sum + "</strong></p>"; } function add1() var x = document.getElementById("first").value; var y = document.getElementById("second").value; outputSum(x, y); </script> </head> js/adds2.html Demo

Viewing Generated Source Code Use JavaScript to modify the DOM via an object’s innerHTML property. The browser’s View Source command shows the original unmodified HTML. Use the browser’s Inspect Element command instead to see the modified HTML. Demo

Assignment #2. Prototype Use HTML, CSS, Node.js, and Express to create a prototype of your project. Use a prototype to elicit more accurate requirements from your customer. Do not use any client-side toolkits such as React. Not expected to be a polished application. You do not need to use any actual data on the server side. You can simply use hardcoded data.

Assignment #2, cont’d You can prototype one of the three use cases that you described for Assignment #1, or you can do something completely different. Show more than logging in and logging out. Demonstrate a key functionality. Use Express on the server side. Maintain the model-view-controller architecture. Use GET and POST routing. You can use Jade or another page engine.