Sei sulla pagina 1di 0

Publishedbywww.myignou.

in
Visitourwebsitetodownloadmoresolvedassignments.

Uploadedby : PankajSethi
Call : 9781453353
Email : sethi_pankaj@yahoo.in
CourseCode : BCS53
CourseTitle : WebProgramming
AssignmentNumber : BCA(V)053Assign/1314
MaximumMarks : 100
Weightage : 25%
LastDateofSubmission : 15thOctober,2013/15thApril,2014

Thisassignmenthastwoquestionsof80marksRest20marksareforvivavoce.
Question1:(CoversBlock1) (104=40Marks)

a) WhatarethefeaturesofWeb2.0technologies?WhydoyouneedtouseCSS?Createawebpage
forBCA.Thewebpageshouldhavevarioussections(use<div>tagforthispurpose),eachsection
shouldprovidedetailedlistofcoursesofonesemesterofBCAEachofthesectionshouldhaveits
ownstyle.
b) WhatisXML?WhyisitneededeventhoughyouhaveHTML?Createatleastfiveinstancesofyour
friends data using a XML page. The list can contain name and date of birth of the friend. In
addition, each friend will have at least one phone number and address. Create the DTD for the
XMLdocumentyouhavecreated.
c) Explain the concept of Document Object Model in the context of JavaScript. Explain how events
arehandledusingJavaScript.WriteaprogramusingJavaScriptthatdisplaysthecurrenttimeona
webpageandincrementsitafterevery10seconds.
d) What are WAP and WML? Explain with the help of an example. Explain the process of creating a
webpageforamobiledevicealongwithanexample.

Answer1:
(A)Web2.0describeswebsitesthatusetechnologybeyondthestaticpagesofearlierwebsites.Theterm
wascoinedin1999byDarcyDiNucciandwaspopularizedbyTimO'ReillyattheO'ReillyMediaWeb2.0
conferenceinlate2004.AlthoughWeb2.0suggestsanewversionoftheWorldWideWeb,itdoesnotreferto
anupdatetoanytechnicalspecification,butrathertocumulativechangesinthewaywebpagesaremadeand
used.
AWeb2.0sitemayallowuserstointeractandcollaboratewitheachotherinasocialmediadialogueas
creatorsofusergeneratedcontentinavirtualcommunity,incontrasttowebsiteswherepeoplearelimitedto
thepassiveviewingofcontent.ExamplesofWeb2.0includesocialnetworking
sites,blogs,wikis,folksonomies,videosharingsites,hostedservices,webapplications,andmashups.
ThekeyfeaturesofWeb2.0include:
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

1. Folksonomy; free classification of information


2. A rich user experience
3. A user as a contributor
4. Long tail
5. User participation
6. Basic trust
7. Dispersion
8. Mass participation

WhatisCSS?
CSS(CascadingStyleSheets)wasoneoftheW3C's(W3Consortiumistheorganizationwhichprovides
standardsforweborientedprogrammingandscripting)mostprimitiveeffortsatuntyingtheformattingand
styleapplyingdetailsfromdocumentstructureinHTML.Thispersistentsubjecthasbeenattheheartofmost
W3CHTMLactivitysinceHTML4.0'slaunch,andCSSisacriticalfactorinexecutingthatproject.

RoleofCSSinwebdesigning:
ByprovidingasimplesetoftoolsthatimplementmuchmorethoroughcontroloverpresentationthanHTML
itself,CSSwassupposedtoattractwebdevelopersawayfromthemillionsofFONTtagsusedinHTML
documents.HTML4.0's(andXHTML's)criticismoftheFONTelementisthestick.CSSprovidestheweb
documentdesignersanumberofkeyaspectsthatarenearlyimpossibletoimplementeffectivelywithstraight
HTML(eveniftheFONTelementisused).

FeaturesandAdvantagesofCSS:
1.
CSSprovidesreusability.Theformattingdescriptionsappliedtodocumentscanbeappliedtoany
documentwiththesamevocabulary.
2. CSSevenletsyoucreatestylesheetsthataddressparticularsituationswithinagivenvocabulary,
specifyingthepagedesignandlayoutbasedonnestedelementstructuresorattributevalues.Youcan
maketensofthousandsofHTMLdocumentsusethesameformattingjustbyconnectingonelineof
codeineachdocumenttothesameCSSstylesheet.Thisalsomakesiteasytochangeformatting
acrossallofthosedocumentsbecausechangesmadetothemasterstylesheetarereplicatedinallthe
documentsthatuseit.
3. Organizationappearanceofthewebdocumentismuchstraightforwardasittakesjustaadjustment
orchangeinastylesheetratherthanaexploreandsubstitutemethodorfindandreplacestrategy
acrossthousandsofdocuments.

Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

