Webtechnologies - CIE-356 T - Unit 2 Notes
Webtechnologies - CIE-356 T - Unit 2 Notes
Unit 2 Notes
WebTechnologies(CIE-356T)
What is JavaScript?
The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":
Example
<!DOCTYPE html>
<html>
<body>
</body>
Example
In this example JavaScript changes the value of the src (source) attribute of
an <img> tag:
<!DOCTYPE html>
<html>
<body>
<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn
on the light</button>
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn
off the light</button>
</body>
</html>
There are many advantages linked with The primary advantage is its ability to
this like faster. highly customize, response
response times, a more interactive requirements, access rights based on
application. user.
It does not provide security for data. It provides more security for data.
HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.
No need of interaction with the server. It is all about interacting with the servers.
JavaScript Variables
Example
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
. object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).
. <script>
. emp={id:102,name:"Shyam Kumar",salary:40000}
. document.write(emp.id+" "+emp.name+" "+emp.salary);
. </script>
. <script>
. var emp=new Object();
. emp.id=101;
. emp.name="Ravi Malik";
. emp.salary=50000;
. document.write(emp.id+" "+emp.name+" "+emp.salary);
. </script>
Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
. <script>
. function emp(id,name,salary){
. this.id=id;
. this.name=name;
. this.salary=salary;
. }
. e=new emp(103,"Vimal Jaiswal",30000);
.
. document.write(e.id+" "+e.name+" "+e.salary);
. </script>
We can define method in JavaScript object. But before defining method, we need to
add property in the function with same name as method.
. <script>
. function emp(id,name,salary){
. this.id=id;
. this.name=name;
. this.salary=salary;
.
. this.changeSalary=changeSalary;
. function changeSalary(otherSalary){
. this.salary=otherSalary;
. }
. }
. e=new emp(103,"Sonoo Jaiswal",30000);
. document.write(e.id+" "+e.name+" "+e.salary);
. e.changeSalary(45000);
. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
. </script>
With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.
When a web page is loaded, the browser creates a Document Object Model of the
page.
With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
The HTML DOM is a standard object model and programming interface for HTML.
It defines:
In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.
HTML DOM methods are actions you can perform (on HTML Elements).
HTML DOM properties are values (of HTML Elements) that you can set or change.
The HTML DOM can be accessed with JavaScript (and with other programming
languages).
A property is a value that you can get or set (like changing the content of an HTML
element).
Example
The following example changes the content (the innerHTML) of the <p> element
with id="demo":
Example
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="demo" to find the element.
The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML
elements.
The HTML DOM allows JavaScript to change the content of HTML elements.
Example
<html>
<body>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
</html>
Example explained:
Example
<!DOCTYPE html>
<html>
<body>
<script>
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
</body>
</html>
Example explained:
This example changes the value of the src attribute of an <img> element:
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
</body>
</html>
Example explained:
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("demo").innerHTML = "Date : " + Date(); </script>
</body>
</html>
document.write()
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
JavaScript Forms
If a form field (fname) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:
JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Submit
If a form field (fname) is empty, the required attribute prevents this form from being
submitted:
Automatic HTML form validation does not work in Internet Explorer 9 or earlier.
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different
ways.
Server side validation is performed by a web server, after input has been sent to the
server.
Client side validation is performed by a web browser, before input is sent to a web
server.
Introduction to JSP
JSP simplifies web development by combining the strengths of Java with the
flexibility of HTML. Some of the advantages of JSP over Servlets are listed below:
• JSP code is easier to manage than Servlets as it separates UI and business
logic.
• JSP minimizes the amount of code required for web applications.
• Easily generates content dynamically in response to user interactions.
• It provides access to the complete range of Java APIs for robust application
development.
• JSP is suitable for applications with growing user bases.
Code Length Jsp required less code Servlets required more code
JSP Elements
We will learn about the several elements available in JSP with suitable examples. In
JSP elements can be divided into 4 different types.
• Expression
• Scriplets
• Directives
• Declarations
1. Expression
This tag is used to output any data on the generated page. These data are
automatically converted to a string and printed on the output stream.
Syntax:
<%= “Anything” %>
Note: JSP Expressions start with Syntax of JSP Scriptles are with <%=and ends
with %>. Between these, you can put anything that will convert to the String and
that will be displayed.
Example:
<%=”HelloWorld!” %>
2. Scriplets
This allows inserting any amount of valid Java code. These codes are placed in the
_jspService() method by the JSP engine.
Syntax:
<%
// Java codes
%>
Note: JSP Scriptlets begins with <% and ends %> . We can embed any amount of
Java code in the JSP Scriptlets. JSP Engine places these codes in the _jspService()
method.
Example:
<%
String name = “Geek”;
out.println(“Hello, ” + name);
%>
Variables available to the JSP Scriptlets are:
• Request
• Response
• Session
• Out
3. Directives
A JSP directive starts with <%@ characters. In the directives, we can import
packages, define error-handling pages, or configure session information for the JSP
page.
Syntax:
<%@ directive attribute=”value” %>
Types of Directives:
• page: It defines page settings.
• include: It includes other files.
• taglib: It declares a custom tag library.
4. Declarations
This is used for defining functions and variables to be used in the JSP.
Syntax:
<%!
//java codes
%>
Note: JSP Declaratives begins with <%! and ends %> with We can embed any
amount of java code in the JSP Declaratives. Variables and functions defined in the
declaratives are class-level and can be used anywhere on the JSP page.
Example:
<%@ page import="java.util.*" %><html><body>
<%!
Date theDate = new Date();
Date getDate() {
System.out.println("In getDate() method");
return theDate;
}
%>
Hello! The time is now <%= getDate() %></body></html>
Example:
<!DOCTYPE html><html><head>
<title>A Web Page</title></head><body>
1. Save the JSP file using the .jsp extension (e.g., hello.jsp).
2. Start the server (e.g., Apache Tomcat).
3. Place your application inside the appropriate folder (e.g., webapps for
Tomcat).
4. Open the browser and enter the JSP page URL:
http://localhost:portnumber/YourApplicationContextRoot/jspfile
The JSP file is compiled and executed.
As depicted in the above diagram, JSP page is translated into Servlet by the help of
JSP translator. The JSP translator is a part of the web server which is responsible for
translating the JSP page into Servlet. After that, Servlet page is compiled by the
compiler and gets converted into the class file. Moreover, all the processes that
happen in Servlet are performed on JSP later like initialization, committing response
to the browser and destroy.
To create the first JSP page, write some HTML code as given below, and save it
by .jsp extension. We have saved this file as index.jsp. Put it in a folder and paste the
folder in the web-apps directory in apache tomcat to run the JSP page.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java
code in the JSP page. We will learn scriptlet tag later.
. <html>
. <body>
. <% out.print(2*5); %>
. </body>
. </html>
It will print 10 on the browser.
The directory structure of JSP page is same as Servlet. We contain the JSP page
outside the WEB-INF folder or in any directory.
In JSP (Java Server Pages), session tracking is essential for maintaining user-
specific data across multiple requests. Two commonly used techniques for session
tracking in JSP are:
1. Using Cookies
2. Using HttpSession (Session Object)
Cookies are small pieces of data stored on the client’s browser and sent to the server
with each request.
jsp
CopyEdit
<%
Cookie userCookie = new Cookie("username", "JohnDoe");
userCookie.setMaxAge(60 * 60 * 24); // Cookie valid for 1 day
response.addCookie(userCookie);
%>
Cookie has been set!
jsp
CopyEdit
<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
out.print("Welcome back, " + cookie.getValue());
}
}
} else {
out.print("No cookies found!");
}
%>
Notes:
• Cookies store small amounts of data and are sent with each HTTP request.
• Use setMaxAge(0) to delete a cookie.
HttpSession is a built-in JSP API that maintains user data across multiple requests on
the server.
jsp
CopyEdit
<%
HttpSession sessionObj = request.getSession();
sessionObj.setAttribute("user", "JohnDoe");
%>
User session is created!
jsp
CopyEdit
<%
HttpSession sessionObj = request.getSession(false);
if (sessionObj != null && sessionObj.getAttribute("user") != null) {
out.print("Hello, " + sessionObj.getAttribute("user"));
} else {
out.print("No active session found!");
}
%>
jsp
CopyEdit
<%
HttpSession sessionObj = request.getSession(false);
if (sessionObj != null) {
sessionObj.invalidate();
out.print("Session has been destroyed!");
}
%>
Notes:
• Use cookies for lightweight data storage and persistent user preferences.
• Use HttpSession for secure, temporary storage of user data.