HTML 1. Why is HTML validation recommended? 2. Label every component of the following HTML element (Some of the possible labels are attributes, values, content, start/end tag, etc.). <a href=“links.html”>Useful links </a> 3. Give an example where an absolute link is more appropriate to use than a relative link. 4. Correct any invalid HTML 5 syntax: a) <!DOCTYPE html> <!-- An example file <!-- Our first Web page --> <html> <body> <h1> Welcome to <b> SY306! </h1> </b> <h2> Today’s Agenda </h2> <li> HTML5 <li> JavaScript </body> b) <!DOCTYPE htm> <html> <title>Internet and WWW How to Program - Welcome</title> <body> <img scr = "xmlhtp.jpg" height = "238" width = "183" > <h1 align=“center”>Under construction</h1> </body> </html> c) <html> <head> <title>Internet and WWW How to Program - Links</title> </head> <body> <b> <h1>Here are my favorite links</h1> </b> <p><A href = "http://www.yahoo.com">Yahoo!</A></p> <p><A mailto = "[email protected]">Webmaster</A></p> </body> </html> d) <!DOCTYPE html> <html> <head> <title>Best features of the Internet</title> </head> <body> <ul> <li>Meet new people from around the world.</li> <li>Access to new media as it becomes public: </li> <ul> <li>New games</li> <li>New applications & software </ul> <li>Search engines</li> </ul> </body> </html> 5. Write the code to generate this table: a) b) c) 6. What kind of security each of the following provides: Using <input type=“password”> Using <input type=“hidden”> Using https:// Using http:// 7. Write the code to generate this form – the script to execute when the form is submitted is confirm.py: 8. Write the code to generate this form – the script to execute when the form is submitted is search.py: CSS 9. What is a clickJacking attack? 10. Write an external stylesheet styles.css that makes every h1 element centered; apply the stylesheet to starter.html 11. Write an embedded stylesheet that will: Make every <h1> and <h2> section have 20pt size text Put lines above all links instead of under them Define a generic selector called “cat" that will italicize text 12. Write an external stylesheet that will: Using some relative size, make all <h3> text twice as large as <h4> text Make normal paragraphs that are nested inside a table appear in bold. 13. Where is the syntax bug in the following code: /* styles.css */ td {background-color: green; color: white} th {background-color: green; color: red} a {font-weight: bold; text-decoration: none} table {margin-left: 5em, border-style: groove, border-width: thick} div {border-style: inset; border-width: thick} .crazy {color: yellow; font-weight:700} .mild {color: gray; text-decoration: underline} 14. What attributes does the <p> get assigned? <style type = “text/css”> body { font-weight: bold } td { font-size: 14pt; font-color: green } .cool { font-color: red } p { font-size: 12pt } td p { text-decoration: underline; font-color: yellow } </style> <table><tr> <td><p class=“cool”>Let’s get it started</p></td> </tr></table> 15. Draw the output rendered by the browser when the following code is executed: <head> <style type=“text/css”> .pane { float:right; width:20%; height:600px; border:1px solid black } .header { width:75%; height:100px; border:1px solid black } .main { width:75%; height:500px; border:1px solid black } </style> </head> <body> <div class=“pane”> some content </div> <div class=“header”> the header </div> <div class=“main”> the main body </div> </body> JavaScript 16. What is the output of the following JavaScript program: a) var x, y, z; x = 7; y = 9; z = "abc"; window.alert(x+y+z); window.alert(z+y+x); if (x) window.alert("x true"); x = "seven"; window.alert(x+y+z); b) var a, b, c; a = 1; b = 2; c = 3; d = a + b * c; window.alert("<h1>Begin</h1>"); if (d < 20) window.alert("d is okay: "+d); else window.alert("d is too high!:"+ d); d = d - 3; document.writeln("<h1>Done. Final d = "+d+"</h1>"); 17. Write a JavaScript snippet to read in a number from the user and output its absolute value. 18. Write a JavaScript snippet to read in three numbers x, y, z and output them in sorted order. 19. Consider the following code: /* Return an integer no larger than ‘max’ */ var max = 25; var value; do { value = window.prompt( "Please enter an integer no larger than "+max); } while (value > max); a) What is the purpose of this code? b) When does this code work, and why? c) When does it fail and how do you fix it? 20. What is the output of the following JavaScript program? a) function dog(g) { h = 3; var sum = g+h; document.write("<br> Sum is: "+sum); } g = 7; h = 5; document.writeln("<br> g: "+g+" h: "+h); dog(g); document.writeln("<br> g: "+g+" h: "+h); document.writeln("<br> sum: "+sum); document.writeln(“<br> End of script"); b) function fun1 (x) { x = x + 3; y = y + 4; document.writeln("<br> FUN1: "+x+ "," +y); } function fun2 () { var y; x = x + 10; y = y + 20; document.writeln("<br> FUN2: "+x+ "," +y); } x = 1; y = 2; document.writeln("<br> MAIN #1: "+x+ "," +y); fun1(x); document.writeln("<br> MAIN #2: "+x+ "," +y); fun1(y); document.writeln("<br> MAIN #3: "+x+ "," +y); fun2(); document.writeln("<br> MAIN #4: "+x+ "," +y); c) function printme( z ) { document.writeln("<br> z is ",z); } var array1 = [17, 21, 42]; var array2 = [14, 19]; var x = 1; printme (array1); printme (array2[1]); printme (x); array1[x] = 57; printme (array1); 21. Write a function that takes two arguments and returns the minimum of the two; write code to invoke the function 22. a) Write a function “sumArray” as follows: Input: an array Output: the sum of that array b.) Write test code to create an array and call “sumArray” on it. DHTML 23. Change this code to make the <p> element have a large font when you move the mouse over it. <!DOCTYPE html> <html> <head> <meta charset = “utf-8” /> <title>Bigger</title> <script type = "text/javascript"> </script> </head> <body> <p> Welcome to my page! </p> </body> </html> 24. Modify the code below so that clicking on the button changes target of <a> element to “dog.html” <!DOCTYPE html> <html><head> <meta charset = "utf-8" /> <title>Change Link</title> <script type = "text/javascript"> </script> </head> <body> <p><a href="cat.html">See some animals!</a></p> <form> <input type="button" value="Change animal“ /> </form> </body> </html> 25. Write a form to read in a password from the user in two boxes. When they submit the form, proceed only if the passwords are the same. Regular Expressions 26. Write the expression to replace one or more newline characters in a string with “&&”. Make it work for both Unix (\n) and Windows (\r\n) 27. What are some common uses of regular expressions in web programming? Cookies – third party cookies 28. What are cookies; how do they work? 29. What are 3rd party cookies? Python and CGI: 30. Write Python script that will, given the URL provided below, generate HTML that looks like the screenshot http://mope.academy.usna.edu/~alice/sy306/ice/ex1.py?maxNumber=5 31. Write a Python script that accepts two numbers from browser user, prints error if num2 is zero, otherwise outputs num1/num2. Cookies: 32. JS: Ask user for favorite quote using a window prompt. Save quote in a cookie identified by “favQuote”. Display quote on the page using an alert. 33. JS: Read the value of cookie identified by “favQuote” and display it in a pop-up msg if it exists, otherwise display “no quotes” 34. Python: Write a Python script to create a cookie with identifier “favQuote” and content provided by user through CGI (param name “quote”). Output a confirmation message to the user “quote was saved” displayed on the page. Input validation, XSS attacks 35. What is a JavaScript injection? 36. Explain the steps of a typical reflective XSS attack. 37. Explain how input filtering can be used to prevent XSS attacks SQL 38. Write the SQL to create the Enrolled table with the following schema: Enrolled(Alpha, Cid, Semester, Grade) Assume reasonable types for the columns. Primary keys are underlined, and foreign keys are in italic 39. Write the SQL to update the grade of student with alpha 181234 enrolled in SY306 during Spring2017 semester in the Enrolled table above. The new grade is ‘A’. 40. Consider the table: Department(DeptName, ChairName, WebAddress, DivName) Write the SQL query to find the name of the Chair of the ‘Math’ Department 41. Consider the table Students(Alpha, SName, Email, Major) Write the SQL query to find the alpha and name of SCY or SIT students with ‘23’ somewhere in their email address. Display the results sorted by Alpha in descending order. 42. Consider the tables: Students(SNb, SName, Email) Courses(Cid,CName, Dept) Enrolled(SNb,Cid, Semester) a) Find the student number and name for each student enrolled in ‘Spring2017’ semester b) Find the names of all students enrolled in courses offered by the ‘ComSci’ department SQL with Python 43. Consider the following tables and 2 files: CREATE TABLE songs ( SongID int NOT NULL auto_increment, Title varchar(30) NOT NULL, Artist varchar(30) NOT NULL, Votes int not null default 0, Constraint PK_songs PRIMARY KEY (SongID) ); song.py: import mysql.connector # Song class- adds, deletes, prints songs class song: # This class is used to create and maintain songs for the survey def __init__(self): pass #add a song to the database #songID is AUTO_INCREMENT and votes has a default of 0, so no need to worry about them def addSong(cursor, artist, title): # TODO #create query statement #execute the query #check number of rows affected > 0 if insert successful #get the last songid inserted #if insert successful (number of rows inserted > 0) # return the songID (AUTO_INCREMENT key of song table) generated #else return False def printSongs(cursor): query = "SELECT SongID, Artist, Title, Votes FROM songs ORDER BY Artist, Title" # query = "SELECT Artist FROM songs ORDER BY Artist, Title" # if only one column returned, make sure we read it as a tuple of 1 element, which is (col1,) try: cursor.execute(query) except mysql.connector.Error as err: #for DEBUG only we'll print the error and statement- we should print some generic message instead for production site print ('<p style = "color:red"') print(err) print (" for statement" + cursor.statement ) print ('</p>') nbRows = 0 #create a table with results table = "<table><tr><th>SongID</th><th>Artist</th><th>Title</th><th>Votes</th></tr>\n " for (songID, artist, title, votes) in cursor: # for (artist,) in cursor: #do something like this if only one column, artist in the example, is returned - needs to be a tuple, so have the , table += "<tr><td>"+str(songID) + "</td><td>" + artist+"</td><td>"+title+"</td><td>" + str(votes) + "</td></tr>\n" nbRows+=1 table += "</table>" if nbRows > 0: return table else: return "" songPage.py: #!/usr/bin/env python3 import cgi,cgitb cgitb.enable() import mysql.connector from mysql.connector import errorcode from song import song import config print( "Content-type:text/html\n"); print ("""\ <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <title>DB connection with Python</title> </head> <body> """) #connect to the database try: cnx = mysql.connector.connect(user=config.USER, password = config.PASSWORD, host = config.HOST, database=config.DATABASE) #check for errors except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print(err) print("<p>Fix your code or Contact your system admin</p></body></html>") quit() #create cursor to send queries cursor = cnx.cursor() #see if needed to insert data - get parameters from the form params = cgi.FieldStorage() insertButton = params.getvalue("insert") #if insert button was pushed if insertButton: #get the artist and title from the form artist = params.getvalue("artist") title = params.getvalue("title") #call the add song function in song to insert the song result = song.addSong(cursor, artist, title) #print either a confirmation message or error message if result: print ('<h2>New song with id ' + str(result) + ' inserted into the database</h2>') else: print ('<h2>Could not insert the song</h2>') #create the page print ("<h1>Favorite songs</h1>") print ('<form method = "post" action = "songPage_handout.py">') #TODO: print a table with the songs from database, or "No songs in database" message if there are no songs. Use the printSongs function in song #print the inputs for getting the artist and title, and a submit button to insert print ("""\ <p> <label>Artist: <input type = "text" name = "artist"></label><br> <label>Title: <input type = "text" name = "title"></label><br> <input type = "submit" name = "insert" value = "Insert song"> </p>""") print ("</form>") #close cursor since we don't use it anymore cursor.close() #commit the transaction cnx.commit() #this is really important otherwise all changes lost #close connection cnx.close() #print end html tags print("</body></html>"); a) In songPage.py, complete the code to print the table of songs from the database, by using the printSongs method in the song class b) In song.py, complete the code for the addSong() method to insert a song into the database Sessions 44. Complete the following code to create or continue a session that stores into a session variable the time of last visit (which is the time the script is run): #!/usr/bin/env python3 #from http://webpython.codepoint.net import hashlib, time, os, shelve from http import cookies import cgitb; cgitb.enable() cookie = cookies.SimpleCookie() string_cookie = os.environ.get('HTTP_COOKIE') if not string_cookie: #create session id and cookie sid = hashlib.sha256(repr(time.time()).encode()).hexdigest() cookie['sid'] = sid message = 'New session' else: #read the cookie cookie.load(string_cookie) if 'sid' in cookie: sid = cookie['sid'].value else: sid = hashlib.sha256(repr(time.time()).encode()).hexdigest() cookie['sid'] = sid message = 'New session' cookie['sid']['expires'] = 12 * 30 * 24 * 60 * 60 #ICE print the cookie, content type line # and start HTML file # The shelve module will persist the session data # and expose it as a dictionary #create file name /tmp/sess_sid filename #open shelve with that name; store in variable called "session" #Retrieve last visit time from the session and print value # Save the current time in the session #close shelf (saves the session variables to disk) SQL Injections: 45. Consider the following snippet of a Pyhton script that is executed when a user submits a web form asking for username and password; form = cgi.FieldStorage() user = pass = result “‘ AND #if at form.getvalue("username") form.getvalue(“password”) = cursor.query(“SELECT * FROM Users_Table WHERE name = ‘” + user + passwd = ‘” + pass +”’”); least one result, user allowed to login a) Give the exact input that can be provided by a user such that the user can login without having a valid username and password Value for username field _________________________________________________ Value for password field______________________________________________ 46. List one way or preventing SQL injections? Why is that method effective? DB Security 47. Write the SQL command to grant select privileges on your PRODUCT table to user ‘alice’ Will the user ‘alice’ be able to select from the PRODUCT table after you executed your command? Will the user “alice” be able to remove the PRODUCT table from your database? Write the SQL command to remove the privileges to your PRODUCT table from the user ‘alice’ HTTP/HTTPS protocol 48. Write the HTTP GET request generated when you enter http://www.usna.edu/cs/news.html in the address bar of a browser and you hit enter: 49. How do the HTTP request and response look like? http://mope.academy.usna.edu/~adina/welcome.py?username=ac welcome.py #!/usr/bin/env python3 from http import cookies import urllib.parse import cgi #get parameters params = cgi.FieldStorage() username = params.getvalue("username") cookie = cookies.SimpleCookie() cookie["Username"] = urllib.parse.quote(username) print (cookie) print( "Content-type:text/html\n"); print (<!DOCTYPE html> <html><head><meta charset = "utf-8"> <title>Storing cookies with Python</title> </head><body>""") print ("<h1>Welcome "+ username + "</h1>"); print("</body></html>"); HTTP Request: HTTP Response: 50. Assume that you are writing a login form and you need to submit the login information securely (encrypted) The script to execute on the server is “login.py”. The server is mope.academy.usna.edu. What do you need to do, so the login information sent by the browser to the server, is encrypted? Cross-site Request Forgery (CSRF) attack 51. List the steps of a CSRF attack 52. What are the pre-requisites (what needs to happen) of a CSRF attack? 53. Describe what is “referrer validation”, in the context of CSRF attacks 54. Why referrer validation is not always preventing CSRF attacks? 55. Describe one method to prevent CSRF attacks HTTP authentication 56. Is encryption used in the HTTP basic authentication? 57. Assume that the user is requesting the SecretFolder/secretFile.html that is protected by basic http authentication. What is the HTTP Response header that a browser will receive when first making the request? 58. Give one advantage and one disadvantage/problem of HTTP basic authentication 59. Give one advantage and one disadvantage/problem of HTTP digest authentication 60. Why is form-based authentication the most widely used method of authentication for web applications?
© Copyright 2026 Paperzz