Aspectstobuildafinestylesheet:

1. Keep your style sheet documents in a safe place! Any time your documents refer to a central style sheet,
you can use that resource to modify the presentation for all your documents. It makes it easier for you to
make the changes, but invaders possibly could alter the style sheet to graffiti your documents.

2. Although a single master style sheet for a site is smart and attractive, sometimes you need to change a
presentation for a particular unit of a website, a certain document, or even a certain element in the
document.

3. The "cascade" in Cascading Style Sheets enables you to handle this problem easily without requiring
constant cut-and-paste to make personalized style sheets.

4. Style sheets and documents can refer to multiple style sheets, and CSS provides a set of rules and
protocols for determining where to use each style.

5. HTML and XHTML provide extra features like the class and style attributes called as hooks, for connecting
style-based formatting to particular elements.

6. Cascading Style Sheets also enables designers to get out of the complex dealing of formatting HTML
generated by server-side program codes. Rather than having to edit templates packed with programming
code, web designers can agree with programmers on what the output of those programs should look like
and then design style sheets to match without getting directly involved in the code.

7. On the client side, CSS makes it simple to reach into the formatting created by web document designers
and change it when apt; thus, there is no need to make styling particularly for a page.

8. Designers and programmers sometimes have to work closely together in both client- and server-side
development.

9. CSS makes it easy to divide tasks cleanly. CSS offers methods that enable users to state how content
should be formatted and designed. Combined with the importance on user-friendliness and accessibility
which has influenced much of the CSS process, this enables users to access information in a format that's
comfortable and convenient for them.

(B)

XML is a text-based markup language that is fast becoming the standard for data interchange on the web. As with HTML,
you identify data using tags (identifiers enclosed in angle brackets: <. . . >). Collectively, the tags are known as markup.
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents
in a format that is both human-readable and machine-readable. It is defined in the XML 1.0
Specification produced by the W3C, and several other related specifications, all freeopen standards.
The design goals of XML emphasize simplicity, generality, and usability over the Internet. It is a textual data
format with strong support via Unicodefor the languages of the world. Although the design of XML focuses on
documents, it is widely used for the representation of arbitrary data structures, for example in web services.
Many application programming interfaces (APIs) have been developed to aid software developers with
processing XML data, and several schema systems exist to aid in the definition of XML-based languages.
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.


The Difference Between XML and HTML
XML is not a replacement for HTML.
XML and HTML were designed with different goals:
XML was designed to transport and store data, with focus on what data is
HTML was designed to display data, with focus on how data looks
HTML is about displaying information, while XML is about carrying information.
Friends.xml
<?xmlversion="1.0"?>
<!DOCTYPEFriendDataSYSTEMFrnd.Xml>
<FriendData>
<Friend>
<FriendName>Amit</FriendName>
<Dob>3/5/1990</Dob>
<Address>Delhi</Delhi>
<PhoneNo>9834132325</PhoneNo>
</Friend>
<Friend>
<FriendName>Ankur</FriendName>
<Dob>12/7/1991</Dob>
<Address>Delhi</Delhi>
<PhoneNo>989113322</PhoneNo>
</Friend>
<Friend>
<FriendName>Neha</FriendName>
<Dob>21/9/1991</Dob>
<Address>Noida</Delhi>
<PhoneNo>9999123521</PhoneNo>
</Friend>
<Friend>
<FriendName>Rohit</FriendName>
<Dob>6/7/1992</Dob>
<Address>Delhi</Delhi>
<PhoneNo>9834132325</PhoneNo>
</Friend>
<Friend>
<FriendName>Pooja</FriendName>
<Dob>12/1/1992</Dob>
<Address>Delhi</Delhi>
<PhoneNo>9990765231</PhoneNo>
</Friend>
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

</Friend-Data>

Frnd.Xml

