Reducing the volatility of pro¢ts and risk spreading

A single-product, single-market ¢rm is vulnerable to erratic and cyclical variations indemand and input costs, as well as to long-term decline in demand. Together, thesetwo factors lead to cyclically £uctuating revenue and costs and hence pro¢ts, as wellas to pro¢ts that are potentially in secular decline. Therefore, diversi¢cation is a wayfor the ¢rm to reduce the dispersion and o¡set the decline in pro¢ts. Cyclical variationscan be o¡set by the acquisition of products whose sales move counter-cyclically to itsexisting product, while secular decline can be o¡set by acquiring products exhibitinglong-term growth. Such diversi¢cation strategies are intended to both stabilize andprevent the ¢rm from making losses, because such diversi¢cation may be a strategydesigned to avoid bankruptcy and the death of the enterprise.
Diversi¢cation enables a ¢rm to spread risks by o¡ering a degree of insurance
against unexpected changes in any one market for any one product. A market shock a¡ecting a single product will have greater impact on a specialist ¢rm’s pro¢ts than those of a diversi¢ed one. For example, the demand for air travel has been adversely a¡ected by unexpected shocks, such as the invasion of Kuwait by Iraq in 1991 or the events of 9-11 in the USA. A given fall in sales may have a bigger proportionate impact on specialist airlines than a diversi¢ed company with an airline division, leading to losses, retrenchment and, ultimately, bankruptcy.

Common Questions about Computer Graphics

1. What is the need for computer graphics?

Ans.Graphical communication is an old and more popular method of exchanging information than verbal communication and is more convenient when computers are utilized for this purpose.

As the volume of information increases, problem of storage arises. Also, in the 21st century people do not have time to read huge number of pages. This problem was solved by computer graphics. This can be clearly understood with the help of an example where we  wantwe want to present the performance of a factory since 1980. For this, we  requirewe require a number of pages to render this large volume of information related with financial, numerical and statistical information. It will take a lot of time to analyze such a long report. We  canWe can easily represent this data in a pictorial form thus making it simple to understand. Pictures can represent a huge database in the form of bar charts, pie charts, and so on.

Two other prominent applications of graphics are in the field of Computer Aided Design (CAD) and Computer Aided Manufacturing (CAM).  In CAD, graphics techniques are used to produce the drawings of certain parts of a machine from any viewing angle. In CAM computer graphics techniques, one may display the manufacturing layout for a given part and trace the path taken by machine tools for a given manufacturing process

2. Define computer graphics and Interactive computer graphics?

Ans.

Computer graphics can be defined as the use of computers to define, store, manipulate, interrogate, and present pictorial output of the data.

Interactive computer graphics refers to devices and systems that facilitate the man-machine graphic communication.

3. Briefly, narrate the history of graphics hardware technology?

Ans.

In early days, the high cost of the hardware for computer graphics remained the obstacle, which prevented their widespread use. Computers have been getting progressively more inexpensive and it has become a household article these days. The microelectronics revolution and the subsequent reduction in the price of the digital hardware have completely changed the situation. Due to this price reduction, it is now realistic to expect that all computers with graphic display hardware capability will be making extensive use of computer graphics.

The announcement of the IBM personal computer using 16-bit Intel 8088 microprocessor on August 12, 1981, can be regarded as a historic event, which had a profound effect in the world of computers. These computers significantly improved the state of display technology in the world of computers.

The next major change in PC display technology was announced by Apple Company in 1984, when it introduced the Macintosh PC. It was the first PC that did not include a text-based display but provided only a graphic display. The application programs developed for the Macintosh advocated WYSIWYG (What You See Is What You Get) style of interface. This concept has become a basic requirement in the area of desktop publishing (DTP). The PowerPC’s from IBM, Apple, and other vendors created a new standard for DTP computers. With such a development, computer graphics and multimedia has become a necessity for all types of users.

4. How to make graphics processing faster?

Ans.

Video/Graphic processing can be made faster in two ways: by using a graphic co-processor and a graphic accelerator. The graphic co-processor boosts video performance by assuming tasks normally handled by the CPU. An accelerator takes control of graphic task, which are otherwise performed by the CPU. However, an accelerator is not programmable. It is a functioned processor, which caries out specific tasks hard-coded into the chip.

5. What is graphics processor? Why it is needed?

Ans.Graphics processor helps in managing the screen faster with an equivalent software algorithm executed on the CPU. Through the use of these processors certain amount of parallelism can be achieved for executing graphic commands. Several manufacturers of personal computers use a proprietary graphics processor.

6. Name some graphics processors.

Ans.

Some graphics processors are:

n  Intel 82786

n  Texas Instruments 43010

7. Justify the statement “Windows OS is so popular”?

Ans.

The Windows OS is popular because it supports a graphical user interface (GUI), in which users can perform operations with the help of graphical objects such as windows and buttons. Apart from an intuitive GUI, it supports various other features such as support for integrated application environment, multitasking, multimedia, and networking.

8. What are the strengths of UNIX operating system?

Ans.

The Unix operating system has been known and popular as a simple, small, portable, powerful, time-sharing operating system. However, now it has also gained commercial strength. It is still the most portable and configurable of all operating systems. Unix has adopted to the new hardware architecture and application requirements by incorporating new functionalities such as distributed file system, X11 base GUIs, Multi threading, distributability and so on. Unix became quite popular within Bell Labs.

9. What is a pixel?

Ans.

Pixel may be defined as the smallest size object or color spot that can be displayed and addressed on a monitor.

10. Give the different applications of Computer Graphics.

Ans.

Computer graphics is used in every field. Some of the major application areas are:

a.     Building design and construction

b.     Electronic Design

c.     Mechanical Design

d.     Entertainment and Animation

e.     Aerospace industry

f.     Medical Technology

g.     Cartography

h.     Art and Commerce.

11. Name the Computer languages that support Computer Graphics.

Ans.

Some languages that support computer graphics are:

a.     FORTRAN

b.     BASIC

c.     PASCAL

d.         C

12. Why C language is popular for graphics programming?

Ans.

C has become a choice for today’s professionals, developers for graphics programming. C is a structured language and is rich in expressive power and applicable to a wide variety of users. Because of the rich set of graphical functions available, this language helps in designing for graphical applications. The C code is small, fast, portable, and flexible

Computer Graphics

Introduce computer graphics as a revolutionary development in the field of computer sciences. Tell the students that William Fetter invented the term computer graphics in 1960. Explain the term computer graphics followed by the history of computer graphics hardware.

Conduct an open discussion on the applications of computer graphics. You may discuss the applications of computer graphics discussed in the Additional Inputs  sectionInputs section.

Next, discuss operating system support for graphics. Finally, discuss programming language support for graphics.  Inform the students that they will learn to use C programming for creating graphics as a part of this curriculum.

