0% found this document useful (0 votes)
62 views

Web Technologies Assignments Assignment-1: Name: V.Aravind Class: CSE 3D Roll No: 19R15A0520

The document contains an assignment submission with questions and answers related to HTML, CSS, and JavaScript. For question 1, the student creates an HTML document with two frames - a top frame that links to department descriptions, and a bottom frame that displays the descriptions. For question 2, the student explains the three types of CSS (inline, internal, external) with examples of each. For question 3, the student defines what an "event" is in JavaScript and provides examples of how JavaScript can handle events like mouse clicks.

Uploaded by

Aravind Vagaldas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Web Technologies Assignments Assignment-1: Name: V.Aravind Class: CSE 3D Roll No: 19R15A0520

The document contains an assignment submission with questions and answers related to HTML, CSS, and JavaScript. For question 1, the student creates an HTML document with two frames - a top frame that links to department descriptions, and a bottom frame that displays the descriptions. For question 2, the student explains the three types of CSS (inline, internal, external) with examples of each. For question 3, the student defines what an "event" is in JavaScript and provides examples of how JavaScript can handle events like mouse clicks.

Uploaded by

Aravind Vagaldas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Web Technologies Assignments

Name: V.Aravind Class: CSE 3D Roll No: 19R15A0520

Assignment-1
Q1) Create a html document that has two frames in one column. The top frame, which must be 20
percent of the column, must have at least four links to other documents; the bottom frame will display
those documents.The links must be names of the departments in your college;The documents must be
at least five-line description of departments.
Ans: Mainframe.html
<html>
<head>
<tittle> Assignment question</title>
</head>
<frameset> rows= "50%, 50%" border="2">
<frame name="top" src="frame1.html">
<frame name =”bottom” src=””>
<noframes>
</frameset>
</html>

Frame1.html
<html>
<body>
<a href="CSE.html" target = "bottom">CSE</a>
<a href="EEE.html" target= “bottom “>ECE</a><br>
<a href="ECE-.html" target="bottom") EEE</a> <br>
<a href="CIVIL.html" target="bottom">Civil</a>
</body>
</html>

CSE.html
<html>
<body>
<h1> CSE:</h1>
<p> Computer science Engineering encompasses a Variety of topics that relate to computation, like analysis of
algorithms, Programming language, Program design, Software and computer hardware. </p>
<h4> What does a computer science engineer do?</h4>
<P> 1. Design and develop Software application for different industries. </P>
<p>2.Manages the software, hardware and network in any industry </p>
</body>
</html>
ECE.html
<h1>ECE </h₁>
<P> The Electrical & Computer Engineering (ECE) Program prepares you for a wide range of engineering Study
and Career options, including business, biomedical engineering, computer hardware, the aerospace industry,
computer software, nanoelectronic chips, Photonics, nanoengineering, robotics and solar energy harvesting and
distribution.</p>
</body>
</html>

EEE.html
<html>
<body>
<h1> EEE </h1>
<P> B.Tech Electrical and Electronics Engineering is a 4-year Undergraduate course that deals with the study of
electricity, electromagnetism, and their applications in various domains such as transport, appliances,
machinery, etc. After completing B.Tech EEE in India, graduates can pursue further education, research-based
work, or job opportunities in government of private firms.
</p>
</body>
</html>

CIVIL.html
<html>
<body>
<p> Civil Engineers are generally responsible for designing, Constructing and managing Various construction
projects such as roads, building, tunnels, bridges and other. In addition, many Civil Engineers are also involved
conducting research
</p>
</body>
</html>

Q2) Explain different types of CSS with an example for each.


Ans: CSS (Cascading Style Sheet) describes the HTML elements which are displayed on screen, paper, or
in other media. It saves a lot of time. It controls the layout of multiple web pages at one time. It sets the font-size,
font-family, color, background color on the page.
There are 3 types of CSS which are below:
o Inline CSS
o Internal/ Embedded CSS
o External CSS
1. Internal CSS
The Internal CSS has <style> tag in the <head> section of the HTML document. This CSS style is an effective
way to style single pages. Using the CSS style for multiple web pages is time-consuming because we require
placing the style on each web page.
Example program:
<!DOCTYPE html>  
<html>  
<head>  
<style>  
body {  
    background-color: black;  
}  
h1 {  
    color: red;  
    padding: 50px;  
}   
</style>  
</head>  
<body>  
<h2>CSS types</h2>  
<p>Cascading Style sheet types: inline, external and internal</p>  
</body>  
</html>  