<!ELEMENTFriendData(Friend+)>
<!ELEMENTFriend(FriendName,Dob,Address,PhoneNo)>
<!ELEMENTFriendName(#PCDATA)>
<!ELEMENTDob(#PCDATA)>
<!ELEMENTAddress(#PCDATA)>
<!ELEMENTPhoneNo(#PCDATA)>

(C)
A Document object represents the HTML document that is displayed in that window. The Document object has
various properties that refer to other objects which allow access to and modification of document content.
The way that document content is accessed and modified is called the Document Object Model, or DOM. The
Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web
document.
Window object: Top of the hierarchy. It is the outmost element of the object hierarchy.
Document object: Each HTML document that gets loaded into a window becomes a document object.
The document contains the content of the page.
Form object: Everything enclosed in the <form>...</form> tags sets the form object.
Form control elements: The form object contains all the elements defined for that object such as text
fields, buttons, radio buttons, and checkboxes.
Here is a simple hierarchy of few important objects:

There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how
you can use them to access and modify document content.
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

The Legacy DOM: This is the model which was introduced in early versions of JavaScript language. It is
well supported by all browsers, but allows access only to certain key portions of documents, such as
forms, form elements, and images.
The W3C DOM: This document object model allows access and modification of all document content and is
standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the
modern browsers.
The IE4 DOM: This document object model was introduced in Version 4 of Microsoft's Internet Explorer
browser. IE 5 and later versions include support for most basic W3C DOM features.

What are events?


Events occur when some sort of interaction takes place in a web page. This can be the end user
clicking on something, moving the mouse over a certain element or pressing down certain keys
on the keyboard. An event can also be something that happens in the web browser, such as the
web page completing the loading of a page, or the user scrolling or resizing the window.
Through the use of JavaScript, you can detect when certain events happen, and cause things to
occur in response to those events.
How events work
When events happen to an HTML element in a web page, it checks to see if any event handlers
are attached to it. If the answer is yes, it calls them in respective order, while sending along
references and further information for each event that occurred. The event handlers then act
upon the event.
There are two types of event order: event capturing and event bubbling.
Event capturing starts with the outer most element in the DOM and works inwards to the
HTML element the event took place on and then out again. For example, a click in a web page
would first check the HTML element for onclick event handlers, then the body element, and so
on, until it reaches the target of the event.
Event bubbling works in exactly the opposite manner: it begins by checking the target of the
event for any attached event handlers, then bubbles up through each respective parent element
until it reaches the HTML element.
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
oncl i ck=JavaScript
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

When an input field is changed


When an HTML form is submitted
When a user strokes a key

PROGRAM
<script type="text/javascript">
function DisplayTime(){
if (!document.all && !document.getElementById)
return
timeElement=document.getElementById? document.getElementById("curTime"):
document.all.tick2
var CurrentDate=new Date()
var hours=CurrentDate.getHours()
var minutes=CurrentDate.getMinutes()
var seconds=CurrentDate.getSeconds()
var DayNight="PM"
if (hours<12) DayNight="AM";
if (hours>12) hours=hours-12;
if (hours==0) hours=12;
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
timeElement.innerHTML="<font style='font-family:verdana, arial,tahoma;font-
size:12px;color:#E25984; font-weight:bold;'>"+currentTime+"</b>"
setTimeout("DisplayTime()",10000)
}
window.onload=DisplayTime
</script>

(D)
WAP is the de facto worldwide standard for providing Internet communications and advanced telephony services
on digital mobile phones, pagers, personal digital assistants and other wireless terminals - WAP Forum
WAP stands for Wireless Application Protocol. Per the dictionary definition for each of these words, we have:
Wireless: Lacking or not requiring a wire or wires: pertaining to radio transmission.
Application: A computer program or piece of computer software that is designed to do a specific task.
Protocol: A set of technical rules about how information should be transmitted and received using
computers.
WAP is the set of rules governing the transmission and reception of data by computer applications on, or via,
wireless devices like mobile phones. WAP allows wireless devices to view specifically designed pages from the
Internet, using only plain text and very simple black-and-white pictures.
WAP is a standardized technology for cross-platform, distributed computing, very similar to the Internet's
combination of Hypertext Markup Language (HTML) and Hypertext Transfer Protocol (HTTP), except that it is
optimized for:
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

low-display capability
low-memory
low-bandwidth devices, such as personal digital assistants (PDAs), wireless phones, and pagers.
WAP is designed to scale across a broad range of wireless networks, like GSM, IS-95, IS-136 and PDC.
WML(WirelessMarkupLanguage),formerlycalledHDML(HandheldDevicesMarkupLanguages),
isalanguagethatallowsthetextportionsofWebpagestobepresentedoncellular
telephonesandpersonaldigitalassistants(PDAs)viawirelessaccess.WMLispartoftheWireless
ApplicationProtocol(WAP)thatisbeingproposedbyseveralvendorstostandardsbodies.The
WirelessApplicationProtocolworksontopofstandarddatalinkprotocols,suchasGlobal
SystemforMobilecommunication,codedivisionmultipleaccess,andTimeDivisionMultiple
Access,andprovidesacompletesetofnetworkcommunicationprogramscomparabletoand
supportiveoftheInternetsetofprotocols.
WML is an application of XML, which is defined in a document-type definition.
WML is based on HDML and is modified so that it can be compared with HTML.
WML takes care of the small screen and the low bandwidth of transmission.
WML is the markup language defined in the WAP specification.
WAP sites are written in WML, while web sites are written in HTML.
WML is very similar to HTML. Both of them use tags and are written in plain text format.
WML supports client-side scripting. The scripting language supported is called WMLScript.
ToCreateawebpageformobile:
LAYOUT
LOGO:
One of the main things in the layout. You should try to make it as attractive as you can
but at the same time take care of its size. Make sure that the size doesnt exceed 2 KBs
of size because images always take forever to load on mobile networks and you dont
want your site to load incompletely for different people!
WEBSITE NAVIGATION:
One of the most important things in the design. No matter what, you need to have the
links to main pages/places/things on your website on this bar and this should always be
at the top. As you know, typing on most mobile devices using the small QWERTY or the
virtual QWERTY keypads is not easy to work with at all. Therefore, creating a thorough
navigation for your website is a key aspect to making your website mobile friendly.
CONTENT:
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

This is the main thing on your mobile website. People actually come to websites on their
mobile devices just to view the content. So make sure that you dont make any single
change to your content for mobile devices otherwise you might just end up losing a user.
While on Mobile Devices, people are usually on the go, so they dont really have much
time to view content. As a solution to this, you should cut down your content to some
major value points but at the same time you should provide your user with a Link to the
main article containing all of your content. (If you have an active blog then you can ignore
this as you cant really cut down content for each post separately every day!!)
We all know that images in content are a must. But in the mobile version of your website,
you should make sure that you dont have much graphics because most mobile phones
would take forever to load heavy images. So use images and graphics as little as
possible, only where contextually relevant.
And if you do wish to put images on your mobile website, it should be in .J PEG or .GIF or
.PNG format as these files are pretty much light-weight. Plus make sure to compress
your pictures to avoid zooming. And one more, today nearly all current devices display
images, however, users may browse with the images turned off. So always use the ALT
text property for the images which is a recommended practice. Also, you must properly
size your images to avoid a situation where the reader/visitor has to zoom into the image
to see it properly.
FOOTER:
Theres an old saying, A Man is not recognized by the clothing hes wearing but by the
condition of his shoes! This goes true for many websites. I always see blogs, marketing
websites etc. OVER-LOADED with garbage and dirty Hyper-links in Footer. Like me,
many others dont like it and on mobile websites where the screen size is small, this
could be one thing where you could lose a client or a reader. So make an attractive
Footer!
So if you want your applications/websites mobile-interface going successful, you should
lay focus on its Layout. It should just be error-free as Web-Browsing on Mobile Devices
will be the next big thing.

Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

CODING
This is one thing where many new mobile-interface developers hesitate. Below are some
tips that can help remove that hesitation:
VALID CODE:
Use proper code and make sure that its 100% valid because most mobile browsers arent
as good as their PC (Personal-Computer) counterparts so you should make sure that its
valid.
FLUID LAYOUTS:
Its not always easy to discover how your layout will look on all mobile browsers as there
are far too many mobile devices used for web browsing and to track them all can be a big
pain. One way to address/bypass this problem is the use fluid layouts that will
automatically adjust to the screen size.
To accomplish this avoid setting widths in pixels and use percentages or ems instead.
For instance, instead of:
1wi dt h: 400px;
use
1wi dt h: 100%
or
1wi dt h: 1. 0ems
You can find more about the fluid mobile layouts and also download some pre-built ones
by going to this link: Perfect multi-column CSS liquid layouts iPhone compatible
SPECIFIC STYLESHEETS
You can always target various mobile devices for better user-experience. For example,
for targeting users browsing your site using Handheld devices you can use this in your
websites<head>:
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

1<l i nkr el =" st yl esheet " hr ef =" handhel d. css" t ype=" t ext / css" medi a=" handhel d" / >
You can find more about these media types at this link: W3.org Media Types.
SAY NO TO FANCY SCRIPTS
For your mobile website to go successful, dont use J avascript or Flash or any other of
those fancy scripts available out there. Because majority of mobile devices fail to interpret
these and end up either freezing the device or just doing something stupid!
If you really want to use these then should give your user a Polite Option so that your
user knows what his/her mobile handset is loading and opening up (and if anything goes
wrong, its their fault and not yours because you already warned them).
TAKE IT EASY WITH THE ADS
This is one thing that almost everyone should take care of! Dont fill up your mobile page
with ads. And this is not only for the mobile page but also for the original website.
Its an old saying, One rotten Apple in a basket makes all others dirty. It goes true for
these websites which are full of ads. These websites dont care about User-Experience
but only care about the money that comes into their pockets (because CPM is high on
mobile devices).
So my suggestion, just dont fill it up with ads! Just dont make your page with colourful
ads.
MOBILE BROWSER DETECTION (AUTOMATIC)
For making your brand successfull you should also include an automatic Mobile Browser
Detection & Redirection server-side script (eg. PHP). You might also use this as User
Agent detection, where a server makes a decision on what to serve based on how an
incoming browser describes its capabilities. You might also want to use this as an
alternative or fallback method to the previous one Mobile Browser Detection in PHP.
Other implementations feature real-time J avaScript requests to databases
like DeviceAtlas or WURFL that also supply information on what a device can do. A
mobile version is not complete until its automatically triggered for every mobile user!
MAKE A DEDICATED APPLICATION CLIENT (if necessary)
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

Yes! You read it correctly. If you have a really high user-base, make a dedicated
application targeting various mobile interfaces. Facebook, Gmail, Twitter, Yahoo and
many other big-companies have done this and this is why they have been so successful.
If you make an application for specific handsets then you no longer have to care about all
the Fancy scripts etc. because you can then enhance the application your own way (you
cant change the mobile browser but definitely your own application).


Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

Question 2: (Covers Block 2) (104=40 Marks)


a) Explain different types of client-server architectures. Explain the GET and POST methods
of HTTP protocol? Why do you use these methods? Explain with the help of an example
each.
b) Create a J SP page that shows use of J SP Directives, Elements, Scriptlets, Expressions and
variables. Create a web page using J SP that stores the number of times a button is clicked
on to the server.
c) What are cookies? Why are they used? How are they different to a session? Create a page
that asks your name and creates a cookie about your name
d) What is J DBC? Why are they used? Create a web site using J SP to verify your login and
password. The site should allow you to register, in case you do not have login name and
password. The username and password must be stored in the database. On successful login,
a welcome page should displayed.

