QB Ans AWT

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

Q1. Compare JSP with other technologies?

1. JSP Versus .NET and Active Server Pages(ASP)


.NET is well-designed technology from Microsoft. ASP.NET is the part that
directly competes with servlets and JSP.
Advantage:
1. JSP is portable to multiple operating systems and Web servers. The core .NET
platform runs on a few non-Windows platform.
2. JSP has a clear advantage for the dynamic code. With JSP the dynamic part is
written in Java. So JSP is moe powerful and better suited to complex
applications that require reusable components.
2. JSP Versus PHP
PHP (a recursive acronym for “PHP:Hypertext Preprocessor) is a free, opensource.
HTML-embeddedscripting language that is somewhat similar to both ASP
and JSP.
Advantage:
1. The dynamic part in JSP is written in Java, which already has an extensive
API for networking, database access, distributed objects and the like. Whereas
PHP requires learning an entirely new, less widely used language.
2. JSP is much more widely supported by tool and server vendors than in PHP.
3. JSP Versus Pure Servlets
JSP doesn’t provide any capabilities that couldn’t, in principle, be
accomplished with servlets. JSP documents are automatically translated into
servlets behind the scenes.
Advantage:
1. JSP is more convenient to write and modify
2. By separating the presentation from the content, you can put different
people on different tasks.
Need for Servlets
1. JSP pages get translated into servlets
2. JSP consists of static HTML, special purpose JSP tags and Java code
3. Some tasks are better accomplished by servlets than by JSP
4. Some tasks are better accomplished by a combination of servlets and JSP
Than by either servlets or JSP alone.
4. JSP versus JavaScript
JavaScript is completely distinct from the Java programming language and is
normally used to dynamically generate HTML on the client, building parts of
the web page as the browser loads the document. This is a useful capability
and does not normally overlap with the capabilities of JSP which runs only on
the server.
Advantage:
1. JSP pages include SCRIPT tags forJavaScript, just as normal HTML
pages do.
2. JSP can even be used to dynamically generate the JavaScript that will be
sent to the client.
3. JavaScript is not a competing technology ; it is a Complementary one.

Q2.Explain JSP Expressions in detail?


USING JSP EXPRESSION

A JSP expression is used to insert values directly into the output. It has the following
syntax;
<%= Java Expression %>
The expression is evaluated, converted to a string, and inserted in the page. This
evaluation is
performed at runtime (when the page is requested) and thus has full access to
information about
the request.
Ex: To show the Date/Time that the page has requested
Current Time: <%= new java.util.Date() %>
JSP EXPRESSION
The code placed within JSP expression tag is written to the output stream of the
response. So
you need not write out.print() to write data. It is mainly used to print the values of
variable or
method.
Syntax of JSP expression tag
<%= statement %>
Example of JSP expression tag
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Note: Do not end your statement with semicolon in case of expression tag.
Example of JSP expression tag that prints current time
To display the current time, we have used the getTime() method of Calendar class.
The
getTime() is an instance method of Calendar class, so we have called it after getting
the instance
of Calendar class by the getInstance() method.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The
index.html file gets
the username and sends the request to the welcome.jsp file, which displays the
username.
File: index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>

Q3.Illustrate Scriplets with example?


WRITING SCRIPLETS
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name
In this example, we have created two files index.html and welcome.jsp. The index.html file
gets
the username from the user and the welcome.jsp file prints the username with the welcome
message.
File: index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
SCRIPLET EXAMPLES
A JSP page that uses the bgColor request Parameter to set the background color of the page;
<! DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE> COLOR TESTING </TITLE>
</HEAD>
<%
String bgColor=request.getParameter(“bgColor”);
if ((bgColor==null) || (bgColor.trim().equals(“”)))
{
bgColor=”WHITE”;
}
%>
<BODY BGCOLOR=”<%=bgColor %>”>
<H2 ALIGN=”CENTER”> TESTING A BACKGROUND OF “<%=bgColor %>”
</H2>
</BODY>
</HTML>

Q4.Describe JSP action Tags with example?


JSP Action Tags

There are many JSP action tags or elements. Each JSP action tag is used to
perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean.
The Jsp action
tags are given below.
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:fallback can be used to print the message if plugin is working.
It is used in jsp:plugin.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean
development. So we
will see these tags in bean developement.
jsp:forward action tag
The jsp:forward action tag is used to forward the request to another resource it may
be jsp, html
or another resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:forward>
Example of jsp:forward action tag without parameter
In this example, we are simply forwarding the request to the printdate.jsp file.
index.jsp
<html>
<body>
<h2>this is index page</h2>