External CSS
In external CSS, we link the web pages to the external .css file. It is created by text editor. The CSS is more
efficient method for styling a website. By editing the .css file, we can change the whole site at once.
Example program:
<head>  
<link rel="stylesheet" type="text/css" href="style.css">  
</head>  

File: style.css
body {  
    background-color: lightblue;  
}  
h1 {  
    color: navy;  
    margin-left: 20px;  
}   

Inline CSS
Inline CSS is used to style a specific HTML element. Add a style attribute to each HTML tag without using the
selectors. Managing a website may difficult if we use only inline CSS. However, Inline CSS in HTML is useful in
some situations. We have not access the CSS files or to apply styles to element.
Example:
<!DOCTYPE html>  
<html>  
<body style="background-color:white;">  
<h1 style="color:blue;padding:20px;">CSS Tutorials</h1>  
<p style="color:blue;">It will be useful here.</p>  
</body>  
</html>  

Q3) "Javascript is event driven" what is meant by event?Show how javascript can handle events?
Ans: Event: The change in the state of an object is known as an event.
Events handle: I'm HTML, there are various events which represent that some activity is performed by the user.
The browser Javascript interaction with HTML is handled through events that occur when the user or the
browser manipulates a pages.The process of reacting over events is called Event Handling.
Some of the event handlers:
Mouse Events:
Onclick: The onclick attribute fires on a mouse click on the element.
Syntax:
<element onclick=”script”>
Example:
<p id="demo" onclick="myFunction()"> Click on me to change text color</p>

<script>
function myFunction() {
  document.getElementById("demo").style.color = "red";
}
</script>

OnMouseover:
The onmouseover attribute fires when the mouse pointer moves over an element.
<html>
<head> Javascript Event.
<h1> Java script Event </h1>
</head>
<body>
<script language="javascript" type="text/Javascript”>
Function mouseoverevent(){
alert( This is onmouseover event');
}
</script>
<P onmouseover="mouseoverevent (") Keep Cursor over me </P>
</body>
</html>

Q4) Compare and contrast HTML and DHTML.


Ans:
● HTML is a mark-up language, while DHTML is a collection of technology.
● DHTML creates dynamic web pages, whereas HTML creates static web pages.
● DHTML allows including small animations and dynamic menus in Web pages.
● DHML used events, methods, properties to insulate dynamism in HTML Pages.
● DHML is basically using JavaScript and style sheets in an HTML page.
● HTML sites will be slow upon client-side technologies, while DHTML sites will be fast enough upon client-
side technologies.
● HTML creates a plain page without any styles and Scripts called as HTML. Whereas, DHTML creates a
page with HTML, CSS, DOM and Scripts called as DHTML.
● HTML cannot have any server side code but DHTML may contain server side code.
● In HTML, there is no need for database connectivity, but DHTML may require connecting to a database
as it interacts with user.
● HTML files are stored with .htm or .html extension, while DHTML files are stored with .dhtm extension.
● HTML does not require any processing from browser, while DHTML requires processing from browser
which changes its look and feel.