Answer-2:
(A)
Client/server architecture this approach introduced replacement of file server by database server. User
queries could be answered directly by using a relational database management system. The client/server
architecture significantly decreased network traffic by providing a query response rather than total file
transfer. It allows multi-user updating through a GUI front end to a shared database. Remote Procedure
Calls (RPCs) or standard query language (SQL) statements are typically used to communicate between
the client and server.
The following are the examples of client/server architectures.
1) Two tier architectures In two tier client/server architectures, the user interface is placed at user's
desktop environment and the database management system services are usually in a server that is a
more powerful machine that provides services to the many clients. Information processing is split between
the user system interface environment and the database management server environment. The database
management server supports for stored procedures and triggers. Software vendors provide tools to
simplify development of applications for the two tier client/server architecture.
2) Three tier architectures The three tier architecture is introduced to overcome the drawbacks of the two
tier architecture. In the three tier architecture, a middleware is used between the user system interface
client environment and the database management server environment. These middleware are
implemented in a variety of ways such as transaction processing monitors, message servers or application
servers. The middleware perform the function of queuing, application execution and database staging. In
addition the middleware adds scheduling and prioritization for work in progress. The three tier client/server
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

architecture is used to improve performance for large number of users and also improves flexibility when
compared to the two tier approach. The drawback of three tier architectures is that the development
environment is more difficult to use than the development of two tier applications.
i) Three tier with message server. In this architecture, messages are processed and prioritized
asynchronously. Messages have headers that include priority information, address and identification
number. The message server links to the relational DBMS and other data sources. Messaging systems
are alternative for wireless infrastructures.
ii) Three tier with an application server This architecture allows the main body of an application to run on a
shared host rather than in the user system interface client environment. The application server shares
business logic, computations and a data retrieval engine. In this architecture applications are more
scalable and installation costs are less on a single server than maintaining each on a desktop client.
Uses Client/server architectures are used in industry as well as in military. They provide a versatile
architecture that allows insertion of new technology more readily than earlier software designs.