Fractals

Most graphic packages allow you to create simple graphics using lines, polygons, and curves easily. However, these basic tools cannot help you in creating clouds, trees, or for that matter the jazzy patterns in the AVS used in audio software such as Winamp or the latest Windows Media Player. Such real-life or complex patterned graphics are implemented using the concept of fractals.

Fractals are mathematically generated patterns, which are produced by recursive implementation of self-similar pattern at varying scales within itself. For example, fractals can be implemented to create a tree from a small leaf with a tiny stem under it by infinite recursions of the same pattern (mathematical function).

A well-known fractal named after  its inventor, Benoit Mandelbrot, is the Mandelbrot set. Mandelbrot discovered the concept of fractals when he wrote a program to run a mathematical formula (dealing with fractional dimensions such as 1.2 dimes ions) recursively on an IBM computer. The output was a pretty pattern.

Applications of Computer Graphics – Geographical Information Systems (GIS)

GIS is a software system through which you can capture, store, and manipulate geographical information and display it in various forms. Geographical information (spatial data) has always been better understood through pictures rather than numerical data. GIS depicts geographical information pictorially, in the form of maps. Consequently graphics form an inevitable part of GIS.

Applications of Computer Graphics – Computer Aided Design (CAD)

CAD is the use of computers for creating engineering drawings used in various fields such as architecture, and civil engineering. CAD has been a boon for engineers, who can now use graphical tools for CAD, such as AutoCAD, and create, manipulate, and share engineering drawings with ease.

OpenGL

OpenGL is a known and highly used Application Programming Interface (API) for creating 2D and 3D graphics, which has become a de-facto industry standard. It is an easy to use, reliable, and portable graphics development environment, which is compatible with popular programming languages such as C, C++, and Java.

You can download various applications made using OpenGL at its official site, http://www.opengl.org. For example, to download games made in OpenGL visit http://www.opengl.org/applications/windows/games/.

Common Questions About SSL

1. What is SSL? Why do you require SSL?

Ans.SSL or Secure Socket Layer is a protocol that authenticates Web sites to browsers.  It is also used for encrypting communication between browser  and Web servers. To enable SSL, you simply need to install digital certificates or Server ID.

The main role of SSL is to provide security for Web traffic. Security includes confidentiality, message integrity, and authentication. SSL achieves these elements of security through the use of cryptography, digital signatures, and certificates.

2. Explain SSL working.

Ans.SSL has two distinct entities, server and client. The client is the entity that initiates the transaction whereas the server is the entity that responds to the client and negotiates which cipher suites are used for encryption. In SSL, the Web browser is the client and the Web site server is the server. Three protocols lie within SSL, the Handshake protocol, the Record protocol, and the Alert protocol. The client authenticates the server during the Handshake protocol. When the session is initiated and the handshake is complete, the data transfer is encrypted during the Record Protocol phase. If there are any alarms at any point during the session, the alert is attached to the questionable packet and handled according to the Alert protocol.

3. What is XML? Explain in brief.

Ans.

XML is a simple, common format for representing structured information as text. You can create your own tags to define and structure data, and transmit it.  The basic syntax of XML is extremely simple. As with HTML, XML represents information as text using tags to add structure. A tag begins with a name in between angular brackets (<>). In XML, every tag must have a closing tag. An opening tag, closing tag and any content in between are collectively referred to as an element of an XML document. Elements can contain other elements but they must be properly nested. Elements can also contain text or a combination of elements and text.

4. Given an overview about EJBs.

Ans.

Enterprise Java Beans (EJB) is a server-side component that executes specific business logic on a server when invoked by a local or remote client. EJB is actually a framework for writing distributed programs. It involves a standardization agreement that enables a component to run within any application server. The agreement is accomplished by implementing a set of Java interfaces from the EJB API. Note that EJBs are not GUI components.

5. What are the advantages and disadvantages of EJBs.

Ans.

Following are the advantages of EJBs:

n  Many vendor application servers conform to the J2EE  specification allowing you to select a best-of-breed solution.

n  To handle fluctuations in resource demand server-side resources can easily be scaled by adding or removing servers.

n  Application servers provide access to complex services, such as transaction and security management, resource pooling, JNDI (Java Naming and Directory Interface), and component lifecycle management.

Following are the disadvantages of EJBs:

n  EJB has a large and complicated specification.

n  EJBs take time to develop. Also, they are difficult to debug. Occasionally, the bug may not be in your code but in the application server itself.

n  Frequently released newer versions of EJB specifications render application obsolete quickly.

6. Explain entity beans and session beans?

Ans.

An entity bean is an object with the following special properties:

n  It is permanent. It does not get destroyed itself after a program finishes executing.

n  It is network-based. It can be used by any program over a network provided the program is able to access the bean on the networked machine.

n  It is executed remotely. Methods of an entity bean run on a server machine. When you call an entity bean’s method, your program’s thread stops executing and control passes over to the server. When the method returns from the server, the thread resumes execution.

n  It is identified by a primary key. Entity beans must have a primary key. The primary key is unique – each entity bean is uniquely identified by its primary key. For example, an employee entity bean may have Social Security number as primary key. You can only use entity beans when your objects have a unique identifier field or when you add such a field.

Session beans are different from entity beans in that they are not permanent objects. They are not shareable in  general although it is possible to share them using handles. Session beans can be used to distribute and isolate processing tasks. Each session bean can be used to perform a certain task on behalf

of its client. The tasks can be distributed on different machines. Session beans also do not have a primary key. Unlike entity beans, session beans are not primarily meant to be shared or found later.

7. Briefly describe the remote and home interfaces in EJBs?

Ans.A remote interface is the business end of EJB. It is the set of services provided by EJB.

The home interface is the book-keeping interface. It helps clients to create a new instance of an EJB, or to find an existing instance of an EJB. The methods used to find existing EJBs are shown as finder methods. Since session beans are not designed to be shareable, there are no session bean finder methods.

8. What is DTD?

Ans.DTD or Document Type Definitions is a document that contains grammar rules for validating an XML document. It is a schema specification method for XML

Security In Jsp

Introduce security as a major concern for data exchanged over the Internet by giving examples of hacking and misuse of data. Explain SSL to the students.

Shift focus to recent developments in the Internet domain and introduce XML as a revolutionary technology for data description, exchange, and storage. Explain XML in detail using ample examples. Refer to the Focus Areas section to explain XSL and XSLT.

Finally introduce basic EJB concepts to the students. Being an advanced topic, you could ask the students to refer to the following link for more information.

http://www.ejbtut.com/EntityCreate.jsp

The following section provides some extra inputs on the important topics covered in the SG:

Generating SSL Certificate