Q5) Write a java script to validate a form consisting of name , age, addres, emailID, hobby(check
box),Gender(radio box),country(drop down menu).
Ans:<html>
<head>
<title> Form Validation </title>
<script type="text/Javascript">
function Validate(){
if (document.myform. Name.value()== "") {
alert ("please provide your name !");
document.myform.Name.focus();
return false;
}
if (document.myform.Email.value()== "")
{
alert(“please provide your Email!");
document.myform.Email.focus();
return false;
}
if(document.myform.Country.value()== "")
{
alert (“please provide your country!")
return false;
}
if (document.myForm.age.value() == "")
{
alert ("Please provide your Age!");
document.myform.age.focus();
return false;
}
if (document.myform.address.value()== "") //{
alert ("Please provide your address! " );
document.myform. address.focus();
return false;
}
return (true);
}
</script>
</head>
<body style="padding-left: 525px;">
<form name="myform" onsubmit="return (validate(B));">
Name<input type="text" name="Name><br><br>
Age<input type= "number" name="age"> <br><br>
E-mail<input type="text" name="Email"><br><br>
Gender: <br><input type="radio" name = 'Male' > Male <br>
<input type="radio' name = 'Female'>Female <br>
<input type = 'others' name='others'>others <br> <br>
Hobbies:<br> <br>
<input type="checkbox" name="books"> Reading Books<br><br>
<input type=checkbox" name = "games"> Playing Games <br> <br>
<input type= "checkbox" name="music"> Listening to music <br><br>
Address: <br>
<textarea cols="30" rows="5 name="address"</textarea> <br><br>
Country:
<select name = "Country">
<option value="-1" selected > select country </option>
<option value="1") USA </option>
<option value="2"> UK </option>
<option value="3"> INDIA </option>
<option value = "4"> PAKISTAN </option>
<option value="5"> RUSSIA</option>
</select><br><br>
<input type="submit" value="submit">
<input type="reset" value=cancel">
</form>
</body>
</html>

Assignment -2
Q1. Explain different types of selectors in detail with an example.
Ans: CSS selectors are used to select the content we want to style. css selectors select HTML elements
according to its id,class,type,attribute etc. There are many types of selectors in class. Below are the different
types of class selectors.
a. CSS Element Selector: It selects the HTML element by name
<html>
<head>
<style>
P{ text-align: center;
color: blue
}
</style>
</head>
<body>
<p> Welcome </p>
</body>
</html>
b. CSS ID Selector: It selects the id attribute of an HTML element to select a specific element. Id is unique
within the page so it is chosen to select a unique element written with hash(“#”) character
<html>
<head>
<style>
#p1{ text-align:centre;
Color:blue;
}
</style>
</head>
<body>
<p id=”p1”>Hello</p>
<p>Welcome</p>
</body>
</html>

c. CSS Class Selector: It selects elements with a specific class attribute. It is used with a full stop(.) followed
by class name.
<html>
<head>
<style>
•p1{ text-align: center; color: blue; }
</styles>
</head>
<body>
<h1 class:"p1" > Class selector </h1>

<p class="p1"> Uses full stop </p>


</body>
</html>

d. CSS Universal Selector: Used as a wildcard character. It selects all the elements on the page.
<html>
<head>
<style>
*{color:blue;}
</style>
<body>
<h2>Universal Selector</h2>
</body>
</html>
e. CSS Group Selector: used to select all the elements with the same style definitions, it is mainly used to
minimize the code. commas(,) are used to separate each selector in grouping.
<html>
<head>
<style>
h1,p{text-align:centre;color:blue;}
</style>
<body>
<h1>Group Selector</h1>
<p>minimizes the code</p>
</body>
</html>

Q2) Explain how switch-case statement is used in Javascript with an example.


Ans: The switch statement is used to perform different actions based on different conditions
The switch expression is evaluated once.The value of the expression is compared with the values of each
case.If there is a match, the associated block of code will be executed.If there is no match, the default code
block is executed. Switch cases use strict comparison. The value must be of same type to match
A strict composition can only be true if the operands are of the same type. It Consists of two keywords

a) break keyword
When the script reaches a break keyword, it breaks out of the switch block. This will stop the execution inside
the switch block. It is not necessary to break the last case.
b) default keyword. It specifies the code to run if there is no case match.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}

Q3) Explain how Math object is used in javascript with an example.


Ans: The math object allows you to perform mathematical tasks on numbers. Math objects, unlike other objects,
have no constructor. It is static. All methods and properties can be used without creating a Math object first.
Math Properties
•Syntax : Math.property
Javascript provides 8 mathematical constants that can be accessed as Math properties

Property Description

Math.E Returns Euler’s number

Math.PI Returns the value of PI

Math.SQRT2 Returns the square root of 2

Math.SQRT1_2 Returns the square root of 1/2