GET
The GET method means retrieve whatever information (in the form of an entity) is
identified by the Request-URI. If the Request-URI refers to a data-producing process, it is
the produced data which shall be returned as the entity in the response and not the source
text of the process, unless that text happens to be the output of the process.
The semantics of the GET method change to a "conditional GET" if the request message
includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-
Range header field. A conditional GET method requests that the entity be transferred only
under the circumstances described by the conditional header field(s). The conditional GET
method is intended to reduce unnecessary network usage by allowing cached entities to be
refreshed without requiring multiple requests or transferring data already held by the client.
The semantics of the GET method change to a "partial GET" if the request message
includes a Range header field. A partial GET requests that only part of the entity be
transferred, as described in section 14.35. The partial GET method is intended to reduce
unnecessary network usage by allowing partially-retrieved entities to be completed without
transferring data already held by the client.
POST
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

The POST method is used to request that the origin server accept the entity enclosed in the
request as a new subordinate of the resource identified by the Request-URI in the Request-
Line. POST is designed to allow a uniform method to cover the following functions:
- Annot at i on of exi st i ng r esour ces;
- Post i ng a message t o a bul l et i n boar d, newsgr oup, mai l i ng l i st ,
or si mi l ar gr oup of ar t i cl es;
- Pr ovi di ng a bl ock of dat a, such as t he r esul t of submi t t i ng a
f or m, t o a dat a- handl i ng pr ocess;
- Ext endi ng a dat abase t hr ough an append oper at i on.
The actual function performed by the POST method is determined by the server and is
usually dependent on the Request-URI. The posted entity is subordinate to that URI in the
same way that a file is subordinate to a directory containing it, a news article is subordinate
to a newsgroup to which it is posted, or a record is subordinate to a database.
The action performed by the POST method might not result in a resource that can be
identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate
response status, depending on whether or not the response includes an entity that describes
the result.
Example
POST / pat h/ scr i pt . cgi HTTP/ 1. 0
Fr om: f r og@j mar shal l . com
User - Agent : HTTPTool / 1. 0
Cont ent - Type: appl i cat i on/ x- www- f or m- ur l encoded
Cont ent - Lengt h: 32

