2. Purpose of SEO
• To drive targeted traffic to your website [or specific pages]
• Ideally, the traffic drives additional sales
• Most online purchases are made on sites found through search engine listings
3. SEO is Technically Not Paid Advertising
• SEO – influence rankings in the “natural” (a.k.a. “organic”, a.k.a. “algorithmic”)
search results
• PPC – paid search advertising on a pay-per-click basis. The more you pay, the higher
your placement. Stop paying = stop receiving traffic.
• PPC – pay per click
• SEM – encompasses both SEO and PPC
• Search engine marketing
5. Most Commonly Used Search Engines
• Google
• Google AdWords
• Bing
• Microsoft Advertising
• Yahoo Search
6. SEO is Based on Keywords
• Keyword Research
• The “right” keywords are…
• relevant to your business
• popular with searchers
• https://ads.google.com/home/tools/keyword-planner/
8. SEO – Constant Changes
• Topically relevant links from important sites
• Anchor text
• Keyword-rich title tags
• Keyword-rich content
• Internal hierarchical linking structure
• The whole is greater than the sum of the parts
9. Begin The 7 Steps
1) Get Your Site Fully Indexed
2) Get Your Pages Visible
3) Build Links & PageRank
4) Leverage Your PageRank
4) Encourage Clickthrough
6) Track the Right Metrics
7) Avoid Worst Practices
10. 1) Get Your Site Fully Indexed
Search engines are wary of “dynamic” pages - they
fear “spider traps”
The better your PageRank, the deeper and more often
your site will be spidered
11. 1) Get Your Site Fully Indexed
Page # estimates are wildly inaccurate, and include non-indexed pages
(e.g. ones with no title or snippet)
Misconfigurations (in robots.txt, in the type of redirects used, requiring
cookies, etc.) can kill indexation
Keep your error pages out of the index by returning 404 status code
Keep duplicate pages out of the index by standardizing your URLs,
eliminating unnecessary variables, using 301 redirects when needed
12. Not Spider-Friendly
• GET http://www.bananarepublic.com --> 302 Moved Temporarily
• GET http://www.bananarepublic.com/browse/home.do --> 302 Moved
Temporarily
• GET
http://www.bananarepublic.com/browse/home.do?targetURL=http%3A%2
F%2Fwww.bananarepublic.com%2Fbrowse%2Fhome.do&CookieSet=Set --
> 302 Moved Temporarily
• GET http://www.bananarepublic.com/cookieFailure.do --> 200 OK
13. 2) Get Your Pages Visible
• 100+ “signals” that influence ranking
• “Title tag” is the most important copy on the page
• Home page is the most important page of a site
• Every page of your site has a “song” (keyword theme)
• Incorporate keywords into title tags, hyperlink text, headings (H1 & H2 tags), alt tags, and
high up in the page (where they’re given more “weight”)
• Eliminate extraneous HTML code
• “Meta tags” are not a magic bullet
• Have text for navigation, not graphics
14. 3) Build Links and PageRank
• “Link popularity” affects search engine rankings
• PageRank™ - Links from “important” sites have more impact on
your Google rankings (weighted link popularity)
• Google offers a window into your PageRank
• PageRank meter in the Google Toolbar (toolbar.google.com)
• Google Directory (directory.google.com) category pages
• 3rd party tools like SEOChat.com’s “PageRank Lookup” & “PageRank
Search”
• Scores range from 0-10 on a logarithmic scale
15. 4) Leverage Your PageRank
• Your home page’s PageRank gets distributed to your deep pages by virtue of
your hierarchical internal linking structure (e.g. breadcrumb nav)
• Pay attention to the text used within the hyperlink (“Google bombing”)
• Don’t hoard your PageRank
• Don’t link to “bad neighborhoods”
16. 4) Leverage Your PageRank
Avoid PageRank dilution
Canonicalization (www.domain.com vs. domain.com)
Duplicate pages: (session IDs, tracking codes, superfluous parameters)
http://company.com/Products/widget.html
http://company.com/products/widget.html
http://company.com/Products/Widget.html
http://company.com/products/Widget.html
In general, search engines are cautious of dynamic URLs (with ?, &, and = characters) because of
“spider traps”
Rewrite your URLs (using a server module/plug-in) or use a hosted proxy service (e.g. GravityStream)
See http://catalogagemag.com/mag/marketing_right_page_web/
17. 5) Encourage Clickthrough
• Zipf’s Law applies - you need to be at the top of page 1 of the search results.
It’s an implied endorsement.
• Synergistic effect of being at the top of the natural results & paid results
• Entice the user with a compelling call-to-action and value proposition in your
descriptions
• Your title tag is critical
• Snippet gets built automatically, but you CAN influence what’s displayed here
18. 6) Track the Right Metrics
Indexation: # of pages indexed, % of site indexed, % of product
inventory indexed, # of “fresh pages”
Link popularity: # of links, PageRank score (0 - 10)
Rankings: by keyword, “filtered” (penalized) rankings
Keyword popularity: # of searches, competition, KEI (Keyword
Effectiveness Indicator) scores
Cost/ROI: sales by keyword & by engine, cost per lead
19. Avoid Worst Practices
• Target relevant keywords
• Don’t stuff keywords or replicate pages
• Create deep, useful content
• Don't conceal, manipulate, or over-optimize content
• Links should be relevant (no scheming!)
• Observe copyright/trademark law & Google’s guidelines
20. Spamming in Its Many Forms…
• Hidden or small text
• Keyword stuffing
• Targeted to obviously irrelevant keywords
• Automated submitting, resubmitting, deep submitting
• Competitor names in meta tags
• Duplicate pages with minimal or no changes
• Spamglish
• Machine generated content
21. Spamming in Its Many Forms…
Pagejacking
Doorway pages
Cloaking
Submitting to FFA (“Free For All”) sites & link farms
Buying up expired domains with high PageRanks
Scraping
Splogging (spam blogging)
22. Not Spam, But Bad for Rankings
Splash pages, content-less home page, Flash intros
Title tags the same across the site
Error pages in the search results (eg “Session expired”)
"Click here" links
Superfluous text like “Welcome to” at beginning of titles
Spreading site across multiple domains (usually for load balancing)
Content too many levels deep
23. In Summary
• Focus on the right keywords
• Have great keyword-rich content
• Build links, and thus your PageRank™
• Spend that PageRank™ wisely within your site
• Measure the right things
• Continually monitor and benchmark
24. Pay Per Click
• Bid on the search terms
you want
• You only pay when
someone clicks to get to
your website
25. Positives of PPC
• Immediate placement
• You can control budget and positioning
• Only pay if traffic is produced
• You can use inexpensive keywords
26. Negatives of PPC
• Requires a lot of research
• Can cost you a lot of money if done wrong
• Requires you to know about the industry
29. Podcast Assignment
Write a one-to-two-page response paper answering the following questions after listening to a
podcast associated with web design or website development.
• What concepts were discussed that you learned about in BITM 3730? Identify the topics
discussed.
• How did the podcast present these topics differently than the course lectures? Explain how.
• Did the podcast make you more comfortable in using certain technologies? Explain how.
Also detail the name of the podcast, the “edition” of the podcast, and a link to the podcast.
30. Example of Podcast Detail
• Web Design Business with Josh Hall
• 219 - Using YouTube To Grow Your Design Business with Pat
Flynn
• https://podcasts.apple.com/us/podcast/219-using-youtube-to-grow-your-
design-business-with/id1484689808?i=1000581383565
31. Apple Podcasts Link
• https://podcasts.apple.com/us/genre/podcasts-technology/id1318
38. What is CMS?
• Content Management Systems (CMS) are commonly used to create and store data
online
• The most commonly used CMS tools allow individuals to create their own website
without knowing anything about web development [coding in HTML, CSS, JS, etc.]
• Individuals merely install the CMS software to their website and type in specific
information to create websites
39. Two Common Reasons to Use CMS
• User-friendly browser-based publishing tools
• No technical skills required
• Compliance with Accessibility requirements
• W3C standards
40. What is Content?
• Any type or unit of digital information.
• Text, images, graphics, video, sound, documents, records, etc
• Anything that we would like to manage in an electronic format.
41. Why CMS?
• Web Content Management System
• Create/manage HTML & images
• Authoring tools
• Templates for presentation
44. Differences in CMS
• Every CMS has its own unique way of organizing and managing content.
• It helps you to create/edit/delete content in a shared repository (database).
• It contains much improved CSS (Cascading Style Sheets).
• CMS enables content to be shared across the Web sites.
45. Why Use Them?
• Drupal, Joomla, WordPress use a database (tables) to store information
• CMS uses a different technology than standard html/css sites
• The technology is open-source (free!)
• Allows people to update their owns sites
• You are the master of your own domain!
46. Joomla
• The name Joomla is derived from the Swahili word "Jumla", which means "all
together" or "as a whole".
• Joomla! is one of the most powerful Open Source Content Management Systems. It
is used all over the world for everything from simple websites to complex corporate
applications.
• Joomla! is easy to install, simple to manage, and reliable.
47. Joomla
• Joomla is written in PHP, uses object-oriented programming structure
(OOPS) techniques and software design pattern, stores data in a MySql
database, and includes features such as page caching, RSS feeds, printable
versions of pages, news flashes, blogs, polls, search, and support for language
internationalization.
• It is based on a model-view-controller (MVC) web application framework
that can be used independently.
48. Why Joomla?
• It is designed to work perfectly in basic shared web hosting environments, a package that is
least expensive and most common. Installer is simple and just like any other common
desktop software.
• It is supported by several extensions, add-on, and plug in. They are written in PHP, which is
most widely used, general purpose scripting language and best suited for web development.
• Joomla supports SSL logins and SSL pages.
• Joomla probably has a pre built module to transform it in a social bookmarking website.
• Joomla's greatest advantage is availability of a large number of extensions that you can use
to Plug-in extra features into your website and transform your website into anything you
like.
49. WordPress Issues
• The WordPress content management system is an ideal platform for
bloggers as it is easy to install and use.
• Adding or removing post dates, need to be changed in design mode and it
requires knowledge of WP scripting.
• You can add membership functionality in WordPress.
50. Why WordPress?
• With WordPress, any type of website can be created like a personal blog or
website, a photoblog, a business website, a professional portfolio, a
government website, a magazine or news website, an online community, even
a network of websites.
• Website can be made with beautiful with themes, and can be extended with
plugins.
51. WordPress
• Free website on WordPress website
• Installed to your website if you own a domain
• Themes can be uploaded or created for use
52. Drupal Issues
• Learning curve is bigger than Joomla and WordPress
• Less support available than Joomla and WordPress
54. Learning Curve
• WordPress
• Easy, No experience required
• Joomla
• Medium, Easier than Drupal, harder than WordPress.
• Drupal
• Requires technical expertise. Major updates are an effort
55. E-Commerce
• WordPress
• Yes, with plugins
• Joomla
• Extensions for managing products and content
• Drupal
• the latest version, does not support a stable e-commerce module yet
57. Speed
• WordPress
• High traffic can cause limitations
• Joomla
• Faster and less resource intensive
• Drupal
• Consumes resources if not tweaked properly
59. Themes
• WordPress
• Extensive. Tens of thousands of themes
• Joomla
• Few. Thousands of themes
• Drupal
• Many. Thousands of themes
60. Mobile Friendly
• WordPress
• Good. Simple responsive starter themes
• Joomla
• Good. Many mobile extensions to choose from
• Drupal
• Good. Going mobile is simple.
61. Once Installed
• Easier to have website host install for you to avoid potential errors
• Login through Admin Panel, such as wp-admin
• All actions occur with the Admin panel, impact how website looks and is
accessed
65. Using Social Media for Websites
• Adding authenticity
• Grabbing attention
• Boosting imagery
• Inviting interaction
• Embracing mobile
• Elevating User Generated Content
66. Ways Social Media Assists Websites
• More traffic
• More revenue
• Increased brand awareness
• Build personal connection with clients
70. JavaScript Basics
• JavaScript is embedded in an HTML file using
<script></script>
• .js is the file extension for JavaScript
• Functions make up the majority of JavaScript
• If statements are used for condition execution in JavaScript
• You comment out a single line of code using //
71. JavaScript Important Notes
• Like Java [uses functions]
• Interpreted by the browser, not compiled
• Complimentary to HTML, used for dynamic web pages and form validation
• OS and Browser (for the most part) independent
• JavaScript is either embedded in a webpage using <script> …</script> or in a separate file
usually with a .js extension.
• Like stylesheets and css files, JavaScript and js files allows for portability and reusability.
• To reference an external JavaScript: <script src=“scripts.js”></script>
72. DIV and SPAN Reminder
• DIV – gives you the ability to identify particular sections (divisions) of a
document using the id attribute. Particularly useful in AJAX and dynamic
HTML.
• SPAN – has the same attributes and uses above. Both tags have the style,
class and id attributes.
• Primary difference between the two is the DIV tag inherently breaks a
paragraph.
• Both are typically used to apply styles to HTML documents.
73. JavaScript Intro
• JavaScript allows for client-side code execution.
• Similar to Java
• Typically used for client-side form validation, dynamic HTML and AJAX.
• Example:
<script>
document.write(“Our first JavaScript”);
</script>
• In the above example, code is written directly in the HTML document.
• In order for code to be reusable, the code can be stored in a .js file.
76. onclick
• Using standard HTML, a webpage is static (i.e. it won’t change until the
HTML file is changed)
• Using dynamic HTML and events like onClick, the content of a page or a tag
can be changed on the fly
77. onclick Example HTML
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="js/scripts.js"></script>
</head>
<body>
<div id="myDIV">TODO write content</div>
<button id="divChange" onclick="divChange()">Change the DIV value</button><br/>
<button id="divChangeBack" onclick="divChangeBack()">Change the DIV value back</button><br/>
<button id="docChange" onclick="docChange()">Change the entire document</button><br/>
</body>
</html>
78. onclick JavaScript code
function divChange()
{
previousDIV = document.getElementById("myDIV").innerHTML;
document.getElementById("myDIV").innerHTML="DIV has changed";
}
function divChangeBack()
{
document.getElementById("myDIV").innerHTML = previousDIV;
}
function docChange()
{
document.write("Document has changed");
}
79. Another onclick Example HTML
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="styles.css" rel="stylesheet" type="text/css" title="Default Style" id="defaultStyle" />
<link href="styles2.css" rel="stylesheet" type="text/css" title="Mobile Style" id="mobileStyle"/>
<script src="js/scripts.js"></script>
</head>
<body>
<h1>Here is my H1, watch it change.</h1>
<p class="justified">this is a test of the justified class</p>
<button id="styleSwitchButton" onclick="switchStyle()">Switch Style</button>
</body>
</html>
80. Another onclick Example JS
function switchStyle()
{
styleDefault = document.getElementById("defaultStyle");
styleMobile = document.getElementById("mobileStyle");
if (styleDefault.disabled)
{
styleDefault.disabled = false;
styleMobile.disabled = true;
}
else
{
styleDefault.disabled = true;
styleMobile.disabled = false;
}
}
81. JS Functions
• JavaScript code can be written as a block or code that will execute once or as
functions
• Functions are useful when they are used again and again within a page or a
website. One use for a function is form validation. Custom functions can be
written to validate the form before it is submitted.
82. JS Functions Cont.
• The function syntax is
function myFunction(){
• …..;
}
• In the above example, the function name is myFunction and it takes no arguments
• A argument is passed for use within the function
• A function can return a value as well so it can be assigned to an outside variable.
• function myAdditionFunction(a, b) {
return a + b;
}
83. JS Comments
• When writing code, it is useful to embed comments, so the purpose of the
code is understood
// - this comments out a single line
• /*
• */ comments all content between and ignores line breaks
84. document
• Similar to java, there are objects within JavaScript
• The main one to remember is the document object. This object references the entire HTML
document.
• One typical use is the document.getElementById(“myid”).innerHTML=“some string”;
• In the above example, the code will find an HTML element such as a <p>, <div> or a
<span> and change the “value” of that tag (i.e. the content between the open and close
tag).
• In order for the element to be referenced, the id attribute must be used in the opening tag
(<div id=“myid”>This text will change</div>
85. Variables
• In programming, variables allow for the storage of a value so it can be referenced later within the code.
• JavaScript creates variables using the following syntax:
var foo = “a”;
var bar = “b”;
• Javascript has no types. Programming languages typically have types like integer, string, decimal. Javascript stores everything using the same
variable type.
• It is possible to create a variable with no initial value
var myVar;
• var x = 1;
var y = 2;
var z = x + y;
• var x = “test”;
var y = “string”;
var z = x + “ “ + y;
86. Scope
• Variables have a limited scope when defined in a function.
Function myFunction() {
var myLocalVar = 1; //this var will not be accessible from outside
}
87. Operators
• + adds two operands
• - subtracts second operand from the first
• * multiply both operands
• / divide first operand by the second operand
• ++ increments the operator by one
• -- decrements the operator by one
• == Checks if two operands are equal, if so,
returns true, otherwise false
• != Checks if two operands are not equal, if so,
returns true, otherwise false
• > Checks if the first operand is greater than the
second operand
• < Checks if the first operand is less than the
second operand
• >= Checks if the first operand is greater than or
equal to
• <= Checks if the first operand is less than or
equal to
88. Additional Operators
• && returns true if both statements are true
• || returns true if either statement is true
• ^ returns true if only one statement is true
• = simple assignment operator
• += adds right operand to the left operand and assigns to
the left operand
• -= subtracts right operand from the left operand and
assigns to the left operand
• *= multiples right operand with the left operand and
assigns to the left operand.
• /= divides the left operand with the right operand and
assigns to the left operand.
• C += A is equal to c = c+a
• C -= A is equal to c = c-a
• C *= A is equal to c = c * a
• C /= A is equal to c = c/a
89. If Statement
• If statements are used for conditional execution.
• Else statements are used to run a different set of code if the if statement doesn’t evaluate to true
• The syntax in Java is:
if (condition)
{
code to be executed
}
else
{
code to be executed
}
90. If in Action
var alertString='';
var firstName=document.getElementById("firstName");
var lastName=document.getElementById("lastName");
if (firstName.value == "")
{
alertString+='Enter your first namen';
}
if (lastName.value == "")
{
alertString+='Enter your last namen';
}
if (alertString != "")
{
alert(alertString);
}
91. AJAX
• Asynchronous JavaScript and XML
• Why asynchronous? – Allows time for the server to process the request and return the results when
complete. JavaScript proceeds while the server is processing
• Uses XMLHttpRequest – builtin javascript object for sending requests for XML using JavaScript
• Two most useful methods for XMLHttpRequest are open and send.
• Open method has the following parameters
• Method – GET or POST. GET will be sufficient most times however it won’t be sufficient when a uncached
copy of the file is necessary
• url – the URL of the xml file or script
• Async – true or false – send the method asynchronously or not
92. AJAX Cont.
• For the response from the server, you can use the responseText or
responseXML property of the XMLHttpRequest object
• responseText is used when the response consists of plain text
• responseXML is used when the response consists of XML
93. What is a Cookie?
• A small piece of data sent from a website and stored in a user’s web browser
while a user is browsing a website
• When the user browses the same website in the future, the data stored in the
cookie can be retrieved by the website.
94. JavaScript Cookie
• Name: the name of the cookie
• Value: the value of the cookie
• Expires: the date/time when the cookie expires automatically
• Path: the path of the cookie
• Domain: the name of the server that created the cookie
• Secure: whether to use encryption to read/set the cookie
• Only small amounts of data can be stored in a cookie
• Cookies are available via JavaScript only to the domain used when the cookie was created
• Cookies are available only to files in the same directory the cookie was created in (use path “/” to make a
cookie available to all files)
95. Setting a Cookie
• To set a cookie, you assign an appropriate value to document.cookie
• We can write a function so that we don’t need to write the same code again and again
function setCookie(name, value, expireDays)
{
var expires = new Date();
expires.setDate(expires.getDate() + expireDays);
var myCookie = name + "=" + escape(value) +
";expires=" + expires.toGMTString() +
";path=/";
document.cookie = myCookie;
}
96. Explaining What We Just Did
• Var expires is set to a new Date object. An object is a data structure which contains
properties and its behavior.
• The above Date object is created with no date and time. The Date() function is
called its constructor. When setDate is called, it is set with the current date and the
number of days in expiresDays is added hence setting the expire time.
• The myCookie var is nothing but a string. The escape function “escapes” characters
within a string. The characters it escapes are used in the URL and can cause the
HTTP request to fail
• In order to delete a cookie, we can just call setCookie(name, “”, -1). This will clear
out the cookie name and value and set it to expire to yesterday
97. Getting a Cookie
function getCookie(name)
{
if ((document.cookie == null) || (document.cookie == ""))
{
return "";
}
else
{
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++)
{
var cookie = cookies[i].split('=');
if (removeLeadingSpace(cookie[0]) == name)
{
return unescape(cookie[1]);
}
}
return "";
}
}
98. JavaScript Function Test
function myWhileFunction(a, b)
{
var i = 1;
var counter = 1;
while (counter <= b)
{
i = i * a;
counter++;
}
return i;
}
• Explain how many times the following
while loop will run and what the value
of i will be when it is complete when
called with myWhileFunction(2,8)
99. Test Answer
• It will run 8 times
• i will equal 256
function myWhileFunction(a, b)
{
var i = 1;
var counter = 1;
while (counter <= b)
{
i = i * a;
counter++;
}
return i;
}
100. Important Notes
• XML works well with JavaScript
• JavaScript can help in getting a cookie in addition to setting a cookie
• A cookie stores small amounts of data
• The expires function is used to set an expiration date on a cookie
• Cookies are available in the same directory the cookie was created in
102. XML and JavaScript [JS file]
function showData()
{
var xml = new XMLHttpRequest();
var addressHTML = "";
var addressbook = document.getElementById("addressbook");
xml.open("GET", "addressdata.xml", false);
xml.send("");
var xmlDoc = xml.responseXML;
var names = xmlDoc.getElementsByTagName("name");
var mails = xmlDoc.getElementsByTagName("email");
for (var i = 0; i < names.length; i++)
{
var name = names[i].childNodes[0].nodeValue;
var mail = mails[i].childNodes[0].nodeValue;
addressHTML += "<li>" + name + "(" + mail + ")</li>n";
}
addressbook.innerHTML = addressHTML;
}
103. Concerns with Cookies
• Cookies can be overwritten in the browser.
• Some browsers allow for this and others can be edit by opening the file which stores
the cookies.
• Cookies are prime targets for sql injection. Imagine you are performing a
select based on the username:
• select student_id from students where username = “<username>” where <username>
is the valued stored in the cookie.
104. onclick Display Date and Time
<!DOCTYPE html>
<html>
<body>
<h2>Date and Time</h2>
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
<p id="demo"></p>
</body>
</html>
105. JavaScript Compared to HTML/CSS
• HTML to define the content of web pages
• CSS to specify the layout of web pages
• JavaScript to program the behavior of web pages
106. More onclick Examples
<!DOCTYPE html>
<html>
<body>
<button onclick="document.getElementById('demo').innerHTML=Date()">The time
is?</button>
<p id="demo"></p>
</body>
</html>
107. Another onclick Example
<!DOCTYPE html>
<html>
<body>
<button onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>
108. Common JS/HTML Elements
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
onload The browser has finished loading the page
109. JavaScript - Java
• Arrays
• Booleans
• Math Class
• Random Class
• Objects
• Functions
• Assignment requirements
111. Basics
• Java programming language can be embedded into JSP
• JSP stands for Java Server Pages
• JSP is compiled on servlets
• JSP is a server-side web technology
• The primary function of JSP is rendering content
• The primary function of a servlet is processing
112. JSP – Java Server Page
• Based on HTML. JSP pages can be based on HTML pages, just change
the extension
• Server-side web technology
• Compiled into servlets at runtime
• Allows for embedding of Java code directly into the script using
<%.....%>
• Requires Apache Tomcat installation on server
113. Servlet
• Compiled code used to deliver content over the HTTP protocol
• Developed as a Java class conforming to the Java Servlet API
• Typically used in conjunction with JSPs for more extensive processing
114. JSP vs Servlet
• JSPs are more geared towards rendering content
• Servlets are better suited for processing since they are pre-compiled
• Consider the concept of Model-View-Controller (MVC)
• Model is your business model which houses all of the business logic
• View is your users’ view into your application. In this case it would be JSPs
• Controller is the glue between the model and the view
• Spring and Struts are two popular MVCs used in Java web applications
• Servlets will typically process request data, enrich it (process it) and forward the request
onto a JSP for display
115. Working Together
• JavaServer Pages (JSP) is a Java standard technology that enables you to write
dynamic, data-driven pages for your Java web applications.
• JSP is built on top of the Java Servlet specification.
• The two technologies typically work together, especially in older Java web
applications.
• From a coding perspective, the most obvious difference between them is that with
servlets you write Java code and then embed client-side markup (like HTML) into
that code, whereas with JSP you start with the client-side script or markup, then
embed JSP tags to connect your page to the Java backend.
116. JSP vs. Everyone Else
• JSP vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part
is written in Java, not Visual Basic or other MS specific language, so it is more powerful and
easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers.
• JSP vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML.
• JSP vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for
"real" programs that use form data, make database connections, and the like.
• JSP vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image processing
etc.
• JSP vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
117. Methods to Set HTTP Status Code
S.N
o.
Method & Description
1
public void setStatus ( int statusCode )
This method sets an arbitrary status code. The setStatus method
takes an int (the status code) as an argument. If your response
includes a special status code and a document, be sure to
call setStatus before actually returning any of the content with
the PrintWriter.
2
public void sendRedirect(String url)
This method generates a 302 response along with a Location header
giving the URL of the new document.
3
public void sendError(int code, String message)
This method sends a status code (usually 404) along with a short
message that is automatically formatted inside an HTML document
and sent to the client.
118. Applications of Servlet
• Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page
or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media
types and compression schemes the browser understands, and so forth.
• Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in
a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.
120. init
public void init(ServletConfig config)
throws ServletException
• Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
• The servlet container calls the init method exactly once after instantiating the servlet. The init
method must complete successfully before the servlet can receive any requests.
• The servlet container cannot place the servlet into service if the init method
• Throws a ServletException
• Does not return within a time period defined by the Web server
121. destroy
public void destroy()
• Called by the servlet container to indicate to a servlet that the servlet is being taken
out of service. This method is only called once all threads within the servlet's
service method have exited or after a timeout period has passed. After the servlet
container calls this method, it will not call the service method again on this servlet.
• This method gives the servlet an opportunity to clean up any resources that are
being held (for example, memory, file handles, threads) and make sure that any
persistent state is synchronized with the servlet's current state in memory.
122. Servlet Life Cycle
• Servlet life cycle is governed by init(), service(), and destroy().
• The init() method is called when the servlet is loaded and executes only once.
• After the servlet has been initialized, the service() method is invoked to process a
request.
• The servlet remains in the server address space until it is terminated by the server.
Servlet resources are released by calling destroy().
• No calls to service() are made after destroy() is invoked.
123. GUIs
• A GUI (graphical user interface) is a system of interactive visual components
for computer software.
• A GUI displays objects that convey information and represent actions that
can be taken by the user.
• The objects change color, size, or visibility when the user interacts with them
127. In Class Exercise
Create a popup message using an event. Your JavaScript code will go inside an HTML file called
welcome.html. You should create a message on your page such as Hello and when you hover over the
message a popup shows up with a different message, such as Hello and Welcome to My site.
128. Building In Class Exercise
• <html>
• <head>
• <title>JS Event Example</title>
• <script type="text/javascript">
129. Building In Class Exercise
• function trigger()
• {
• document.getElementById("hover").addEventListener("mouseover", popup);
• function popup()
• {
• alert("Welcome to my WebPage!!!");
• }
130. Building In Class Exercise
• }
• </script>
• <style>
• p
• {
• font-size:50px;
• position: fixed;
• left: 550px;
• top: 300px;
• }
• </style>
131. Building In Class Exercise
• </head>
• <body onload="trigger();">
• <p id="hover">Welcome!!!</p>
• </body>
• </html>
132. Building In Class Exercise
• Remember to copy you WYSIWYG code into Notepad and save as
• welcome.html
• Do not save as .js file
134. Review: JavaScript vs Java
• interpreted, not compiled
• more relaxed syntax and rules
• fewer and "looser" data types
• variables don't need to be declared
• errors often silent (few exceptions)
• key construct is the function rather than the class
• "first-class" functions are used in many situations
• contained within a web page and integrates with its HTML/CSS content
135. Review: External Linking
• <script src="filename" type="text/javascript"></script
• script tag should be placed in HTML page's head
• script code is stored in a separate .js file
• JS code can be placed directly in the HTML file's body or head (like CSS
136. Common Uses of JavaScript
• Form validation
• Page embellishments and special effects
• Navigation systems
• Basic math calculations
• Dynamic content manipulation
• Sample applications
• Dashboard widgets in Mac OS X, Google Maps, Philips universal remotes, Writely word
processor, hundreds of others…
137. Example 1: Add Two Numbers
<html>
…
<p> … </p>
<script>
var num1, num2, sum
num1 = prompt("Enter first number")
num2 = prompt("Enter second number")
sum = parseInt(num1) + parseInt(num2)
alert("Sum = " + sum)
</script>
…
</html>
138. Example 2: Browser Events
<script type="text/JavaScript">
function whichButton(event) {
if (event.button==1) {
alert("You clicked the left mouse button!") }
else {
alert("You clicked the right mouse button!")
}}
</script>
…
<body onmousedown="whichButton(event)">
…
</body>
Mouse event causes page-
defined function to be
called
Other events: onLoad, onMouseMove, onKeyPress, onUnLoad
139. Example 3: Page Manipulation
• Some possibilities
• createElement(elementName)
• createTextNode(text)
• appendChild(newChild)
• removeChild(node)
• Example: add a new list item
var list = document.getElementById('t1')
var newitem = document.createElement('li')
var newtext = document.createTextNode(text)
list.appendChild(newitem)
newitem.appendChild(newtext)
This uses the browser
Document Object Model
(DOM). We will focus on
JavaScript as a language,
not its use in the browser
140. Document Object Model (DOM)
• HTML page is structured data
• DOM provides representation of this hierarchy
• Examples
• Properties: document.alinkColor, document.URL, document.forms[ ], document.links[ ],
document.anchors[ ], …
• Methods: document.write(document.referrer)
• These change the content of the page!
• Also Browser Object Model (BOM)
• Window, Document, Frames[], History, Location, Navigator (type and version of browser)
141. Hello World in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Hello World Example</title>
</head>
<body>
<script type="text/javascript">
<!--
document.write("<h1>Hello, world!</h1>");
//-->
</script>
</body>
</html>
142. Number properties/methods
Number object "static" properties
Number.MAX_VALUE largest possible number, roughly 10308
Number.MIN_VALUE smallest positive number, roughly 10-324
Number.NaN Not-a-Number; result of invalid computations
Number.POSITIVE_INFINITY infinity; result of 1/0
Number.NEGATIVE_INFINITY negative infinity; result of -1/0
143. Number properties/methods
Number instance methods
.toString([base]) convert a number to a string with optional base
.toFixed(digits) fixed-point real with given # digits past decimal
.toExponential(digits) convert a number to scientific notation
.toPrecision(digits) floating-point real, given # digits past decimal
144. Number properties/methods
global methods related to numbers
isNaN(expr) true if the expression evaluates to NaN
isFinite(expr) true if expr is neither NaN nor an infinity
145. Math properties/methods
Math.E e, base of natural logarithms: 2.718...
Math.LN10, Math.LN2,
Math.LOG2E, Math.LOG10E
natural logarithm of 10 and 2;
logarithm of e in base 2 and base 10
Math.PI , circle's circumference/diameter: 3.14159...
Math.SQRT1_2, Math.SQRT2 square roots of 1/2 and 2
Math.abs(n) absolute value
Math.acos/asin/atan(n) arc-sin/cosine/tangent of angle in radians
Math.ceil(n) ceiling (rounds a real number up)
Math.cos/sin/tan(n) sin/cosine/tangent of angle in radians
Math.exp(n) en, e raised to the nth power
Math.floor(n) floor (rounds a real number down)
Math.log(n) natural logarithm (base e)
Math.max/min(a, b...) largest/smallest of 2 or more numbers
Math.pow(x, y) xy, x raised to the yth power
Math.random() random real number k in range 0 ≤ k < 1
Math.round(n) round number to nearest whole number
Math.sqrt(n) square root
146. String methods
String.fromCharCode(expr) converts ASCII integer → String
.charAt(index) returns character at index, as a String
.charCodeAt(index) returns ASCII value at a given index
.concat(str...) returns concatenation of string(s) to this one
.indexOf(str[,start])
.lastIndexOf(str[,start])
first/last index at which given string begins in this string, optionally starting
from given index
.match(regexp) returns any matches for this string against the given string or regular
expression ("regex")
.replace(old, new) replaces first occurrence of old string or regular expr. with new string (use
regex to replace all)
.search(regexp) first index where given regex occurs
.slice(start, end)
.substring(start, end)
substr. from start (inclusive) to end (exclusive)
.split(delimiter[,limit]) break apart a string into an array of strings
.toLowerCase()
.toUpperCase()
return new string in all upper/lowercase
147. Dealing with old browsers
• Some old browsers do not recognize script tags
• These browsers will ignore the script tags but will display the included JavaScript
• To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
• The <!-- introduces an HTML comment
• To get JavaScript to ignore the HTML close comment, -->, the // starts a JavaScript comment,
which extends to the end of the line
148. Exception Handling
• Exception handling in JavaScript is almost the same as in Java
• throw expression creates and throws an exception
• The expression is the value of the exception, and can be of any type (often, it's a literal String)
• try {
statements to try
} catch (e) { // Notice: no type declaration for e
exception-handling statements
} finally { // optional, as usual
code that is always executed
}
• With this form, there is only one catch clause
149. Exception Handling
• try {
statements to try
} catch (e if test1) {
exception-handling for the case that test1 is true
} catch (e if test2) {
exception-handling for when test1 is false and test2 is true
} catch (e) {
exception-handling for when both test1and test2 are false
} finally { // optional, as usual
code that is always executed
}
• Typically, the test would be something like
e == "InvalidNameException"
150. JavaScript Warnings
• JavaScript is a big, complex language
• We’ve only scratched the surface
• It’s easy to get started in JavaScript, but if you need to use it heavily, plan to invest time in learning it well
• Write and test your programs a little bit at a time
• JavaScript is not totally platform independent
• Expect different browsers to behave differently
• Write and test your programs a little bit at a time
• Browsers aren’t designed to report errors
• Don’t expect to get any helpful error messages
• Write and test your programs a little bit at a time
151. JS Pop Up Type 1: Alert Box
• An alert box is often used if you want to make sure
information comes through to the user.
• When an alert box pops up, the user will have to
click "OK" to proceed.
152. Alert Box Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
153. JS Pop Up Type 2: Confirm Box
• A confirm box is often used if you want the user to verify or accept something.
• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
• If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
154. Confirm Box Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
155. JS Pop Up Type 3: Prompt Box
• A prompt box is often used if you want the user to input a value before entering a
page.
• When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.
• If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
156. Prompt Box Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
157. Two Input Prompt Example
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--
var favcolour, favcolour2;
favcolour = prompt("What is your Favorite colour?");
favcolour2 = prompt("How about your second favorite colour?");
document.write(favcolour," ", favcolour2);
// -->
</script>
</body>
</html>
158. JavaScript Popups
<script>
// JavaScript popup window function
function basicPopup(url) {
popupWindow =
window.open(url,'popUpWindow','height=300,width=700,left=50,top=50,resizable=yes,scrollbars=
yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes')
}
</script>
<a href="http://courses.shu.edu/BITM3730/marinom6/" onclick="basicPopup(this.href);return
false">Click here to visit my website</a>
159. JavaScript Assignment
• Combine your skills from CSS [onclick] and your JS skills to create an HTML
file called popup.html that when you click an onclick it will open your
courses.shu.edu website as a popup.