Math.LN2 Returns the natural logarithm of 2

Math.LN10 Returns the natural logarithm of 10


Math.LOG2E Returns base 2 logarithm of E

Math.LOG10E Returns base 10 logarithm of E

Example:
<html>
<head> Math Example</head>
<body>
<h1> Math properties</h1>
<p id="GFG"></p>
<script>
document.getElementById("GFG").innerHTML=“Math.LN10:”+Math.LN10+ “<br>" +"Math.LOG2E:
"+Math.LOG2E + "<br> +"Math.LOG10E" +Math.LOG2E + "<br> +
"Math.SQRT2 : " +Math.SQRT2"<br>"+"Math.LN2:”+Math.LN2+“<br>" +“Math.E :“+Math.E+"<br>"
+“Math.PI:”+Math.PI;
</script>
</body>
</html>
Math methods
Method Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x, in radians

acosh(x) Returns the hyperbolic arccosine of x

asin(x) Returns the arcsine of x, in radians

asinh(x) Returns the hyperbolic arcsine of x

atan(x) Returns the arctangent of x as a numeric value


between -PI/2 and PI/2 radians

atan2(y, x) Returns the arctangent of the quotient of its


arguments

floor(x) Returns x, rounded downwards to the nearest


integer

log(x) Returns the natural logarithm (base E) of x

max(x, y, z, ..., n) Returns the number with the highest value

min(x, y, z, ..., n) Returns the number with the lowest value

pow(x, y) Returns the value of x to the power of y

random() Returns a random number between 0 and 1

round(x) Rounds x to the nearest integer

sign(x) Returns if x is negative, null or positive (-1, 0, 1)


sin(x) Returns the sine of x (x is in radians)

sinh(x) Returns the hyperbolic sine of x

sqrt(x) Returns the square root of x

tan(x) Returns the tangent of an angle

tanh(x) Returns the hyperbolic tangent of a number

trunc(x) Returns the integer part of a number (x)

Q4) Create a XML Schema for Library Management system.


Ans: <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE bookstore SYSTEM "Library.dtd">
<bookstore>
<book>
<title>Web Technologies</title>
<author> Uttam KRoy </author>
<ISBN > 1111</ISBN>
<edition>5</edition>
<publisher>Oxford</publisher>
<price>499</price>
</book>
<book>
<title>PHP</title>
<author>Steven</author>
<ISBN >1111</ISBN>
<edition>4</edition>
<publisher>Oxford</publisher>
<price>599</price>
</book>
</bookstore>
Library.dtd
<?xml version="1.0" encoding="UTF-8"?>
<! ELEMENT bookstore [book+]>
<! ELEMENT book [title, author, ISBN, edition, publisher price]>
<! ELEMENT title [#PCDATA]>
<! ELEMENT author [# PCDATA]>
<! ELEMENT ISBN [# PCDATA]>
<! ELEMENT edition [# PCDATA]>
<! ELEMENT publisher [PCDATA
<! ELEMENT price [#PCADA]>

Q5) Explain the working of XSL.


Ans: XSL stands for Extensible Stylesheet Language.It is used for transforming and presenting XML documents
known as XSLT. XSL is formalized as a specification World Wide Web Consortium (Wac)
The main parts of XSL are:
XSLT: for transforming XML documents into various other types of documents.
XPath: for navigating in XML documents.
XQuery: It is a language for querying XML.
XSL-FD: For formatting XML documents.
Working
• XSLT is written in XML format.
• It is used to define the transformation rules to be applied on the target XML document
•The XSLT processor takes XSLT stylesheets and applies the transformation rules on the target XML document
and then it generates a formatted document in the form of XML, HTML or text format.
• At the end it is used by XSLT formatted to generate the actual object and displayed on the end-user.

Assignment - 3
Q1) Explain the life cycle of servlets with an example.
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the
servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class. The servlet instance is
created only once in the servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The init method is
used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the
init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is received. If servlet is not
initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized,
it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the
Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response)throws ServletException,
IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance from the service. It gives the
servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy
method of the Servlet interface is given below:
public void destroy()
// Java program to show servlet example
// Importing required Java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class AdvanceJavaConcepts extends HttpServlet
{
private String output;

// Initializing servelet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}

// Requesting and printing the output


public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(output);
}

public void destroy()


{
System.out.println("Over");
}
}

Q2) Write a program to illustrate Parameter reading and Parameter initializing.


An object of ServletConfig is created by the web container for each servlet. This object can be used to get
configuration information from a web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is
easier to manage the web application if any specific content is modified from time to time.
Methods of ServletConfig interface
1. public String getInitParameter(String name):Returns the parameter value for the specified parameter
name.
2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter
names.
3. public String getServletName():Returns the name of the servlet.
4. public ServletContext getServletContext():Returns an object of ServletContext.
Syntax to provide the initialization parameter for a servlet
The init-param sub-element of the servlet is used to specify the initialization parameter for a servlet.

1. <web-app>

2. <servlet>
3. ......

4.

5. <init-param>

6. <param-name>parametername</param-name>

7. <param-value>parametervalue</param-value>

8. </init-param>

9. ......

10. </servlet>

11. </web-app>
Q3) Write about the methods in the servlet interface.
Servlet interface provides commandbehavior all the servlets.Servlet interface defines methods that all servlets
must implement.
Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life
cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-
life cycle methods.
Methods are:

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet
and invoked by the web container only once.