SSL certificates can be created using Java’s keytool application. This application is installed in JAVA_HOME/bin directory. For generating SSL certificate, perform the following steps. You can view the help and various options available with keytool by executing it without any parameter:

  1. Execute the following command at the command prompt:

%JAVA_HOME%\bin\keytool -genkey -alias alias_name -keyalg RSA \ -keystore keystore_path

where, alias_name is the name of the server and website URL for which this certificate will be used. Keystore path is the directory into which this certificate will be stored.

  1. Answer the following questions asked at the command prompt:

Enter keystore password:  123456

What is your first and last name?

[Unknown]:  na

What is the name of your organizational unit?

[Unknown]:  na

What is the name of your organization?

[Unknown]:  na

What is the name of your City or Locality?

[Unknown]:  na

What is the name of your State or Province?

[Unknown]:  na

What is the two-letter country code for this unit?

[Unknown]:  na

Is CN=na, OU=na, O=na, L=na, ST=na, C=na correct?

[no]:  y

Key password is too short – must be at least 6 characters

Enter key password for <alias_name>

(RETURN if same as keystore password):  123456

After successfully completing the above, SSL certificate will be generated by the name of file specified under keystore_path.

Installing SSL Certificate on Tomcat

The universally accepted SSL port is 443 but Tomcat uses port 8443 for SSL by default. Therefore, for accessing secure channel onto Tomcat use https://localhost:8443.

For installing the SSL certificate on Tomcat, edit server.xml file. This file can be located under CATALINA_HOME/conf directory. Uncomment the following connector element:

After that, edit the keystorefile and keystorepassword attribute for Factory element by navigating to class customizations within server.xml. Set keystorefile to the complete path directing to SSL certificate and set keystorepassword as same as the password used for generating the certificate using keytool.

Introducing XSL and XSLT

XSL is a very important concept in web programming. It is for XML what CSS is for HTML. XSL stands for eXtensible Stylesheet Language. Unlike CSS, XSL does not have any definitions for any particular tag.

XSL is more popularly known as XML Style Sheets. XSL is much more than a style sheet language. It adheres to an XML-like syntax and provides various parsing and selecting capabilities from an XML file using XSL Transformation (XSLT).

Following are some brief examples using XSL:

<?xml version=’1.0′?>

<xsl:stylesheet xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”

version=”1.0″>

<xsl:template match=”speech”>

<p><xsl:apply-templates/></p>

</xsl:template>

<xsl:template match=”attenuated”>

<i><xsl:apply-templates/></i>

</xsl:template>

</xsl:stylesheet>

The following XML can be parsed with above XSL file:

<?xml version=’1.0′?>

<speech>Hello 123 <attenuated>testing</attenuated></speech>

On parsing it will generate the following output:

<?xml version=”1.0″ encoding=”utf-8″?>

<p>Hello 123 <i>testing</i></p>

Multiple XSL files can be used with a single XML file. For example, there can be separate XSLs for generating content for mobile devices. For linking an XSL with an XML, INSERT IGNORE the following element before root:

<?xml-stylesheet type=”text/xsl” href=”url_of_xsl”?>

XSLT is embedded inside the XSL file and has elements for conditions, looping, selection, and so on. Using it, an XML document can be filtered for content for any possible combination. Some of the important elements are of XSLT are:

xsl:for-each: It is used to select all child nodes of a particular node. <xsl:for-each select=”some_node”></xsl:for-each> will loop for all the first level children of some_node. If there are more than one type of children at the same level, output can be sorted by using <xsl:sort select=”sort_by”/>.

xsl:if: It is used with test attribute. When the comparison inside test returns true content, inside xsl:if is followed. It can be used with xsl:for-each to filter out some nodes. For example, <xsl:if test=”boolean”>…</xsl:if>.

xsl:choose: It works as switch-case as in high level programming languages. It is always used with an xsl:when element, which contains the test. xsl:otherwise works as a default case. For example:

<xsl:choose>

<xsl:when test=”one”></xsl:when> (should have at least one occurrence)

<xsl:otherwise></xsl:otherwise> (optional)

</xsl:choose>

Common Questions about Servlet

. What are the several ways of tracking users?

Ans.

The several ways in which you can track users are:

n  Using hidden controls

n  Using cookie

n  Using sessions

n  Using applications

2. Explain in brief how to use hidden controls in a web page? Give an example.

Ans.

Using HTML, hidden controls are an easy way to store data in a Web page. You can store data in a hidden control and then refer to the value of control wherever required. Hidden controls are often used when you submit a form to itself. That is if your form’s ACTION attribute is set to the same page which contains the form. In this case, every time the page loads you have to determine whether it is being loaded afresh or after a submission. For this, you can store a text value such as “DONE” in a hidden control SUBMIT_STATUS, and check for it whenever the page loads. If request.getParameter(SUBMIT_STATUS) returns a NULL value, it means that the form is being loaded afresh.

This logic is demonstrated in the following code:

<html>

<head></head>

<body>

<%

if(request.getParameter(“DONE”)==null)

{

out.println(“You entered your name as:” + getParameter(“name”));

}

else

{

%>

<form action = “this.jsp” method = “POST”>

Enter your name:<input type =”text” name = “name”></input

<input type = “HIDDEN” name = “DONE” value =”submitted”>

<input type = “SUBMIT” value = “SUBMIT”>

</form>

<%

}

%>

</body>

</html>

3. What are the disadvantages of hidden controls?

Ans.

The disadvantages of hidden controls are that they are not secure as any user can access the HTML source and view their value. Consequently, you cannot store crucial information such as passwords in them. In addition, they complicate the code many times.

4. What are cookies? Explain in brief.

Ans.

Cookies are small text strings you store on a user’s computer. Cookies store information for tracking users in  name-value pairs. When you first visit a website it may store a cookie on your computer. Next, when you again visit the site it may read or manipulate the value of the cookie and perform an action based on it. For example, if a site allows you to customize the color of the user interface, it may set the color selected by you in a cookie on your computer and read the color value when next time you request the page of the website. The page can them be displayed in the color stored in the cookie.

5. List down any 6 methods of javax.servlet.http.Cookie class and their functionality.

Ans.

Following are the methods of the Cookie class:

java.lang.String getName(): Returns the name of the cookie

java.lang.String getValue(): Returns the value of the cookie

void setValue(java.lang.String value): Assigns a new value to a cookie after it has been created

void setPath(java.lang.String uri): Sets the path for the cookie by which the browser will send the cookie

void setMaxAge(int expiry): Set the maximum age of the cookie in seconds

int getMaxAge(): Returns the maximum age of the cookie in second

6. List down any 6 methods of HttpServletResponse class and their functionality.

Ans.