home=Mosby&f avor i t e+f l avor =f l i es

(B)
Program to show use of scripting elements

<%@page language="java" import="java.io.*" %>
<%@page import="javax.servlet.*" %>
<%@page import="javax.servlet.http.*" %>
<%! int a,b,c; %>
<%
a=10;
b=20;
c=a+b;
%>
<%=c%>

Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.


Create a web page using J SP that stores the number of times a button is clicked on to the server

<%!intclicks=0;%>

<%
Stringparam=request.getParameter("integer");

try
{
inti=Integer.parseInt(param);

clicks++;
}
catch(NumberFormatExceptione)
{
}
%>
<p>Numberofclicksuntillnow:<%=clicks%></p>

<formaction="">
<inputtype="text"name="integer"value="1"/>
<inputtype="submit"value="submit"/>
</form>


(C)
Cookies
Web applications are typically a series of Hypertext Transfer Protocol (HTTP) requests and
responses. As HTTP is a stateless protocol, information is not automatically saved between
HTTP requests. Web applications use cookies to store state information on the client.
Cookies can be used to store information about the user, the user's shopping cart, and so
on.
Types of Cookies
The two types of cookies follow:
SessioncookiesSessioncookiesarestoredinmemoryandareaccessibleaslong
astheuserisusingthewebapplication.Sessioncookiesarelostwhentheuser
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.