public void service(ServletRequest provides a response for the incoming request. It is


request,ServletResponse response) invoked at each request by the web container.

public void destroy() is invoked only once and indicates that servlet is being
destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.

Q4) How to handle HttpRequests and HttpResponses


Ans: The request sent by the computer to a web server, contains all sorts of potentially interesting information; it
is known as HTTP requests.
The HTTP client sends the request to the server in the form of request message which includes following
information:
● The Request-line
● The analysis of source IP address, proxy and port
● The analysis of destination IP address, protocol, port and host
● The Requested URI (Uniform Resource Identifier
The HTTP request methods are:

HTTP Description
Request

GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET request with
extra info sent with the request.

HEAD Asks for only the header part of whatever a GET would return. Just like GET
but with no body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
respond

HttpResponse methods
Sr.No. Method & Description

String encodeRedirectURL(String url)


1 Encodes the specified URL for use in the sendRedirect method or, if encoding
is not needed, returns the URL unchanged.

String encodeURL(String url)


2
Encodes the specified URL by including the session ID in it, or, if encoding is
not needed, returns the URL unchanged.

boolean containsHeader(String name)


3
Returns a Boolean indicating whether the named response header has already
been set.

4 boolean isCommitted()
Returns a Boolean indicating if the response has been committed.

5 void addCookie(Cookie cookie)


Adds the specified cookie to the response.

6 void addDateHeader(String name, long date)


Adds a response header with the given name and date-value.
7 void addHeader(String name, String value)
Adds a response header with the given name and value.

8 void addIntHeader(String name, int value)


Adds a response header with the given name and integer value.

9 void flushBuffer()
Forces any content in the buffer to be written to the client.

void reset()
10
Clears any data that exists in the buffer as well as the status code and headers.

void resetBuffer()
11
Clears the content of the underlying buffer in the response without clearing
headers or status code.

void sendError(int sc)


12
Sends an error response to the client using the specified status code and
clearing the buffer.

13 void sendError(int sc, String msg)


Sends an error response to the client using the specified status.

void sendRedirect(String location)


14 Sends a temporary redirect response to the client using the specified redirect
location URL.

15 void setBufferSize(int size)


Sets the preferred buffer size for the body of the response.

void setCharacterEncoding(String charset)


16
Sets the character encoding (MIME charset) of the response being sent to the
client, for example, to UTF-8.

void setContentLength(int len)


17
Sets the length of the content body in the response In HTTP servlets, this
method sets the HTTP Content-Length header.

void setContentType(String type)


18
Sets the content type of the response being sent to the client, if the response
has not been committed yet.

void setDateHeader(String name, long date)


19 Sets a response header with the given name and date-value.

void setHeader(String name, String value)


20
Sets a response header with the given name and value.

void setIntHeader(String name, int value)


21
Sets a response header with the given name and integer value

void setLocale(Locale loc)


22
Sets the locale of the response, if the response has not been committed yet.
void setStatus(int sc)
23
Sets the status code for this response

Q5) Explain different session tracking techniques.