<jsp:forward page="printdate.jsp" />


</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Example of jsp:forward action tag with parameter
In this example, we are forwarding the request to the printdate.jsp file with parameter and
printdate.jsp file prints the parameter value with date and time.
index.jsp
<html>
<body>
<h2>this is index page</h2>

<jsp:forward page

Q5.Discuss jsp:include action also compare it with include


directive?
THE jsp:include Action
The jsp:include action tag is used to include the content of another resource it may
be jsp, html or servlet.
The jsp include action tag includes the resource at request time so it is better for
dynamic
pages because there might be changes in future.
The jsp:include tag can be used to include static as well as dynamic pages.
Advantage of jsp:include action tag
Code reusability : We can use a page many times such as including header and footer
pages in all pages. So it saves a lot of time.
Difference between jsp include directive and include action

Example of jsp:include action tag without parameter


In this example, index.jsp file includes the content of the printdate.jsp file.
File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>

Q6.Describe Predefined Variables in Scriplets?


1. request
This variable is the HttpServletRequest associated with the request; it gives you
access to
the request parameters, the request type (Ex: GET or POST) and the incoming HTTP
headers (Ex: Cookies).
2. response
This variable is the HttpServletResponse associated with the response to the client.
Since
the output stream is normally buffered, it is usually legal to set HTTP status codes
and
response headers in the body of JSP pages, even though the setting of headers or
status
codes is not permitted in servlets once any output has been sent to the client. If you
turn
buffering off, however, you must set status codes and headers before supplying any
output.
3. out
This variable is the Writer used to send output to the client. However, to make it easy
to
set response headers at various places in the JSP page, out is not the standard
PrintWriter
but rather a buffered version of Writer called JspWriter. You can adjust the buffer size
through use of the buffer attribute of the page directive. The out variable is used
almost
exclusively in scriplets since JSP expressions are automatically placed in the output
stream and thus rarely used to refer to out explicitly.
4. session
This variable is the HttpSession object associated with the request. Recall that
sessions
are created automatically in JSP, so this variable is bound even if there is no incoming
session reference. The one exception is the use of the session attribute of the page
directive to disable automatic session tracking. In that case, attempts to reference
the
session variable cause errors at the time the JSP page is translated into a servlet.
5. application
This variable is the ServletContext as obtained by getServletContext. Servlets and JSP
pages can store persistent data in the ServletContext object rather than in instance
variables. ServletContext has setAttribute and getAttribute methods that let you
store
arbitrary data associated with specified keys. The difference between storing data in
instance variables and storing it in the ServletContext is that the ServletContext is
shared
by all servlets and JSP pages in the Web application, whereas instance variables are
available only to the same servlet that stored the data.
6. config
This variable is the ServletConfig object for the page. In principle, you can use it to
read
initialization parameters, but, in practice, initialization parameters are read from
jspInit,
not from _jspService.
7. pageContext
JSP introduced a class called PageContext to give a single point of access to many of
the
page attributes. The PageContext class has methods getRequest, getResponse,
getOut,
getSession, and so forth. The pageContext variable stores the value of the
PageContext
object associated with the current page. If a method or constructor needs access to
multiple page-related objects, passing pageContext is easier than passing many
separate
references to request, response, out and so forth.
8. page
This variable is simply a synonym for this and is not very useful. It was created as a
placeholder for the time when the scripting language could be something other than
Java.

Q7.What is OOP in PHP? Explain Classes and Objects?


Object-Oriented programming is faster and easier to execute.
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform
operations on the
data, while object-oriented programming is about creating objects that contain both
data and functions.
Object-oriented programming has several advantages over procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code and shorter
development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of
code. You
should extract out the codes that are common for the application, and place them at
a single place and reuse them instead of repeating it.
PHP - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming.
Look at the following illustration to see the difference between class and objects:
Class: Fruit
Objects: Apple, Banana, Mango
PHP OOP - Classes and Objects
A class is a template for objects, and an object is an instance of class.
OOP Case
Let's assume we have a class named Fruit. A Fruit can have properties like name,
color, weight, etc. We can define variables like $name, $color, and $weight to hold
the values of these properties.
When the individual objects (apple, banana, etc.) are created, they inherit all the
properties and
behaviors from the class, but each object will have different values for the properties.
Define a Class
A class is defined by using the class keyword, followed by the name of the class and a
pair of
curly braces ({}). All its properties and methods go inside the braces:
Syntax
<?php
class Fruit {
// code goes here...
}
?>
Below we declare a class named Fruit consisting of two properties ($name and $color) and
two
methods set_name() and get_name() for setting and getting the $name property:
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Note: In a class, variables are called properties and functions are called methods!
Define Objects
Classes are nothing without objects! We can create multiple objects from a class.
Each object has
all the properties and methods defined in the class, but they will have different
property values.
Objects of a class are created using the new keyword.
In the example below, $apple and $banana are instances of the class Fruit:
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