exitsthewebapplication.SuchcookiesareidentifiedbyasessionIDandaremost
commonlyusedtostoredetailsofashoppingcart.
PermanentcookiesPermanentcookiesareusedtostorelongterminformation
suchasuserpreferencesanduseridentificationinformation.Permanentcookies
arestoredinpersistentstorageandarenotlostwhentheuserexitsthe
application.Permanentcookiesarelostwhentheyexpire.
Difference Between Cookie & Session

The main difference between cookies and sessions is that cookies are stored in the user's browser, and
sessions are not. This difference determines what each is best used for.
A cookie can keep information in the user's browser until deleted. If a person has a login and password, this
can be set as a cookie in their browser so they do not have to re-login to your website every time they visit.
You can store almost anything in a browser cookie. The trouble is that a user can block cookies or delete
them at any time. If, for example, your website's shopping cart utilized cookies, and a person had their
browser set to block them, then they could not shop at your website.
Sessions are not reliant on the user allowing a cookie. They work instead like a token allowing access and
passing information while the user has their browser open. The problem with sessions is that when you close
your browser you also lose the session. So, if you had a site requiring a login, this couldn't be saved as a
session like it could as a cookie, and the user would be forced to re-login every time they visit.

A Webpage that asks your name and creates a cookie about your name

<ht ml >
<head>
<scr i pt t ype=" t ext / j avascr i pt " >
<! - -
f unct i on Wr i t eCooki e( )
{
i f ( document . myf or m. cust omer . val ue == " " ) {
al er t ( " Ent er some val ue! " ) ;
r et ur n;
}

cooki eval ue= escape( document . myf or m. cust omer . val ue) + " ; " ;
document . cooki e=" name=" + cooki eval ue;
al er t ( " Set t i ng Cooki es : " + " name=" + cooki eval ue ) ;
}
/ / - - >
</ scr i pt >
</ head>
<body>
<f or mname=" myf or m" act i on=" " >
Ent er name: <i nput t ype=" t ext " name=" cust omer " / >
<i nput t ype=" but t on" val ue=" Set Cooki e" oncl i ck=" Wr i t eCooki e( ) ; " / >
</ f or m>
</ body>
</ ht ml >
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.



(D)
J DBC stands for Java Database Connectivity, which is a standard J ava API for database-independent connectivity between
the J ava programming language and a wide range of databases.
The J DBC library includes APIs for each of the tasks commonly associated with database usage:
Making a connection to a database
Creating SQL or MySQL statements
Executing that SQL or MySQL queries in the database
Viewing & Modifying the resulting records
Fundamentally, J DBC is a specification that provides a complete set of interfaces that allows for portable access to an
underlying database. J ava can be used to write different types of executables, such as:
J ava Applications
J ava Applets
J ava Servlets
J ava ServerPages (J SPs)
Enterprise J avaBeans (EJ Bs)
All of these different executables are able to use a J DBC driver to access a database and take advantage of the stored data.
J DBC provides the same capabilities as ODBC, allowing J ava programs to contain database-independent code.

login.jsp
<%@page cont ent Type=" t ext / ht ml ; char set =i so- 8859- 1" l anguage=" j ava" %>
<%
String error=r equest . get Par amet er ( " er r or " ) ;
if( error==nul l | | error==" nul l " ) {
error=" " ;
}
%>
<html>
<head>
<title>User Logi n J SP</ title>
<script>
function t r i m( s)
{
return s. replace( / ^s*/ , " " ) . replace( / s*$/ , " " ) ;
}
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.


function val i dat e( )
{
if( t r i m( document . f r mLogi n. sUser Name. val ue) ==" " )
{
al er t ( " Logi n empt y" ) ;
document . f r mLogi n. sUser Name. f ocus( ) ;
return f al se;
}
else if( t r i m( document . f r mLogi n. sPwd. val ue) ==" " )
{
al er t ( " passwor d empt y" ) ;
document . f r mLogi n. sPwd. f ocus( ) ;
return f al se;
}
}
</ script>
</ head>

<body>
<div><%=error%></ div>
<form name=" f r mLogi n" onSubmi t =" r et ur n val i dat e( ) ; " act i on=" doLogi n. j sp"
met hod=" post " >
User Name <input t ype=" t ext " name=" sUser Name" / ><br / >
Passwor d <input t ype=" passwor d" name=" sPwd" / ><br / >
<input t ype=" submi t " name=" sSubmi t " val ue=" Submi t " / >
</ form>
</ body>
</ html>