Ans: Session simply means a particular interval of time. Session tracking is a way to maintain state (data) of a
user. It is also known as session management in servlet. It is used to recognize the particular user.
There are four techniques used in section tracking
1. Cookies
A cookie is a small piece of information that is persisted between the multiple client requests -A cookie has a
name, a single value and optional attributes such as a comment,path and dormin qualifiers, a maximum age and
a version number,
• They are a types of cookies
a. Non-persistent cookie. It is valid for a single session only. It is removed each time when user closes the
browser
b. Persistent cookie. It is Valid for multiple sessions - It is not removed each time the user closes the browser. It
is removed only if user logout or signout.

2. Hidden form field.

•In case of Hidden form field a hidden (invisible) textfield is used for maintaining the state of an user.

•In such a case, we store the information in the hidden field and get it from another servlet. This approach is
better if we have to submit form in all pages and we don't want to depend on the browser. It is widely used in the
comment form of a website. In such case, we store page id or page name in the helden field so that each page
can be uniquely identified

3 URL Rewriting
We append a token or identities to the URL of the next Servlet or the next resource. We can send parameter
name/value pairs using the format url?name1= value&name2=value&??

• A name and a value is separated using an equal = sign, a parameter name/ value pair is separated from
another parameter using (&)

When the user click the hyperlink, the parameter name/ value pair will be passed to server.
•From a servlet, we can getParameter() method to obtain a parameter value.

4) Http Session interface.

•In such case, container creates a session id for each user. The container uses this id to identify the particular
user. An object of Help Session can be used to perform two tasks.
1. bind objects
2. View and manipulate information about a session, such as the session identifier, creation time, and last
accessed time.
• The Http Servlet Request interface provides two methods to get the object of Http Session

a.public HttpSession getSession(): Returns current session associated with this request.

b. public HttpSession getSession(boolean create): Returns the current Http Session associated with this request.
• Commonly used methods of HttpSession interface
a public String getId()
b. public long getCreationTime ( )

c public long getLastAccessedTime()

d. public void invalidate()

Assignment – 4
Q1) Explain about the components of JSP?
Ans: Structure of JSP Page :
JSPs are composed of standard HTML tags and JSP tags. The structure of JavaServer pages are simple and
easily handled by the servlet engine. In addition to HTML ,you can categorize JSPs as following -
● Directives
● Declarations
● Scriptlets
● Comments
● Expressions
Directives :
A directives tag always appears at the top of your JSP file. It is global definition sent to the JSP engine.
Directives contain special processing instructions for the web container. You can import packages, define error
handling pages or the session information of the JSP page. Directives are defined by using <%@ and %> tags.
Syntax -
<%@ directive attribute="value" %>
Declarations :
This tag is used for defining the functions and variables to be used in the JSP. This element of JSPs contains the
java variables and methods which you can call in expression block of JSP page. Declarations are defined by
using <%! and %> tags. Whatever you declare within these tags will be visible to the rest of the page.
Syntax - 
 <%! declaration(s) %>
Scriptlets:
In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the
JSP engine. Scriptlets can be used anywhere in the page. Scriptlets are defined by using <% and %> tags.
Syntax -
 <% Scriptlets%>
Comments :
Comments help in understanding what is actually code doing. JSPs provides two types of comments for putting
comment in your page. First type of comment is for output comment which is appeared in the output stream on
the browser. It is written by using the <!-- and --> tags.
Syntax -
 <!-- comment text -->
Second type of comment is not delivered to the browser. It is written by using the <%-- and --%> tags.
Syntax -
  <%-- comment text --%>
Expressions :
Expressions in JSPs are used to output any data on the generated page. These data are automatically
converted to string and printed on the output stream. It is an instruction to the web container for executing the
code within the expression and replacing it with the resultant output content. For writing expressions in JSP, you
can use <%= and %> tags.
Syntax -<%= expression %>
Q2)Write a JSP with a Bean in Session Scope?
Ans: jsp:useBean
The jsp:useBean action tag is used to locate or instantiate a bean class. bean object of the Bean class is already
created, it doesn't create the bean depending on the scope. But if object of bean is not created, it instantiates the
bean.