Q8.What are Traits in PHP? Explain in detail with example?


PHP - What are Traits?
PHP only supports single inheritance: a child class can inherit only from one single
parent.
So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem.
Traits are used to declare methods that can be used in multiple classes. Traits can
have methods and abstract methods that can be used in multiple classes, and the
methods can have any access modifier (public, private, or protected).
Traits are declared with the trait keyword:
Syntax
<?php
trait TraitName {
// some code...
}
?>
To use a trait in a class, use the use keyword:
Syntax
<?php
class MyClass {
use TraitName;
}
?>
Example
<?php
trait message1 {
public function msg1() {
echo "OOP is fun! ";
}
}
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>
Example Explained
Here, we declare one trait: message1. Then, we create a class: Welcome. The class
uses the trait,
and all the methods in the trait will be available in the class.
If other classes need to use the msg1() function, simply use the message1 trait in
those classes.
This reduces code duplication, because there is no need to redeclare the same
method over and over again.

Q9. Explain Iterables in PHP and how to implement iterable


interface as an iterator?
PHP - What is an Iterable?
An iterable is any value which can be looped through with a foreach() loop.
The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data
type for function arguments and function return values.
PHP - Using Iterables
The iterable keyword can be used as a data type of a function argument or as the
return type of a function:
Example
Use an iterable function argument:
<?php
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
$arr = ["a", "b", "c"];
printIterable($arr);
?>
Example
Return an iterable:
<?php
function getIterable():iterable {
return ["a", "b", "c"];
}
$myIterable = getIterable();
foreach($myIterable as $item) {
echo $item;
}
?>
PHP - Creating Iterables
Arrays
All arrays are iterables, so any array can be used as an argument of a function
that requires an iterable.
Iterators
Any object that implements the Iterator interface can be used as an argument of a
function that requires an iterable.
An iterator contains a list of items and provides methods to loop through them. It
keeps a pointer
to one of the elements in the list. Each item in the list should have a key which can be
used to find the item.
An iterator must have these methods:
current() - Returns the element that the pointer is currently pointing to. It can be any
data type
key() Returns the key associated with the current element in the list. It can only be
an integer, float, boolean or string
next() Moves the pointer to the next element in the list
rewind() Moves the pointer to the first element in the list
valid() If the internal pointer is not pointing to any element (for example, if next() was
called at the end of the list), this should return false. It returns true in any other case
Example
Implement the Iterator interface and use it as an iterable:
<?php
// Create an Iterator
class MyIterator implements Iterator {
private $items = [];
private $pointer = 0;
public function __construct($items) {
// array_values() makes sure that the keys are numbers
$this->items = array_values($items);
}
public function current() {
return $this->items[$this->pointer];
}
public function key() {
return $this->pointer;
}
public function next() {
$this->pointer++;
}
public function rewind() {
$this->pointer = 0;
}
public function valid() {
// count() indicates how many items are in the list
return $this->pointer < count($this->items);
}
}
// A function that uses iterables
function printIterable(iterable $myIterable) {
foreach($myIterable as $item) {
echo $item;
}
}
// Use the iterator as an iterable
$iterator = new MyIterator(["a", "b", "c"]);
printIterable($iterator);
?>

Q10.Explain Static Properties and Methods in PHP?


PHP - Static Methods
Static methods can be called directly - without creating an instance of the class first.
Static methods are declared with the static keyword:
Syntax
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>
To access a static method use the class name, double colon (::), and the method
name:
Syntax
ClassName::staticMethod();
Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
// Call static method
greeting::welcome();
?>
Example Explained
Here, we declare a static method: welcome(). Then, we call the static method by
using the class
name, double colon (::), and the method name (without creating an instance of the
class first).

You might also like