doLogin.jsp mainly deals with database to check user id and password is matched with user trying to
provide to get access from the server.
Our password field is encrypted with mysql password function. To decrypt password we have to use mysql
password function again. If you are using Oracle or other database password function come with different
name. Only user knows exact password and anybody can find out real password of the user. This increases
the security of the system and reduces the hacking.
doLogin.jsp
<%@page l anguage=" j ava" i mpor t =" j ava. sql . *" er r or Page=" " %>
<%

Connection conn = null;
Class. f or Name( " com. mysql . j dbc. Dr i ver " ) . newI nst ance( ) ;
conn =
DriverManager. get Connect i on( " j dbc: mysql : / / l ocal host : 3306/ dat abase" , " r oot " , " " ) ;
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.


ResultSet r sdoLogi n = null;
PreparedStatement psdoLogi n=null;

String sUser I D=r equest . get Par amet er ( " sUser Name" ) ;
String sPasswor d=r equest . get Par amet er ( " sPwd" ) ;
String message=" User l ogi n successf ul l y " ;

try{
String sql Opt i on=" SELECT * FROM user mast er wher e"
+" sUser I D=? and sPasswor d=passwor d( ?) and sSt at us=' A' " ;

psdoLogi n=conn. pr epar eSt at ement ( sql Opt i on) ;
psdoLogi n. set St r i ng( 1, sUser I D) ;
psdoLogi n. set St r i ng( 2, sPasswor d) ;

r sdoLogi n=psdoLogi n. execut eQuer y( ) ;

if( r sdoLogi n. next ( ) )
{
String sUser Name=r sdoLogi n. get St r i ng( " sFi r st Name" ) +"
" +r sdoLogi n. get St r i ng( " sLast Name" ) ;

sessi on. set At t r i but e( " sUser I D" , r sdoLogi n. get St r i ng( " sUser I D" ) ) ;
sessi on. set At t r i but e( " i User Type" , r sdoLogi n. get St r i ng( " i User Type" ) ) ;
sessi on. set At t r i but e( " i User Level " , r sdoLogi n. get St r i ng( " i User Level " ) ) ;
sessi on. set At t r i but e( " sUser Name" , sUser Name) ;

r esponse. sendRedi r ect ( " success. j sp?er r or =" +message) ;
}
else
{
message=" No user or passwor d mat ched" ;
r esponse. sendRedi r ect ( " l ogi n. j sp?er r or =" +message) ;
}
}
catch( Exception e)
{
e. pr i nt St ackTr ace( ) ;
}


/ / / cl ose obj ect and connect i on
try{
if( psdoLogi n! =null) {
psdoLogi n. cl ose( ) ;
}
if( r sdoLogi n! =null) {
r sdoLogi n. cl ose( ) ;
}
Publishedbywww.myignou.in
Visitourwebsitetodownloadmoresolvedassignments.


if( conn! =null) {
conn. cl ose( ) ;
}
}
catch( Exception e)
{
e. pr i nt St ackTr ace( ) ;
}

%>
doLogin.jsp match user id and password with database record. If record is matched with user field and
password. It will set user id, user type, user level, first name, last name in session. This can access from
session in further in application. It will finish processing and return to success.jsp page.
success.jsp
<%@page cont ent Type=" t ext / ht ml ; char set =i so- 8859- 1" l anguage=" j ava" %>
<html>
<head>
<title>Successf ul l y Logi n by J SP</ title>
</ head>

<body>
Successf ul l y l ogi n by J SP<br / >
Sessi on Val ue<br / >
<%
out . pr i nt ( " User Name : " +sessi on. get At t r i but e( " sUser I D" ) +" <br >" ) ;
out . pr i nt ( " Fi r st & Last Name : " +sessi on. get At t r i but e( " sUser Name" ) ) ;
%>
</ body>
</ html>
If user id and password is not matched, it will return back to login.jsp page and print error message to user,
user id and password is not matched.
The example of login is given with source code, login.jsp, doLogin.jsp and success.jsp.


Published by www.myignou.in
Uploaded by Pankaj Sethi
Call 9781453353
Email sethi_pankaj@yahoo.in

Potrebbero piacerti anche