Syntax of jsp:useBean action tag

<jsp:useBean id="instanceName" scope= "page | request | session | application"


class="packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression>">
</jsp:useBean>

Attributes and Usage of jsp:useBean action tag


1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be page, request, session or application.
The default scope is page.
o page: specifies that you can use this bean within the JSP page. The default scope is page.
o request: specifies that you can use this bean from any JSP page that processes the same request. It has wider
scope than page..
session: specifies that you can use this bean from any JSP page in the same session whether processes the
same request or not. It has wider scope than request.
o application: specifies that you can use this bean from any JSP page in the same
application. It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must have no-arg or
no constructor and must not be abstract.
4. type: provides the bean a data type if the bean already exists in the scope. It is mainly used with class or
beanName attribute. If you use it without class or beanName, no bean is instantiated.
5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.

JSP with a Bean in Session Scope:


public class Calculator {
public int cube(int n){return n*n*n;}
}
index.jsp file
<jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
<%
int m=obj.cube(5); out.print("cube of 5 is "+m);
%>

Q3)Discuss about the JSP Standard actions?


Ans:
These actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically
insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java
plugin.
1. jsp:include
Includes a file at the time the page is requested.
2. jsp:useBean
Finds or instantiates a JavaBean.
3. jsp:setProperty
Sets the property of a JavaBean.
4. jsp:getProperty
Inserts the property of a JavaBean into the output.
5. jsp:forward
Forwards the requester to a new page.
6. jsp:plugin
Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.
7. jsp:element
Defines XML elements dynamically.
8. jsp:attribute
Defines dynamically-defined XML element's attribute.
9. Jsp:body
Defines dynamically-defined XML element's body.
10. jsp:text
Used to write template text in JSP pages and documents.

Q4) Explain Various CoreTags from JSTL?


Ans: The JSTL core tag provides variable support, URL management, flow control etc. The syntax used for
including JSTL core library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
1. <c:remove> tag: It is used for removing an attribute from a specified scope or from all scopes (page,
request, session and application). By default removes from all.
2. <c: if> tag: This JSTL core tag is used for testing conditions. There are two other optional attributes for
this tag which are var and scope, test is mandatory.
3. <c:choose> tag: It’s like switch statement in Java.
4. <c:when> tag: It’s like case statement in Java.
5. <c:otherwise> tag: It works like default attribute in switch-case statements.
6. <c:catch>tag: This tag is used in exception handling. In this post we have discussed exception handling
using <c:catch> core tag.
7. <c:import> tag: This JSTL core tag is used for importing the content from another file/page to the current
JSP page. Attributes – var, URL and scope.
8. <c:forEach> tag: This tag in JSTL is used for executing the same set of statements for a finite number of
times.
9. <c:forTokens> tag: It is used for iteration but it only works with delimiter.
10. <c:param> tag: This JSTL tag is mostly used with <c:url> and <c:redirect> tags. It adds parameter and
their values to the output of these tags.
11. <c:url> tag: It is used for url formatting or url encoding. It converts a relative url into a application
context’s url. Optional attributes var, context and scope.
12. <c:redirect> tag: It is used for redirecting the current page to another URL, provide the relative address in
the URL attribute of this tag and the page will be redirected to the url.

