0% found this document useful (0 votes)
56 views14 pages

NOV/DEC 2008 ANS 1 (A) Fill in The Blanks

Uploaded by

Chaitali Kothari
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views14 pages

NOV/DEC 2008 ANS 1 (A) Fill in The Blanks

Uploaded by

Chaitali Kothari
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

NOV/DEC 2008

ANS 1 (A) Fill in the blanks


1. SERVER_NAME environtment variable gives the web servser’s computer
name in ASP.
2. For organizing a large site with dynamic navigational link contentlinker ASP
component is used.

4.To persist information of user on client computer for a period of days or years
cookie is used.

7. Flush method of response object is used to send all the data store3d in the
buffer to client and then clears the buffer in ASP buffered approach.
8. Application object is used to share information among several clients visiting
the same group of pages in ASP.
9. For applying rules for structuring an XML document DTD is used.

ANS 2 B: <HTML>

<HEAD>
<title>Politics<title>
</HEAD>
<body>
<h1><U>Political Information</U></h1>
<table border=”1”>
<tr>
<td><U>Name:</U></td>
<td><input type=“text“ Name=“txtName“>
</td>
</tr>
<tr>
<td>Gender:</td>
<td><input type=“Radio“ Name=“Gender“ value=”Male” >Male
<input type=“Radio“ Name=“Gender“ value=”Female” >Female
</td>
</tr>
<tr><td>Party</td>
<td><input type=”text” Nmae=”txtParty”></td>
<tr><td colspan=”2”><input type=”submit” Name=”submit” value=”Add”>
</tr>
</table>
</form>
<% If Request(“submit”)<>” then
qr=”insert into Political_Info values(‘ ” & Request(“txtName”) & ” ’,’ ” &
Request(“Gender”) & ” ‘,’ “ &Request(“txtParty”)& “ ‘)”
cn.execute qr
%>
</body>
</html>
ANS 3(1)
ASP script
<%

today = cint(day(date))
Response.Write(today)
if today MOD 2 = 0 then
Response.Redirect("even.asp")
else
Response.Redirect("odd.asp")
end if

%>
ANS 3(2)
A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer
requests a page with a browser, it will send the cookie too. With ASP, you
can both create and retrieve cookie values.
Create cookie
<%
Response.Cookies("firstname")="Alex"
%>
Retive cookie:
<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>

ANS 3(4) :

a. HTTP_HOST: The test string, “%{HTTP_HOST}”, is a reference to the


HTTP_HOST header that came in with the HTTP request. It’s the name of
the server the request has been sent to.
b. HTTP_USER_AGENT : It is used to retrieve information about the users
browser and computer operating system

<?php

echo $_SERVER['HTTP_USER_AGENT'];

?>

c. HTTP_ACCEPT_LANGUAGE: The Accept-Language header contains


information about the language preference of a user. This HTTP header is useful
to multilingual sites for deciding the best language to serve to the client. Some
exampleAccept-Language headers are provided below:

Nokia 6230i (the Accept-Language header value can be changed in the


Preferences dialog of the emulator):
En

ANS 3(5) :

AdRotator:The AdRotator control is used to display a sequence of ad images.

This control uses an XML file to store the ad information. The XML file must begin and
end with an <Advertisements> tag. Inside the <Advertisements> tag there may be
several <Ad> tags which defines The predefined elements inside the <Ad> tag are listed
below:

Element Description
<ImageUrl> Optional. The path to the image file
<NavigateUrl> Optional. The URL to link to if the user clicks the ad
<AlternateText> Optional. An alternate text for the image
<Keyword> Optional. A category for the ad
<Impressions> Optional. The display rates in percent of the hits

Property:

AdvertisementFile:specifies the path to the XML file that contains ad


information

The AdvertisementFile property is used to set or return the path to the XML file
that contains the advertisement data.
<asp:AdRotator AdvertisementFile="path" runat="server" />
Path: A string specifying the location of the XML file that contains the
advertisement data
Example
<form runat="server">
<asp:AdRotator id="ad1" runat="server"
AdvertisementFile="Ad1.xml" />
</form>