Following are the methods of the HttpServletResponse class:

int SC_ACCEPTED: Indicates that a request was accepted for processing but was not completed

int SC_BAD_GATEWAY: Indicates that the HTTP server received an invalid response from a server, when acting as a proxy or gateway

int SC_BAD_REQUEST: Indicates that the request sent by the client was incorrect

int SC_CONFLICT: Indicates that the request cannot be completed because of a conflict with the current state of the resource

int SC_CONTINUE: Indicates that the client can continue

7. Explain in brief how to create a cookie with an example.

Ans.

You can create a cookie by instantiating an object of the Cookie class. For example, to create a cookie name ‘mycookie’, with the value ‘this is the cookie value’, you can use the following code snippet:

Cookie mycookie =  new Cookie(“mycookie”, “this is the cookie value”);

mycookie.setMaxAge(24*60*60);

respone.addCookie(mycookie)//install cookie on browser

The setMaxAge() method sets the time after which the cookie will expire. The response.addCooki() method will install the cookie on the browser.

8. Explain in brief how to read a cookie with an example.

Ans.

You can read a cookie as:

Cookie[] cookies = request.getCookies();

for(int i=0;i<cookie.length;i++)

{

if(cookies[i].getName().equals(“mycookie”))

out.println(“The value is” + cookie[i].getValue());

}

9. What is a session?

Ans.

Sessions let you preserve data between accesses to a Web page by the same user. Unlike cookie, sessions are stored on the server itself in files or databases.

10. Explain in brief how to track a user using Sessions with an example.

Ans.

You can track user using sessions by storing the details of his/her session with the Web site. For example, you store the number of times that a user has visited a page and display it to him on every visit. To track the user using sessions perform the following steps:

  1. Include page directive with the session attribute set to true, at the top of the page, to indicate that a new session has to be started(if one does not already exist).
  2. Check whether a count has already been set before in a session attribute using the getAttribute() method of the Session class.
  3. If the count has not been set, the getAttribute() method will return null. In that case, you can create a new count value. If a value already exists, you can increment it and store the new value in the session object.

The above steps are implemented in the following code:

<%

Integer count = (Integer)session.getAttribute(“visitcount”);

If(count==null)

{count = new Integer(1);

}

else

{

count = new Integer(visitcount.intValue()+1);

}

session.setAttribute(“visitcount”, count);

%>

<body>

You have visited this page <%=count%> times.

</body>

11. What is the difference between Session and Application?

Ans.

A single session allows you to track one user at a time whereas an application enables you to track all JSPs in the same site, regardless of the number of users accessing them.

12. Explain how to track users using SESSIONS, APPLICATIONS, AND JAVABEANS.

Ans.

You can instruct Tomcat to save the JavaBeans in a session object as well as in attributes. You can store JavaBeans in applications as well. You do this with <jsp:useBean> element’s scope attribute, which you can set to one of these value: scope=”page|request|session|application”. The term scope indicates where a data item is visible in your code. The default scope for a bean is page scope, which means the bean exists only for the page scope. However, if you set the scope of a bean to a session, it is stored with the rest of session’s data

Web Application

Start the session by explaining the concept of HTTP-statelessness. Explain why and in what situations it is important to maintain ‘state’ and track users. In this context, identify the various ways in which you can keep track of users in a Web application.

Explain and demonstrate the use of cookies in a Web application. You could refer an example given in Focus Areas section to explain cookies.

Explain and demonstrate the use of sessions in a Web application. Ask the students to compare cookies and sessions. Also, ask them to identify problems with other techniques such as using hidden fields.

Explain the usage of the application object in brief. Refer to the Focus Areas section for explaining advanced concepts.

The following section provides some extra inputs on the important topics covered in the SG:

Understanding Cookies – An Example

Open http://mail.yahoo.com from your computer. Enter your login credentials and select the ‘Remember my ID on this computer’ checkbox. Access your mail account and do not sign out. Now, the next time you log on to the site from the same computer, you will not need to enter your credentials. You will be directly taken to your mail account when you type http://mail.yahoo.com. Next, on Internet Explorer, select Tools->Internet Options->General tab and click the Delete Cookies button. Click OK to delete the cookies and then again click OK to close the Internet Options dialog box. On Netscape Navigator, the same action can be performed by selecting Tools->Cookie Manager->Manage Stored Cookies and then clicking the Remove All Cookies button in the dialog box that opens.

After you have deleted cookies, again open http://mail.yahoo.com in a new browser window. You will be taken to the login page.

Sharing the Same Cookie with Multiple Servers

Many Web sites today work on more than one server using subdomains such as a.web.com for some feature and b.web.com for some other feature. One of the best examples of this usage is yahoo.com that offers various services through subdomains.

Cookies by default are returned only to the server, which has set them. But sometimes, it becomes mandatory to share the same cookie information among different servers. This is particularly required in  e-commerce sites, which host their shopping cart server separately for security.

Servlets allow same cookie to be shared by multiple servers through the setDomain( pattern ) method under the Cookie class as demonstrated in the following code snippet:

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

{

res.setContentType(“text/plain”);

PrintWriter out = res.getWriter();

if( userValidated( req ) ) //if user is valid — just a place holder for e.g.

{

Cookie key = new Cookie( “valid”, “true” );

key.setDomain( “.web.com” ); //return cookie for all subdomains of web.com

res.setCookie( key );

}

else

{

res.sendError( HttpServletResponse.SC_UNAUTHORIZED );

}

}

Limiting Cookie Access

By default, a cookie is retuned to all the pages on the server. Sometimes, it is desirable that cookie information is returned only for certain directory and its subdirectory. For this, setPath( uri ) method of the Cookie class can be used. For example, if the URI is set to /example, than the cookie will only be returned for http://servername/example and its subdirectories only.

Secure Cookie

HTTPS is considerably slow as compared to HTTP. All communication over HTTPS is encrypted. This encryption – decryption process requires significant amount of processing power and overhead. For some Web applications, it is desirable that only sensitive information is used over HTTPS and rest of the communication takes place over HTTP. For this purpose, the concept of secure cookies is implemented. These cookies are transferred over HTTPS or SSL irrespective of mode of transfer for other communication between client and server. In servlets, a cookie can be made secure using setSecure( secure ) method of Cookie class.

ServletConfig Usage

ServletConfig class is provided to pass initialization parameters to the servlet. Servlets do not have constructor as they are not allowed to create their objects. However, every servlet can define an init() method, which is called only once in the lifetime of the servlet. Init() is overloaded with a version that takes no arguments (class level initializations can be done) and other, which takes an object of ServletConfig class. The name-value pairs of ServletConfig object are specified in web.xml file of the application.

Most of the times database connection string and resource locations are passed using ServletConfig. The main advantage of this is that if some change is made in the database location, there is no need to recompile the servlets