Assignment - 5
Q1.List out the Features of PHP?
Ans: Features of php
It is most popular and frequently used world wide scripting language, the main reason of popularity is; It is open
source and very simple.
● Simple
● Faster
● Interpreted
● Open Source
● Case Sensitive
● Simplicity
● Efficiency
● Platform Independent
● Security
● Flexibility
● Familiarity
● Error Reporting
● Loosely Typed Language
● Real-Time Access Monitoring
Simple
It is very simple and easy to use, compare to other scripting language it is very simple and easy, this is widely
used all over the world.
Interpreted
It is an interpreted language, i.e. there is no need for compilation.
Faster
It is faster than other scripting language e.g. asp and jsp.
Open Source
Open source means you no need to pay for use php, you can free download and use.
Platform Independent
PHP code will be run on every platform, Linux, Unix, Mac OS X, Windows.
Case Sensitive
PHP is case sensitive scripting language at time of variable declaration. In PHP, all keywords (e.g. if, else, while,
echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive.
Error Reporting
PHP have some predefined error reporting constants to generate a warning or error notice.
Real-Time Access Monitoring
PHP provides access logging by creating the summary of recent accesses for the user.
Loosely Typed Language
PHP supports variable usage without declaring its data type. It will be taken at the time of the execution based
on the type of data it has on its value.

Q2) Write a note on TypeConversion in PHP?


Ans: Datatype conversion is the process of changing the type of the variable from one datatype to another. PHP
provides various datatypes and the type conversion can be performed in various methods. Since, PHP is a
loosly typed language, it allows variable declaration without specifying its datatype.
In computer science, type conversion or typecasting refers to changing an entity of one datatype into another.
There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. Explicit
type conversion in some specific way is known as casting.
Typecasting, or type conversion, is a method of changing an entity from one data type to another. ... An example
of typecasting is converting an integer to a string. This might be done in order to compare two numbers, when
one number is saved as a string and the other is an integer.

Q3) Design an Registration form using PHP?


Ans: <html>
<head>
<title>Registration Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<?php if (isset($_POST['form_submitted'])): ?>
<?php if (!isset($_POST['agree'])): ?>
<p>You have not accepted our terms of service</p>
<?php else: ?>
<h2>Thank You <?php echo $_POST['firstname']; ?></h2>
<p>You have been registered as
<?php echo $_POST['firstname'] . ' ' . $_POST['lastname']; ?>
</p>
<p> Go <a href="/registration_form2.php">back</a> to the form</p>
<?php endif; ?>
<?php else: ?>
<h2>Registration Form</h2>
<form action="registration_form2.php" method="POST">
First name:
<input type="text" name="firstname">
<br> Last name:
<input type="text" name="lastname">
<br> Agree to Terms of Service:
<input type="checkbox" name="agree">
<br>

<input type="hidden" name="form_submitted" value="1" />

<input type="submit" value="Submit">

</form>
<?php endif; ?>
</body>
</html>

Q4) Explain about file read functions with examples?


Ans: fread():
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second parameter specifies the
maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
fgets():
The fgets() function is used to read a single line from a file.
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>

Q5) Explain the procedure of connecting to database using PHP with an example?
Ans: PHP MySQL Connect
Since PHP 5.5, mysql connect() extension is deprecated. Now it is recommended to use one of the 2
alternatives.
mysqli_connect()
PDO::__construct()
PHP mysqli_connect()
PHP mysqli_connect() function I used to connect with MySQL
returns resource if connection is established or null

Syntax
resource mysqli_connect (server, username, password)

PHP mysql_close()
PHP mysqli_close() function is used to disconnect with MySQL database connection is closed or false returns
true if
Syntax
bool mysqli_close(resource Sresource link)

PHP MySQL Connect Example


$host localhost 3306
$user
$conn-mysql_connect($host, $user, $pass)

PHP MySQL Create Database


Since PHP 4.3, mysql_create_db() function is deprecated. Now it is recommended to use one of the 2
alternatives.
mysqli_query()
PDO::_query()

PHP MySQL Delete Record

PHP mysql_query() function is used to delete record in a table. Since PHP 5.5, mysql_query() function is
deprecated. Now it is recommended to use one of the 2 alternatives.
mysqli_query()
PDO::_query(

PHP MySQLi Delete Record Example

Example
<?php

$host='localhost:3306,

$user=" $pass="

$dbname 'test,

$conn mysql_connect($host, $user.$pass,$dbname);


if(!$conn) [

die(Could not connect. 'mysqli_connect_error());

echo Connected successfully br

$id=2

$ql-"delete from emp4 where id-Sid": if mysql_query($conn. Ssql)) {

echo "Record deleted successfully. echo "Could not deleted record" mysqli error($coan).

You might also like