SECTION II

ANS 4 (A) 1.

Servlet chaining is a technique in which two or more servlets can cooperate in


servicing a single request.
In servlet chaining, one servlet’s output is piped to the next servlet’s
input. This process continues until
the last servlet is reached. Its output is then sent back to the client.
It can be used:
1) to reduces the demand on a single servlet
2) in Modular design
3) to Enables different complex processes to be maintained by more than one
person.
4) to Allows steps in a process to be modified (eg servlet 1 -> servlet 2 or servlet 1
-> servlet 3 -> servlet 2, etc)
5) to Remove the complexity in a single servlet

ANS 4 (A) 2.

URL encoding: it converts characters into a format that can be transmitted over the
Internet. URLs can only be sent over the Internet using the ASCII character-set.

Since URLs often contain characters outside the ASCII set, the URL has to be
converted into a valid ASCII format.

URL encoding replaces unsafe ASCII characters with a "%" followed by two
hexadecimal digits.

URLs cannot contain spaces. URL encoding normally replaces a space with a + sign.

URL Decoding: It decodes the encoded URL:

Example:

TEXT : Some website you got!

URL ENCODING: encoded

Some+website+you+got%21

Decoding: Some website you got!

ANS 4 (A) 3..

a.Servlet Context :
In servlet programming, the servlet context is the environment where the servlet runs.
The servlet container creates a ServletContext object that you can use to access
information about the servlet's environment.

ServletConfig:
A servlet configuration object used by a servlet container used to pass information to
a servlet during initialization.
b. Servlet config is a private area for every servlet.Any variable stored there is
accessible to only that servlet while sevlet context is a shared area for every servlet in
an application.In an aaplication every servlet can access the variable stored in servlet
context.

c. servlet context hold the info about application and servlet config hold the servlet
info.

d. The ServletContext object is contained within the ServletConfig object, which


the Web server provides the servlet when the servlet is initialized. 

You can specify param-value pairs for ServletContext object in <context-


param> tags in web.xml file. 

e The ServletConfig parameters are specified for a particular servlet and are
unknown to otherservlets. 

The ServletContext parameters are specified for an entire application outside of


any particular servlet and are available to all the servlets within
that application. 

ANS 4 (A) 4.

Certain objects that are available for the use in JSP documents without being declared
first. These objects are parsed by the JSP engine and inserted into the generated servlet.
The implicit objects re listed below

 request
 response
 pageContext
 session
 application
 out
 config
 page
 exception

ANS 4 (A) 5.

JavaBeans are reusable software components for Java that can be manipulated
visually in a builder tool.Practically, they are classes written in the Java programming
language conforming to a particular convention. They are used to encapsulate many
objects into a single object (the bean), so that the bean can be passed around rather
than the individual objects.
 

ANS 5(A)
JSP vs ASP
1. JSP and ASP are both server side scripting languages
2. JSP is from Sun Microsystems while ASP is from Microsoft
3. ASP costs money while JSP is free.
4. ASP code is interpreted while JSP code is compiled at run time
5. JSP code can run faster than ASP if there are fewer changes
6. Majority of Windows users use ASP while users of open source operating systems
like Linux use JSP among others.