ServletContext Advanced Usage

ServletContext’s getResourceAsStream( path ) method is a very powerful and useful method, which returns InputStream handle for requested resource. This method has numerous usages such as:

  1. It helps in creating a self-updating application, which picks up new files from a certain predetermined location.
  2. Language files can be stored separately, which can then be loaded by obtaining the user’s locale information and can be used to present the pages in user’s natural language.
  3. It helps in hiding a direct URL of a resource.

Questions About Servlet

1. What are servlets? Explain with an example?

Ans.Servlets are programs that run on a Web server and create Web pages on the fly.  To be a servlet, a class should extend HttpServlet and override doGet or doPost or both methods, depending on whether data is sent by GET or POST. These methods take two arguments, HTTPServletRequest and HttpServletResponse. The HTTPServletRequest has methods that let you find out about incoming information such as FORM data and HTTP request headers. The HttpServletResponse has method that lets you specify the HTTP response line, response headers, and obtain a PrintWriter object, used to send output back to the client. For simple servlets, most of the effort is spent in println statements that generated the desired page. A sample servlet is given below:

package hallo;

import java.io.*;

import javax.servlet.*;

import. Javax.servlet.http.*;

public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOexception {

PrintWriter out = response.getWriter();

Out.println(“Hello World”);

}

}

2. Explain Servlet life cycle.

Ans.

The lifecycle of a servlet consists of the following main stages:

Instantiation: The Web server creates an instance of a servlet. This is based on  a request or a container startup.

Initialization: The Web server creates the instance’s init() method. When the Web server loads a Web application, it also loads the initialization parameters associated with the application. This and the previous step occur only once during the lifetime of a servlet.

Service: This is the third state in the servlet lifecycle. In this state, the servlet’s service() method is called, which generates response. The generation of response involves the following steps:

  1. Setting the content type of the response. The receiving application (browser) uses this information to know how to treat the response data. For example, to generate an HTML output, the content-type is set to “text html”.
  2. The second step is to get PrintWriter object from response. PrintWriter is a class that extends the java.io writer abstract class. In the case of servlets, the Web server constructs the Print Writer object from the java.io. OutputStream object associated with the underlying connection from the client. With TCP/IP  based implementations, Web server usually gets OutputStream object from the socket, uses the object to create the PrintWriter object, and associates with the HttpServletResponse object. As a result, from within the servlet, you will able to write to object stream associated with the network association.

Destroy: This is the final stage in a servlet lifecycle. In this stage, the destroy() method is called before shutting down the servlet.

3. What is the difference between HttpServlet and GenericServlet?

Ans.

GenericServlet is the base class, which is extended by an abstract class HttpServlet.

4. What is the difference between doGet() and doPost().

Ans.

doGet() needs to be overridden when the data is submitted to the server using the GET method whereas the doPost() method needs to be overridden when POST method is used to submit data to the server.

5. Explain the relationship between a servlet, its servlet container and the servlet API.

Ans.

A servlet is a Java program, which runs in a servlet container and is written according to servlet API specification. Servlet API is a set of classes and interfaces, which outlines all necessary operations, restrictions, and behaviour for a servlet. A servlet container is software, which provides network services over which requests, responses are sent. It should provide abstraction in obtaining requests and formatting responses and at least support communication over HTTP. For example, Tomcat is a servlet container.

6. Which two packages implement the Servlet API?

Ans.

The two packages are:

  1. javax.servlet

javax.servlet.http

8. What are the advantages of using servlets to extend server functionality?

Ans.

Following are the advantages of using servlets:

  1. It helps to achieve platform independence.
  2. It provides performance improvement as classes stays in the memory once called.
  3. It is much more secure over traditional server side languages. For example, no problems of memory leakages and buffer overflows are faced in case of servlets.
  4. It uses Java’s multithreading capabilities, which gives it a performance gain.

9. Describe the request handling cycle and the methods invoked on the servlet by the servlet container.

Ans.Following are the operations done on a servlet by servlet container when a servlet is requested:

  1. If servlet instance does not exist in memory, the container:
  2. Loads the servlet class and thus creates its instance
  3. Calls the init() method on the above class and passes ServletConfig as parameter
  4. On any further request service() method of servlet class is called and HttpServletRequest and HttpServletResponse are passed as parameters to it.

10. Which class provides methods of reading the parameters submitted by a client?

Ans.

There is no class for this but HttpServletRequest interface provides methods getParameter(), getParameterValues(), and getParameterMap() for obtaining parameters submitted by client.

11. Which class provides methods of reading the parameters specified in the deployment descriptor file?

Ans.

ServletConfig class provides methods getInitParameter() and getInitParameterNames() for reading parameters specified in deployment descriptor.

12. Which streams are used for sending the contents of the entity-body in the response?

Ans.

ServletOutputStream is used for sending contents in response, if the data is binary. It extends the OutputStream class. Its object is normally obtained by calling HttpServletResponse.getOutputStream.

For sending character data PrintWriter class is used, which extends the Writer class. Its object is obtained by calling the HttpServletResponse.getWriter() method.

13. Outline the main steps in implementing the servlet.

Ans

Following are the steps used in implementing a servlet for HTTP communication:

  1. Import required servlet packages in the class.
  2. Make the class extend HttpServlet.
  3. Override methods doGet(), doPost(), or doService() as required by problem in hand.
  4. Make an entry for the above servlet in deployment descriptor.
  5. Configure any extra options or filters, which are required by the server to function.

14. Explain the semantics of the HTML FORM element.

Ans.The HTML form element represents a form in which users can input data and submit it to the server for processing. The HTML form tag is as follows:

<FORM NAME=”name” ACTION = “action.jsp” METHOD = “POST/GET”>

The name attribute specified the name for a form. The action attribute specified the URL of the document or the name of the file to which the form data is submitted for action and the method attribute specified the HTTP method through which the data is sent to the server.

The action attribute can be a simple static Web page or a servlet. The method can be POST or GET.

A form includes various other <INPUT> elements such as textbox, list, buttons, or checkboxes.

15. Which statements are true.

  1. A web application can have more than web.xml.
  2. The HTTPServlet class implements the ServletConfig interface.
  3. The HTTPServlet class implements the ServletContext interface
  4. In a doHttpServletMethodName( ) method, the request and the response objects can be manipulated in any order.
  5. The servlet configuration can change from request to request.
  6. The servlet context can change from request to request.
  7. The servlet element must occur before the servlet-mapping in an element in web.xml file.

Servlet Life Cycle

The following section provides some additional information from the industry perspective that you can share with the students:

Getting All Request Headers