ComDescriptio ASP
JSP
n
Writing HTML Response.Write "Some
out.print("Some HTML code");
code HTML code"
Obtaining a Request("parameterName"
request.getParameter("parameterName
parameter )
")
value
Null value null Nothings

ASP Technology JSP


Technology

Reusable, Cross-Platform No JavaBeans, Enterprise JavaBeans, custom JSP


Components tags

Security Against System Crashes No Yes

Memory Leak Protection No Yes

Scripting Language VBScript, Java


Jscript

Customizable Tags No Yes

 
 
Web Server Microsoft IIS or Personal Web Server Any Web server, including Apache,
Netscape, and IIS

Platforms Microsoft Windows Most popular platforms, including the


Solaris Operating Environment, Microsoft
Windows, Mac OS, Linux, and other
UNIX platform implementations
Reusable, Cross-Platform No JavaBeans, Enterprise JavaBeans, custom JSP
Components tags

Security Against System Crashes No Yes

Memory Leak Protection No Yes

Scripting Language VBScript, Java


JScript

Customizable Tags No Yes

OR

ANS 5 (A)

MVC architecture in jsp/servlet

Model–view–controller (MVC) is a software architecture, currently


considered an architectural pattern used in software engineering.

The pattern isolates "domain logic" (the application logic for the user) from the user
interface(input and presentation), permitting independent development, testing and
maintenance of each.
 
Introduction to MVC(Model View Controler) 

Struts : Struts is an open source framework from Jakartha Project designed for
developing the web applications with Java SERVLET API and Java Server Pages
Technologies.Struts conforms the Model View Controller design pattern. Struts
package provides unified reusable components (such as action servlet) to build the
user interface that can be applied to any web connection. It encourages software
development following the MVC design pattern.

Overview of MVC Architecture

The MVC design pattern divides applications into three components:

* The Model maintains the state and data that the application represents .
* The View allows the display of information about the model to the user.

* The Controller allows the user to manipulate the application .


 

Example: Example

Here is a simple application of the pattern, implementing Java Servlets andJavaServer


Pages from Java EE:

Model
The model is a collection of Java classes that form a software application
intended to store, and optionally separate, data. A single front end class that
can communicate with any user interface (for example: a console, a graphical
user interface, or a web application).
View
The view is represented by a JavaServer Page, with data being transported to
the page in the HttpServletRequest or HttpSession.
Controller
The Controller servlet communicates with the front end of the model and loads
the HttpServletRequest or HttpSession with appropriate data, before
forwarding the HttpServletRequest and Response to the JSP using a
RequestDispatcher.

The Servlet is a Java class, and it communicates and interacts with the model, but
does not need to generate HTML or XHTML output; the JSPs do not have to
communicate with the model because the Servlet provides them with the information
—they can concentrate on creating output.

In Struts, the view is handled by JSPs and presentation components, the model is
represented by Java Beans and the controller uses Servlets to perform its action. 

By developing a familiar Web-based shopping cart, you'll learn how to utilize the
Model-View-Controller (MVC) design pattern and truly separate presentation from
content when using Java Server Pages. 

Applying MVC in Servlets and JSP

Many web applications are JSP-only or Servlets-only. With JSP, Java code is
embedded in the HTML code; with Servlets the Java code calls println methods to
generate the HTML code. Both approaches have their advantages and drawbacks;
Struts gathers their strengths to get the best of their association. 

View on JSP 
The early JSP specification follows two approaches for building applications using
JSP technology. These two approaches are called as JSP Model 1 and JSP Model 2
architectures.

JSP Model 1 Architecture


In Model 1 architecture the JSP page is alone responsible for processing the incoming
request and replying back to the client. There is still separation of presentation from
content, because all data access is performed using beans. Although the JSP Model 1
Architecture is more suitable for simple applications, it may not be desirable for
complex implementations.

JSP Model 2 Architecture - MVC

The Model 2 Architecture is an approach for serving dynamic content, since it


combines the use of both Servlets and JSP. It takes advantages of the predominant
strengths of both technologies, using JSP to generate the presentation layer and
Servlets to perform process-intensive tasks. Here servlet acts as controller and is in
charge of request processing and the creation of any beans or objects used by the JSP
as well as deciding depending on the user’s actions, which JSP page to forward the
request to. Note that there is no processing logic within the JSP page itself; it is
simply responsible for retrieving any objects or beans that may have been previously
created by the servlet, and extracting the dynamic content from that servlet for
insertion within static templates.
Limitation in traditional MVC approach 
The main limitation in the traditional MVC approach is, in that there is no separation
of business logic (validation/ conditions/ anything related to business rules) from
controller (is responsible for controlling of the application flow by using
static/dynamic request dispatcher.

MVC Model 2 Architecture is Model View Controller

1.Client submits login request to servlet application


2.Servlet application acts as controller it first decides to request validator another
servlet program which is responsible for not null checking (business rule)
3.control comes to controller back and based on the validation response, if the
response is positive, servlet controller sends the request to model
4.Model requests DB to verify whether the database is having the same user name and
password, If found login operation is successful
5.Beans are used to store if any data retrieved from the database and kept into
HTTPSession
6.Controller then gives response back to response JSP (view) which uses the bean
objects stored in HTTPSession 

ANS 5 (B)

Java servelet program:

import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;

public class Registration extends HttpServlet {


    
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
    throws ServletException, IOException {
        
      PrintWriter out = response.getWriter();
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("<html>\n");
      out.write("    <head>\n");
      out.write("      <form name=\"frm\"  enctype=\"multipart/form-data\" action=\"">\n");
      out.write("      <table width=\"65%\" border=\"0\">\n");
      out.write("  <tr>\n");
      out.write("    <td width=\"24%\">Employee_Id:</td>\n");
      out.write("    <td width=\"76%\"><input type=\"text\" name=\"txteid\" id=\"txteid\"
/></td>\n");
      out.write("  </tr>\n");
      out.write("  <tr>\n");
      out.write("    <td>Employee_Name:</td>\n");
      out.write("    <td><label for=\"txtName\"></label>\n");
      out.write("      <input type=\"text\" name=\"txtName\" id=\"txtName\" /></td>\n");
      out.write("  </tr>\n");
      out.write("  <tr>\n");
      out.write("    <td>Email Address:</td>\n");
      out.write("    <td><label for=\"txtemail\"></label>\n");
      out.write("      <input type=\"text\" name=\"txtemail\" id=\"txtemail\" /></td>\n");
     out.write("   </td></center>\n");
      out.write("    </tr>\n");
      out.write("    <tr>\n");
      out.write("    <td ><center><input name=\"btnsubmit\" type=\"submit\" 
value=\"Submit\" onclick=\"return validate_form(frm)\" /></center>\n");
      out.write("    </td>\n");
      out.write("    <td><center><input name=\"btnreset\" type=\"reset\" id=\"btnreset\"
value=\"Reset\" /></center>\n");

    String eid = request.getParameter("txteid");


    String enm = request.getParameter("txtName");
    String email = request.getParameter("txtemail");
    Connection con=null;
     try
     {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con = DriverManager.getConnection("jdbc:odbc:insert","","");
        String Query="insert into tbl1(Employee_Id,Employee_Name,Email Address)
values('" + eid + "','" + enm + "','" + email + "')";
       Statement stmt = con.createStatement();
        stmt.executeUpdate(Query);
        
      }        
       catch(Exception ex)
       {
           out.println(ex.getMessage());
       }
    
out.write("\n");
out.write("    \n");
out.write("    </body>\n");
out.write("</html>\n");
out.close();
    }

ANS 6 (1).

Implicit objects in jsp are the objects that are created by the container automatically and
the container makes them available to the developers, the developer do not need to
create them explicitly.

There are nine implicit objects. Here is the list of all the implicit objects: 
Object Class
javax.servlet.ServletConte
application
xt
javax.servlet.ServletConfi
Config
g
exception java.lang.Throwable
javax.servlet.jsp.JspWrite
Out
r
Page java.lang.Object
PageConte javax.servlet.jsp.PageCon
xt text
javax.servlet.ServletRequ
Request
est
javax.servlet.ServletResp
response
onse
javax.servlet.http.HttpSes
Session
sion

 Application: These objects has an application scope. These objects are available at


the widest context level, that allows to share the same information between the JSP
page's servlet and any Web components with in the same application.
 Config: These object has a page scope and is an instance of
javax.servlet.ServletConfig class. Config object allows to pass the initialization data
to a JSP page's servlet. Parameters of this objects can be set in the deployment
descriptor (web.xml) inside the element <jsp-file>. The method getInitParameter() is
used to access the initialization parameters.
 Exception: This object has a page scope and is an instance of java.lang.Throwable
class. This object allows the exception data to be accessed only by designated JSP
"error pages."
 Out: This object allows us to access the servlet's output stream and has a page
scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the
output stream that enable access to the servlet's output stream.
 Page: This object has a page scope and is an instance of the JSP page's servlet
class that processes the current request. Page object represents the current page
that is used to call the methods defined by the translated servlet class. First type cast
the servlet before accessing any method of the servlet through the page.
 Pagecontext: PageContext has a page scope. Pagecontext is the context for the
JSP page itself that provides a single API to manage the various scoped attributes.
This API is extensively used if we are implementing JSP custom tag handlers.
PageContext also provides access to several page attributes like including some
static or dynamic resource.
 Request: Request object has a request scope that is used to access the HTTP
request data, and also provides a context to associate the request-specific data.
Request object implements javax.servlet.ServletRequest interface. It uses the
getParameter() method to access the request parameter. The container passes this
object to the _jspService() method.
 Response: This object has a page scope that allows direct access to
theHTTPServletResponse class object. Response object is an instance of the
classes that implements the javax.servlet.ServletResponse class. Container
generates to this object and passes to the _jspService() method as a parameter.
 Session: Session object has a session scope that is an instance of
javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to
manage the state contexts. This object persist information across multiple user
connection.

ANS 6 (2).
javax.servlet.GenericServlet
Signature: public abstract class GenericServlet extends java.lang.Object
implements Servlet, ServletConfig, java.io.Serializable

 GenericServlet defines a generic, protocol-independent servlet.


 GenericServlet gives a blueprint and makes writing servlet easier.
 GenericServlet provides simple versions of the lifecycle methods init and
destroy and of the methods in the ServletConfig interface.
 GenericServlet implements the log method, declared in the ServletContext
interface.
 To write a generic servlet, it is sufficient to override the abstract service
method.

javax.servlet.http.HttpServlet
Signature: public abstract class HttpServlet extends GenericServlet implements
java.io.Serializable

 HttpServlet defines a HTTP protocol specific servlet.


 HttpServlet gives a blueprint for Http servlet and makes writing them
easier.
 HttpServlet extends the GenericServlet and hence inherits the properties
GenericServlet.

ANS 6 (3)

GET Method:

1. All the name value pairs are submitted as a query string in URL.
2. It's not secured as it is visible in plain text format in the Location bar of the web
browser.
3. As the data transfers through address bar (URL) there are some restrictions in
using space, some characters like ampersand (&) etc in the GET method of
posting data. We have to take special care for encoding data if such special
characters are present.
4. Length of the string is restricted.
5. If method is not mentioned in the Form tag, this is the default method used.
6. If get method is used and if the page is refreshed it would not prompt before the
request is submitted again.
7. One can store the name value pairs as bookmark and directly be used while
sharing with others - example search results.
8. Data is always submitted in the form of text
9. If the response of the page is always same for the posted query then use GET
example database searches

POST Method:
1. All the name value pairs are submitted in the Message Body of the request.
2. Length of the string (amount of data submitted) is not restricted.
3. Post Method is secured because Name-Value pairs cannot be seen in location
bar of the web browser.
4. If post method is used and if the page is refreshed it would prompt before the
request is resubmitted.
5. If the service associated with the processing of a form has side effects (for
example, modification of a database or subscription to a service), the method
should be POST.
6. Data is submitted in the form as specified in enctype attribute of form tag and
thus files can be used in FileUpload input box.

ANS 6 (4)

A session is an object associated with a visitor.  Data can be put in the


session and retrieved from it, much like a Hashtable.  A different set of data
is kept for each visitor to the site.
Html form : name.html
<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

SaveName.jsp saves user’s name in session


<%
   String name = request.getParameter( "username" );
   session.setAttribute( "theName", name );
%>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>

NextPage.jsp shows how to retrieve the saved name.


<HTML>
<BODY>
Hello, <%= session.getAttribute( "theName" ) %>
</BODY>
</HTML>

You might also like