Many reusable servlet codes especially the ones used for parsing and filtering parameters are made generic. That is, instead of handling or pre-knowing any particular request parameter they are developed to serve a general purpose to be used with all cases. Following servlet code prints all the values for all the request parameters:

Enumeration e = request.getParameterNames();

while ( e.hasMoreElements() )

{

String name = (String)e.nextElement();

String values[] = request.getParameterValues( name );

for( int count = 0; count < values.length; count++ )

{

out.println( count + ” ” + name + ” = ” + value[ count ] );

}

}

One of the possible uses of the above code is in validating a multiple choice question. If user has not selected a value then this can easily be determined by looping though all the request parameters.

Sending Error Codes

HTTP protocol has well-defined set of error codes in 4xx series, which means error generated due to client and 5xx series, which means error generated on server. Many browsers have default page implementations for error codes to provide more information regarding the error to client. Servers also allow customizations. Using these customizations user can be presented with a specific page, on generation of certain well-known error;. One of the most common examples of this is 404 error. It is generated when requested resource is not found. Many Websites takes the user to home page on 404 or presents the user search interface. Using servlet, API sending a particular error code is easy. Although you can pass any number as error code, HttpServletResponse class provides a list of common codes as

constants. For more information, see the documentation of class. Following code sends 401 or UNAUTHORIZED error code if client cannot be validated.

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

res.setContentType(“text/plain”);

PrintWriter out = res.getWriter();

HttpSession check = request.getSession(false);

String auth = check.getAttribute( “Authorize” );

if ( auth == null )

{

res.sendError(res.SC_UNAUTHORIZED);

}

else

{

res.sendRedirect( “some_url” );

}

}

sendError() method can only be used if no content is sent to the client. It content has been sent to the client then invoking sendError will throw and exception

Java server Pages

Introduce Java Server Pages (JSP) as one of the most popular Web technologies. At this stage, describe ASP and explain how it is different from JSP. During this discussion identify benefits of JSP.

Introduce servlets and compare them to JSP. It is essential that students identify the usage and domains of each. Ideally servlets should be taught before JSP.

Explain the anatomy of JSP. Ensure that students clearly understand its execution. Next, explain the elements of JSP and demonstrate their usage with the help of simple programs. Finally, explain the components of JSP. Demonstrate some example programs in JSP as provided in the Focus Areas section.

Ask the students to explore some advanced features and commands of JSP by referring to the following link:

http://www.jsptut.com/Index.html

The following section provides some extra inputs on the important topics covered in the SG:

More About JSP’s Application Object

The application object in JSP can be accessed by any JSP, to enable sharing of information among these JSPs. The objects under application object are accessible across all applications. This object provides access to global properties and also provides methods to access server resources.

For debug purposes, messages can be logged in the server log using this object.

Two important methods of this object are:

getAttribute(String name): Returns the attribute whose name is specified as a parameter of this method.

setAttribute(String name, Object object): Sets the attribute named name to the value specified in object.

getAttributeNames(): Returns the names of all the attributes of the application object.

Note that Application object in JSP is what ServletContext is for servlets.

More About JSP’s Request Object

The Request object retrieves the data values sent by a client with an HTTP request to the server. Some of the important methods of this object are:

getHeader(String name): Returns the HTTP request header as a string.

getQueryString(): Returns the query string (that is the part following ? in the URL).

getMethod(): Returns the HTTP method used to send data to the server (such as GET, PUT, POST).

getParameter(String name): Returns the value of the parameter whose name is specified as its argument. In case the specified parameter does not exist, it returns NULL.

getParameterNames(): Returns the name of all parameters in the HTTP request.

getParameterValues(String name): Returns all values of the parameter whose name is specified as its argument.

More About JSP’s Response Object

The Response object sends the data to the client. Some of the important methods of this object are:

addHeader(String name, String value): Writes /Appends header values (name-value pair) to the header of the HTTP response.

setHeader(String name, String value): Sets a header with the name and value specified as parameters to it. If a header with the same name already exists, the old value is replaced by the new value.

addCookies(Cookie cookie): Adds the cookie specified in its parameter to the response.

Sample Code

The following code demonstrates some of the intrinsic objects in JSP:

<%@ page contentType=”text/html;charset=UTF-8″ %>

<html>

<head><title>Simple JSP page</title></head>

<body>

<%

/*

A user will not be able to access this page directly unless session is validated and request method is POST. Also this code checks for the page from which user has accessed this page. If page is not accessed from the same server or if accessed directly, user will be directed towards failure.jsp

If session is new i.e. not yet sent to client or session does not contain name attribute then the code checks if the request has name attribute. The code also enforces the client to use only POST method therefore if someone tries to access this page as page?name=some_name it wont be valid and user will be redirected to faliure.jsp using pageContext. If request contains a name attribute and method is POST then a session attribute is set by name.

*/

String referer = request.getHeader( “Referer” );

String server_name = (String)application.getAttribute(“SERVER_URL” );

if( referer == null || server_name == null || referer.indexOf( server_name ) == -1 )

{

pageContext.forward( “failure.jsp” );

}

if( session.isNew() || session.getAttribute( “name” ) == null )

{

String name = request.getParameter( “name” );

if( name == null || request.getMethod().equalsIgnoreCase(

“Get”) )

{

pageContext.forward( “failure.jsp” );

}

else

{

session.setAttribute( “name”, name );

}

}

/**

* access valid

*/

out.println( “Welcome ” + session.getAttribute( “name” )  );

%>

</body>

</html>

Corresponding HTML for the above code

<html>

<head>

<title>Enter Your Name</title>

</head>

<body>

<form method=”post” action=”Implicit.jsp”>

<input type=”text”><br>

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

</form>

</body>

</html>

Including Plug-ins in JSP

You can embed a Java applet at desired position in the browser window using jsp:plugin tag, which will be translated to <object> tag. In case the browser does not support applets, text in jsp:fallback will be displayed.

<html>

<title> Plugin example </title>

<body>

<jsp:plugin type=”applet” code=”app.class” codebase=”code_base” width=”160″ height=”150″ >

<jsp:fallback>

Plugin tag OBJECT or EMBED not supported.

</jsp:fallback>

</jsp:plugin>

</body>

</html>

Web Server

Recall the brief introduction to Web and application servers from session one of this module. Explain in detail what a Web server and an application server are and differentiate between them. Explain how Web servers work. Explain some important HTTP headers referring to the Focus Areas section. Also, enumerate some of the popular application servers given in the Focus Areas section.Explain the deployment process of a Web application on the Tomcat server in detail.

Some of the commonly used important headers include:

Connection: It is used to specify connection type such as secure channel.  It is also used to specify content, which must not be propagated through proxies.

Pragma: It is used for specifying implementation specific values.

Upgrade: It is used by browser to inform the server about the additional protocols it can support. The server uses it to tell the browser of any switches.

Referer: It enables the browser to send the URL of the page from which the current resource was accessed.

Retry-After: When a particular server is unavailable, it is used to inform the client the time period after which it should send the request again.

Content Encoding: Used to specify by which scheme, transmitted content is compressed.

For information on other headers, refer to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html and http://www.cs.tut.fi/~jkorpela/http.html.

Java Web servers are considered the most powerful and popular by various industry experts. Following is a list for some of the famous J2EE servers with their support technologies and URLs:

Server Name Supported Technologies Website
JRun J2EE, JMS, Servlets, JSP http://www.macromedia.com/software/jrun/
WebLogic J2EE, WAP, JMS http://www.bea.com/framework.jsp?CNT=index.htm&FP=/content/products/Weblogic/server/
JBoss EJB, SOAP, JMX http://www.jboss.com/products/jbossas
IBM WebSphere J2EE, WAP, SOAP, UDDI, WSDL http://www?306.ibm.com/software/Webservers/appserv/express/
Sun ONE Web Server Sun ONE server is a specialized server which can work as a single deployment platform for number of technologies like ASP, CGI, PHP apart from servlets and JSP http://www.sun.com/software/products/Web_srvr/home_Web_srvr.xml

MIME

MIME stands for Multipurpose Internet Mail Extensions. MIME is a standard, which defines the type of files shared/transmitted over the Internet, and the program that will be used to view or process that file. MIME type is an integral part of any Web application programming as it is specified in the headers of a Web page as the Content-Type HTTP header.

MIME type is specified as type/sub type. Examples of MIME types for different categories of content are listed below:

Text:

  • text/plain
  • text/html
  • text/richtext

Image:

  • image/gif
  • image/jpeg
  • image/tiff

Multipart:

  • multipart/mixed
  • multipart/encrypted
  • multipart/x-zip

Application:

  • application/excel
  • application/pdf
  • application/word

Message:

  • message/news
  • message/http
  • message/external-body

Audio:

  • audio/x-wav
  • audio/x-aiff
  • audio/x-midi

Video:

  • video/mpeg
  • video/quicktime
  • video/x-msvideo

Common Graphics Interface

Introduce the concept of CGI referring to the concept of Web applications as discussed in the first session of this module. Tell the students that e-mail Websites, online-shopping Websites, astrological Websites are nothing but applications residing on a server that are executed over a network from a remote client instead of actually executing them on the local machine. In this context, detail CGI as a standard. Tell students that CGI can be implemented with scripting as well as compiled languages. Introduce the various applications that can be developed using CGI. Finally, explain and demonstrate CGI programming using PERL.

Additional Inputs

The following section provides some extra inputs on the important topics covered in the SG:

Parts of a URL

It is essential to understand the various parts of a URL before you actually start programming for the Web. The following figure shows parts of a URL

Understanding the CGI Application Execution

The steps for executing CGI application are explained here:

  1. A user enters a URL in a browser or clicks a link to send a request.
  2. The browser decodes the domain name part of the URL and contacts the server using the specified protocol in the URL.
  3. The server translates the URL into a path a file name. The server identifies the requested file to be an executable program.
  4. The server launches the script of the program.
  5. The script executes, reading the environmental variables in the standard input.
  6. The script sends the MIME headers to STDOUT for the content that has is the output.
  7. The script sends the output to STDOUT and terminates.
  8. The server closes the connection with the client.
  9. The browser displays the output.

Introduction to PERL Regular Expressions

Most of the data submitted through forms in Web applications is in the form of strings. Extensive string matching is often required to validate and process the data. PERL offers a string support for string matching through regular expressions. A basic introduction to regular expressions in PERL is given in this section.

To use regular expressions, you need to:

  1. Create a regular expression.
  2. Perform an operation on it such as, comparison, selection or substitution. For example, comparison is done using the =~ operator as $str =~ $regexp, where $ str is a string and $regex is a regular expression.

Simply a regular expression can be a single string. Practically, regular expressions are patterns of characters sets. To create these regular expressions, you can use meta characters, wildcards, and character set representations.

Following are the commonly used meta characters that can be used to create regular expressions in PERL

^: Represents beginning of a string

$: Represents end of a string

.: Represents any character except new line

*: Indicates matching zero or more times

+: Indicates matching one or more times

?: Indicates matching zero or one time

[ ]: Represents a character set

{}: Represents a repetition modifier

Given here are a few examples:

  1. To find whether a string input by the user begins with “ID” or not, you can create a regular expression ^ID. You can compare user input stored in any variable with this expression as:

$user_input =~ m/^ID/;

  1. To find out whether the user input has string ID at the beginning or at the end:

$user_input =~ m/^ID|ID$/;

Note that the | symbol is used to indicate the OR operation.

3.1. To find whether the user input has a string containing ID following by any number of 0s and then a number 5656:

$user_input =~m/^ID0*5656/;

Apart from Meta characters you can use wildcards also. The commonly used wildcards include:

*: Match 0 or more times

+: Match 1 or more times

?: Match 0 or 1 times

{n}: Match exactly n times

{n,}: Match at least n times

{n,m}: Match at least n but not more than m times

To match a string, which begins with any number of a’s has at least one b following it and then has 0 or 1 occurrence of c, you can use:

$str =~ m/a*b+c?/;

For example, the above statement will return true for abc, aabbbbbbc, abbbb, and b but false for ac or aaaac.

Another important element of creating regular expressions is grouping. () brackets can be used to define groups. Consider following examples

$str = m/^(th)+e*/;

Above statement will return true if it finds a match for a word which starts with ‘th’ and has e zero or more times. Therefore, any sentence starting with th, such as the, thee will return true.

Apart from grouping, another important element is character classes represented by [ ]. Character classes are used as shorthand for describing range. For example, [a-z] defines all lowercase alphabets. One important difference between () and [] is that a pattern defined in () is used as is but in [] it is used as individual Ors. That is (abc) will match abc but [abc] is equivalent to a or b or c and will match any of them. That is [] has only one character inside it, with its various possibilities listed – it does not have a string comprising of the possibilities.

Apart from comparison you can also perform other string operations. To give the students an introduction to these refer to:

http://www.troubleshooters.com/codecorn/littperl/perlreg.htm#StringSelections

http://www.troubleshooters.com/codecorn/littperl/perlreg.htm#DoingSubstitutions

http://www.troubleshooters.com/codecorn/littperl/perlreg.htm#DoingTranslations

FAQ about scripting server

1. Can JavaScript be run on the server?

Ans:

Many Web servers support JavaScript as a server side scripting language. In this case, JavaScript can be executed on the server and not on client’s browser. JavaScript (Jscript under IIS) is allowed to access server resources. If server side JavaScript is embedded in an HTML page then following tag definition should be used.

<script language=”JavaScript” runat=”server”>

</script>

2. How can you declare array in JavaScript?

Ans:

JavaScript has built in Array object, there are two ways for declaring an array:

  1. var arr = new Array( array_length );

arr[ 0 ] = “one”;

….

Arr[array_length - 1 ] = “somevalue”;

  1. var arr = new Array( “one”, “two”, “three” );

3. How can client’s system date be obtained using JavaScript?

Ans:

JavaScript has built in Date object for this. Following code will print current system date as dd/mm/yyyy

<script type=”JavaScript”>

var d = new Date()

document.write(d.getDate())

document.write(“/”)

document.write(d.getMonth() + 1)

document.write(“/”)

document.write(d.getFullYear())

</script>

4. How can you open a new browser window?

Ans:

You can open a new browser window using the window.open(url, window name, attributes) method of JavaScript. Note that you can also open a hyperlink in a new window simply using HTML as:

<a href =www.yahoo.com target=”_blank”>

5. Using JavaScript how can you determine client’s browser name and version?

Ans:JavaScript has navigator object to reference browser’s property. Browser’s name can be obtained using navigator.appName and its version can be obtained using navigator.appVersion.

general question about graphics

1. What is Web? What is the difference between Internet and Intranet?

Ans.A Web is a complex network of international, cross platform, and cross cultural communicating devices, connected to each other without any ordering or pattern.

Internet and Intranet are both networks. However, the Internet is a network of networks, involving all communicating devices over the Web. However, an Intranet is limited to the users, machines, and software programs of a specific organization.

2. Explain GET and POST briefly?

Ans.The GET and POST methods are used to send an HTTP request to the Web server. The GET method is used to request a document from the server. For example:

Get /Webdocs/index.html CRLF

The POST method allows Web browsers to send an unlimited amount of data to a Web server by allowing them to tag it on to HTTP request headers as the message body.

3. Explain how HTTP is used in client/server system.

Ans.HTTP is a request-response type protocol that specifies that a client will open a connection to a server and then send a request using a specific format. In the client server system, the client connects to and sends a request to a server using HTTP. The server then receives and parses the request of the client to send back the requested resource using HTTP again. For sending the response, the server software accesses the server hardware and retrieves the requested document.

4. Discuss the difference between static and dynamic Web pages?

Ans.Static Web pages are not processed by the server and are sent as it is. These pages do not have any scripting logic and they cannot change according to client’s request parameters. Dynamic Web pages are processed by the server and then the generated content is sent to the client. They may involve information from a database or some other information such as client’s user name.

5. “HTML is the language of the Web”. Explain.

Ans.

HTML is a markup language in which Web pages are defined. It is simplistic so that everyone can use it. It is truly the language of the Web. Browsers treat all content given to them as HTML. Also, most of the information on the Internet is in the HTML format. Servers generate the HTML content from the server side scripts and send it to the browsers.

6. Why do we require JavaScript and DHTML?

Ans.JavaScript and DHTML make Web pages more interactive. HTML can be used to only present information. It cannot process data and is therefore not interactive

JavaScript can be used to write programs for creating interactive Web pages. For example, if a user leaves out a field in an online form, JavaScript can be used to prompt the user to enter a value in that field.

DHTML can be used to make the pages more interactive by allowing you set properties of Web pages and their look and feel.

7. Brief about role played by CGI programming in Web programming?

Ans.CGI opened the gates of more complex Web applications. It enabled developers to write scripts, which can communicate with server applications and databases. In addition, it enables developers to write scripts that could also parse client’s input, process it, and present it in a user friendly way.

General questions about Scripting Server

1. What is Java Script? List out uses of Java Script.?

Ans.

JavaScript is a scripting language used to make interactive web pages. It is mostly used as a client side scripting language. Its uses include:

n  Control document appearance and content

n  Control the browser

n  Interact with document content

n  Interact with user

n  Read and write client state with cookies

n  Interact with applets

n  Manipulate embedded images

2. Create an HTML page, which pops up an alert message.

Ans.

Following HTML pops up an alert message:

<html>

<head>

<title>Pop up</title>

</head>

<body>

<h1>Trying Pop-ups</h1>

<script language = “JavaScript”>

alert(“This is an alert message. It uses alert() in JavaScript”);

</script>

</body>

</html>

3. Explain briefly about Cascading Style Sheets (CSS).

Ans.

CSS controls the look and placement of elements on a page. With CSS you can set any style property of any element on a HTML page. One of the biggest advantages with CSS instead of regular way of changing the look of elements is that you can split content from design. You can, for instance, link a CSS file to all the pages in your site that sets the look of the pages. So if you want to change the elements on the page, such as font size of the main text, you can just change it in the CSS and all the pages will be updated.

The syntax of CSS code is:

<style type =”text/css”>

ELEMENT [{property1:value1:property2:value2}]

</style>

Note that the style tag is always placed in the head of the document.

4. Explain the uses of script tags.

Ans.

The script tag marks the beginning and end of JavaScript in a web page. You can specify the scripting language in the script tags’ Language attribute. In addition, you can also specify where the script is expected to run using the runat attribute. For example, when JavaScript is used as a server side scripting language, you can use the script tag as:

<SCRIPT Language = “JavaScript” runat = “server”>

</SCRIPT>

5. Explain Document Object Model.

Ans.

The Document Object Model or DOM is the interface that allows you to programmatically access and manipulate content of a web page. It provides a structured, object-oriented, representation of the individual elements and content in a page with methods for retrieving and setting the properties of those objects. It also provides methods for adding and removing such objects, allowing you to create dynamic content.

The DOM also provides an interface for dealing with events, allowing you to capture and respond to user and browser actions.

6. Write a program to display text in status bar on click of a button.

Ans.

<html>

<head>

<title>Pop up</title>

</head>

<body onclick = “window.status = ‘You have clicked!!!’”>

<h1>Changing Status Bar Text</h1>

</body>

</html>

7. What is the difference between HTML and DHTML?

Ans.

HTML is a markup language used to create static web pages. DHTML on the other hand is not a language by itself but a combination of different technologies such as HTML, CSS, JavaScript, and DOM. It is used to create dynamic pages.

8. Explain the methods to access nodes in a Document tree.

Ans.

Following are the methods used to access a node in a document tree:

document.getElementById(): Returns the element or node whose ID is passed as a parameter to it.

document.getElementsByTagName(): Returns the list of nodes that have the tag passed to the function as a parameter.

9. What are text nodes?

Ans.If a node contains text, it is represented as a text node. For example, in<p id-node2>”This is the <b>initial</b>text.</p>, there are text nodes “This is the”, “initial”, and “text”.