CS1401-INTERNET COMPUTING 2 units Question Bank with Answers Unit-1 FUNDAMENTALS Part-A 1. What are the sequences of steps for each HTTP request from a client to the server? 1. Making the connection 2. Making a request 3. The response 4. Closing the connection 2. What is meant by Stateless Connection? When a web server receives a HTTP request from a web browser it evaluates the request and returns the requested document, if it exists, and then breaks the HTTP connection. This document is preceded by the response header, which has details about how to display the document that will be sent by the server. Each time a request is made to the server, it is as if there was no prior connection and each request can yield only a single document. This is known as Stateless Connection. 3. Difference between GET and POST request?

Cached History

Restrictions on data length Restrictions on data type

Security Visibility

GET Can be cached Parameters remain in browser history Yes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters) Only ASCII characters allowed GET is less secure compared to POST because data sent is part of the URL Data is visible to everyone in the URL

4. Write a JavaScript to display a Clock.

POST Not cached Parameters are not saved in browser history

No restrictions No restrictions. Binary data is also allowed POST is a little safer than GET because the parameters are not stored in browser history or in web server logs Data is not displayed in the URL

5. Write a VBScript to remove leading or trailing spaces from string?

6. Write a java script program using switch case statement to extract the day from the current date and display what day it is.

7. What is the difference between node and host? A node is any addressable device connected to a network whereas the host is a more specific descriptor that refers to a networked general-purpose computer rather than a single purpose device (such as a printer). 8. Compare HTML and DHTML HTML 1. It is referred as a static HTML and static in nature. 2.A plain page without any styles and Scripts called as HTML.

3.HTML sites will be slow upon client-side technologies. 4.HTML pages does not require any processing from browser DHTML 1.It is referred as a dynamic HTML and dynamic in nature. 2.A page with HTML, CSS, DOM and Scripts called as DHTML. 3.DHTML sites will be fast enough upon client-side technologies. 4.DHTML requires processing from browser which changes its look and feel 9. What are the various Internet Application Protocols? HTTP(Hyper Text Transfer Protocol) HTTPS(Secure Hyper Text Transfer Protocol) FTP(File Transfer Protocol) SMTP(Simple Mail Transfer Protocol) ICMP(Internet Control Message Protocol) 10. Why we need Client Side Scripting? Client-side scripting is code that exists inside the client’s HTML page. This code will be processed on the client machine and the HTML page will NOT perform a Post Back to the web-server. Traditionally, client-side scripting is used for page navigation, data validation and formatting. The user’s actions will result in an immediate response because they don't require a trip to the server. Part-B 11. Write simple HTML program to illustrate the usage of forms and inputs

Student Registration Form

Please fill all the fields

output form

12. Explain the class of internet addresses and the method of retrieving the data with URL. Definition of URL: We can retrieve data by using the address of the file. This address is called a Uniform Resource Locator(URL). The Address box of the browser shows the URL of the currently displayed document. We can type a URL into the address box and can get the file we wanted. Syntax protocol://domain:port/path?query_string#fragment_id

Explanation: In the same way as each host computer has a unique IP address, every data file or document on the Internet also has a unique address called a URL. The URL consists of three parts: the protocol, the domain name and the path. The protocol, as discussed earlier, is the set of rules which the computer follows in order to communicate with other computers. It lets the computer know how to process the information it receives. If the protocol is http:// , for example, the computer knows it will be processing a World Wide Web document.

The domain name is the Internet address of the computer (server) that is hosting the site and storing the documents. This domain name may be expressed as an IP address. The path is the directory and file specification: it lets the computer know which directory and file to access after connecting to the server. The path is not a required elements, but if you know the path, it will take you directly to the desired file or document. The path is also part of the URL which changes frequently. For example, http:// is the protocol. This lets you know that you are retrieving a World Wide Web document and lets the computer know how to process the hypertext file it is receiving. www.linccweb.org/ is the domain name, the address of the computer that is hositng the web page. E-resources.asp provides the path to the specific page you want; in this case, the name of the file (eresources.asp) that provides links to electronic database. Example http:// www.linccweb.org/eresources.asp Retrieving data with url program: // Demonstrate URL Import java.net *; Class URL Demo{ Public static void main(String args[])throws malformed URL exception { URL hp = new URL(“http:// www.ijcsns.org/downloads”); System.out.println(“protocol”+hp.get protocol()); System.out.println(“port” hp.get port()); System.out.println(“host”: + hp.get host()); System.out.println(“file”: +hp.get files()); System.out.println(“ext”: +hp.to external form()); } } 13. a) Why is meant by a function procedure in VB script? Write a VB Script function procedure to receive the current time and display the time along with a.m or p.m A Function procedure: is a series of statements, enclosed by the Function and End Function statements can perform actions and can return a value can take arguments that are passed to it by a calling procedure without arguments, must include an empty set of parentheses () returns a value by assigning a value to its name

Function myfunction() some statements myfunction=some value End Function (Or) Function myfunction(argument1,argument2) some statements myfunction=some value End Function

A Function procedure can return a result.

b) Write a script in java for calculating the total marks of 6 subjects for 60 students. try to count 14. Explain in detail about Cascading Style Sheets with suitable examples. Definition of CSS: Cascading style sheets (css) are rules or styles for organizing the layout of an HTML document including its color, typefaces, margins, links and other formatting elements.

Types of CSS Inline Style with example Internal Style with example External style with example Inline Style There are four ways of adding styles to a web page  Embed style sheet within the HEAD tags of the HTML document.  Link to an external style sheet from the HTML document.  Import an external style sheet into the document.  In-line style sheet added into the middle of the HTML document.  Local (in-line) style sheet declarations, specific to a single instances on a page  can be used instead of tags to specify font size, color, and typeface and  to define margins, leading, etc.  The inline style attribute is supported by most  tags the allows the author to modify the properties of individual tagged regions  document. An example of a tag with a style attribute is:

This is a heading



There are other ways to make the same changes to this heading, for example, use the font tag to modify the font properties

This is a heading

. There are many ways to define in-line style sheet. However, it is now generally accepted as better to use style attributes rather than other tags for changing the rendering of text and other document entities. The reason for text and other document entities. The reason for having styles is to easily define modification to rendering attributes that apply to parts of a document, in entire documents, or even an entire website.

Internal Style Global (embedded) style sheet declarations, applicable to an entire Document, are defined within the tags, which precede the tag in the HTML document and are usually placed in the header. To embed a global style sheet in the HTML document, the following Syntax is used Title [DOCUMENT BODY GOES HERE] External style Linked style sheet declarations use a single style sheet (in a separate file from HTML documents, saved with the .css suffix) to define multiple pages. They can be accessed by multiple files with a single link tag, ensuring consistency in a website and making it very easy to make global changes/updates. These external style sheets offer several benefits. o Web developers and web managers may share style sheets across a number of documents or sites. o The designers can changes style sheet without affecting the document. The users also lead individual style sheets when they are separately available. o To access them use the in the head section. As the following syntax suggests. Advantages and Disadvantages of CSS CSS saves time: when most of us first learn HTML, we are taught to set the font face, size, color, style, etc. Every time it occurs on a page. This means we find ourselves typing ( or copying and pasting) the same thing again and again. With css, you only have to specify the details once. Css will automatically apply the elements. Css will automatically apply the specified styles whenever that element(s) occurs. Pages load faster: less code means faster download times. Easy maintenance: to change the style of an element, you only have to make an edit in one place. Superior styles to HTML: css has a much wider array of attributes than HTML Disadvantage Browser compatability: the two main browsers ( netscape and internet explorer) , have varying levels of complains with style sheets. This means that some style sheet features are supported and some are not.

15. How will you specify a frame layout? Explain. Introduction to frames HTML frames allow authors to present documents in multiple views, which may be independent windows or subwindows. Multiple views offer designers a way to keep certain information visible, while other views are scrolled or replaced. For example, within the same window, one frame might display a static banner, a second a navigation menu, and a third the main document that can be scrolled though or replaced by navigating in the second frame. Here is a simple frame document: A simple frameset document <P>This frameset document contains: <UL> <LI><A href="contents_of_frame1.html" rel="nofollow">Some neat contents</A> <LI><IMG src="contents_of_frame2.gif" alt="A neat image"> <LI><A href="contents_of_frame3.html" rel="nofollow">Some other neat contents</A> </UL>

Sample Output

--------------------------------------| | | | | Frame 1 | | | | | |---------| | | Frame 3 | | | | | | | Frame 2 |

| | | | | | | | | | |

| | | | | | | | | | | | ---------------------------------------

If the user agent can't display frames or is configured not to, it will render the contents of the NOFRAMES element. Layout of frames An HTML document that describes frame layout (called a frameset document) has a different makeup than an HTML document without frames. A standard document has one HEAD section and one BODY. A frameset document has a HEAD, and a FRAMESET in place of the BODY. The FRAMESET section of a document specifies the layout of views in the main user agent window. In addition, the FRAMESET section can contain a NOFRAMES element to provide alternate content for user agents that do not support frames or are configured not to display frames. Elements that might normally be placed in the BODY element must not appear before the first FRAMESET element or the FRAMESET will be ignored. A frameset document Sample Output: -----------------------------------------|Frame 1 |Frame 3 |Frame 4 | | | | | | | | | | | | | | | | | | | | | | | | | | | | | -------------| | | |Frame 2 | | | | | | | | | | | ------------------------------------------

16. Write short notes on the scripting languages Java Script and VB Script with examples. Need for Client Side Scripting: Client-side scripting, can be embedded into the page on the client’s browser. This script will allow the client’s browser to alleviate some of the burden on your web server when running a web application. Client-side scripting is source code that is executed on the client’s browser instead of the web-server, and allows for the creation of faster and more responsive web applications. The two main benefits of client-side scripting are: •

The user’s actions will result in an immediate response because they don't require a trip to the



server.

Fewer resources are used and needed on the web-server.

JavaScript : • It is a programming language. • It is an interpreted language. • It is object-based programming. • It is widely used and supported • It is accessible to the beginner. 2.Advantages of JavaScript • Speed. Being client-side, JavaScript is very fast because any code functions can be run immediately instead of having to contact the server and wait for an answer. •

Simplicity. JavaScript is relatively simple to learn and implement.



Versatility. JavaScript can be inserted into any web page regardless of the file extension. JavaScript can also be used inside scripts written in other languages such as Perl and PHP.

• •

Server Load. Being client-side reduces the demand on the website server. 3. Disadvantages of JavaScript Security. Because the code executes on the users' computer, in some cases it can be exploited for malicious purposes. This is one reason some people choose to disable JavaScript.



Reliance on End User. JavaScript is sometimes interpreted differently by different browsers. Whereas server-side scripts will always produce the same output, client-side scripts can be a little un predictable. Don't be overly concerned by this though - as long as you test your script in all the major browsers you should be safe.

My First JavaScript

This is a paragraph.

OUTPUT; My First JavaScript This is a paragraph.

VBScript: 1.VBScript is a scripting language 2.A scripting language is a lightweight programming language 3.VBScript is a light version of Microsoft's programming language Visual Basic Advantages of VBScript: • No special installation required •

Popular on windows



Flexible for the Visual Basic programmer, they did not need any new learning to master in VBScript.

Disadvantages of VBScript: • Does not provide cross platform support. •

No specific way to provide multi line comment

OUTPUT: This is my first VBScript!

Unit-2 Server Side Programming

PART-A 1. What is meant by loop Back address? 127.0.0.1 is the loopback address in IP. Loopback is a test mechanism of network adapters. Messages sent to 127.0.0.1 do not get delivered to the network. Instead, the adapter intercepts all loopback messages and returns them to the sending application. IP applications often use this feature to test the behaviour of their network interface. 2. What are the two commonly used request methods? The two most common request methods used are GET and POST. GET - Requests data from a specified resource POST - Submits data to be processed to a specified resource 3. What is the significance of servlet container? To deploy and run a servlet, a web container must be used. A web container (also known as a servlet container) is essentially the component of a web server that interacts with the servlets. The web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. 4. How to track a user session in servlets? There are four typical solutions to this problem: cookies, URL rewriting, hidden form fields and Session tracking APIs. 5. What is the usage of java servlets? The servlet is a Java programming language class used to extend the capabilities of a server. Although servlets can respond to any types of requests, they are commonly used to extend the applications hosted by web servers, so they can be thought of as Java Applets that run on servers instead of in web browsers. (OR) o o o o

Servlets are most often used to Process or store data that was submitted from an HTML form Provide dynamic content such as the results of a database query Manage state information that does not exist in the stateless HTTP protocol, such as filling the articles into the shopping cart of the appropriate customer o Handling HTTP client requests o Capable of serving multiple clients concurrently 6. Why build web page dynamically? o The Web page is based on data submitted by the user.

o E.g., results page from search engines and order confirmation pages at on-line stores o The Web page is derived from data that changes frequently.  E.g., a weather report or news headlines page o The Web page uses information from databases or other server-side sources  E.g., an e-commerce site could use a servlet to build a Web page that lists the current price and availability of each item that is for sale. 7. Give some examples for web server and web browser? Web Servers: Apache HTTP Server Microsoft Internet Information Services (IIS) Sun Java System Web Server Apache Tomcat JBoss Web browsers: Internet Explorer Mozilla Firefox Opera Safari Google Chrome 8. What is the motive of JSP?  JSP is widely used for developing dynamic web sites.  JSP is used for creating database driven web applications because it provides superior server side scripting support.  Simplifies the process of development  Portability  Because of Efficiency  Independency of Layers 9. What are the return values of getParameter values method of the Http servlet Request? Returns the values of the specified parameter for the request as an array of strings, or null if the named parameter does not exist.

10. What is the use of JSP scriptlets? A JSP scriptlet is used to contain any code fragment that is valid for the scripting language used in a page. The syntax for a scriptlet is as follows: <% scripting-language-statements %>

PART-B 1. How can you use the servlet session tracking API to keep track of visitors as they move around at your site with example. The Need for Session Tracking

HTTP is a “stateless” protocol: each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server does not automatically maintain contextual information about the client. Even with servers that support persistent (keep-alive) HTTP connections and keep sockets open for multiple client requests that occur in rapid succession, there is no built-in support for maintaining contextual information. This lack of context causes a number of difficulties. For example, when clients at an online store add an item to their shopping carts. Similarly, when clients decide to proceed to checkout, how can the server determine which previously created shopping carts are theirs? These questions seem very simple, yet, because of the inadequacies of HTTP, answering them is surprisingly complicated. There are three typical solutions to this problem: cookies, URL rewriting, and hidden form fields. 

Our example tracks the number of visits for each unique visitor.  If this is a first time visit, the servlet creates an accessCount of Integer Integer Type and assigns it to the Session.  If the user has visited before,the servlet extracts the accessCount and increments it, and also assigns it to the Session.  Servlet also displays  basic information regarding the session including creation time and time of last access.

package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; import java.util.*; public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Session Tracking Example"; HttpSession session = request.getSession(true); String heading; Integer accessCount = (Integer)session.getAttribute("accessCount"); if (accessCount == null) { // new user accessCount = new Integer(0); heading = "Welcome, Newcomer"; } else { // returning user heading = "Welcome Back"; accessCount = new Integer(accessCount.intValue() + 1); } // Integer is an immutable (nonmodifiable) data structure. So, you can not modify the old one in-place. //Instead you have to to allocate a new one and redo setAttribute. session.putAttribute("accessCount", accessCount); out.println(ServletUtilities.headWithTitle(title) + "\n" + "

" + heading + "

\n" + "

Information on Your Session:

\n" + "\n" + "\n" + \n" + " \n" + " \n" + " \n" + " "+ "
Info TypeValue\n" + "
ID\n" + " " + session.getId() + "\n" + "
Creation Time\n" + " " + new Date(session.getCreationTime()) + "\n" + "
Time of Last Access\n" + " " + new Date(session.getLastAccessedTime()) + "\n" + "
Number of Previous Accesses\n" + " " + accessCount + "\n" + "
\n" + ""); } /** Handle GET and POST requests identically. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }

} Sample Output:

2. Give detailed notes on servlet chaining and communications with proper example. 16 SERVLET CHAINING

• •

Servlets cooperate to create content Multiple servlets in a chain – request parameters supplied to first servlet – output piped to successive servlets – last servlet in chain sends output to client

Servlet Chaining Can be Used to

• • •

Quickly change appearance of a page, group of pages, or type of content – suppress tags – translate into a different language Display section of page in special format – tag - print results of query Support obscure data types – serve up unsupported image formats as GIF or JPEG

ServletContext



For sharing resources among servlets, we use ServletContext – Server-specific attributes (name-value pairs, much like System.properties) and server configuration information – Ability to find other servlets

Servelt Context



Used for

– Getting a MIME type of a file – Writing to a log file – Dispatching requests Servlet Communication



To service a request, the servlet may need to get resources from: – databases – other servlets – HTML pages (or other files) – objects shared among servlets at the same server – and so on

Getting a Resource



There are two ways to get a resource: – With a HTTP request – Using a RequestDispatcher object – Using SendRedirect();

A Request Dispatcher

• •

Receive requests from a client Dispatch the request to a resource: – A servlet, – A JSP, – Another server

Request Dispatcher Methods

• •

void forward (ServletRequest request, ServletResponse response) – Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server void include (ServletRequest request, ServletResponse response) – Includes the content of a resource (servlet, JSP page, HTML file) in the response

Getting a Request Dispatcher

public class BookStoreServlet extends HttpServlet { public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the dispatcher; // it gets the main page to the user RequestDispatcher dispatcher = getServletContext().getRequestDispatcher( "/bookstore/bookstore.html"); ... } }

Resources that are not Available



To deal with resources that are not available you should do:

if (dispatcher == null) { // No dispatcher means the html file //cannot be delivered response.sendError(response.SC_NO_CONTENT); } Forwarding Request

public class BookStoreServlet extends HttpServlet { public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // Get or start a new session for this user HttpSession session = request.getSession(); // Send the user the bookstore's opening page dispatcher.forward(request, response); ... } } Include

• •

Forwarding a request cannot be used to service requests partially We should use include() of resources

********SERVLET 1*********** public class gatewayservlet extends HttpServlet { public void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException , IOException { doGet(request,response); } public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException , IOException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); name = request.getParameter("name");

RequestDispatcher rd = getServletConfig().getServletContext().getRequestDispatcher("/justServlets/secondser vlet"); if(name!=null) { request.setAttribute("UserName",name); rd.forward(request , response); // Forward the value to another Secondservlet } else { response.sendError(response.SC_BAD_REQUEST, "UserName Required"); } } } ********SERVLET2************* public class secondservlet extends HttpServlet { public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException , IOException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); String UserName = (String)request.getAttribute("UserName"); out.println("The UserName is "+ UserName); }

public void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException , IOException { doGet(request,response); } } INVOKING FORM

Please Fill the Registration Form


Enter Your Name


3. Explain the lifecycle of servlet. Write a servlet code to calculate the simple interest. 16 SERVLET: Servlets are programs that run on a Web server and build Web pages. Java technology is very helpful for this kind of CGI programming. Building Web pages on the fly is useful for a number of reasons: The Web page is based on data submitted by the user. The data changes frequently. The Web page uses information from corporate database or other such sources. THE SERVLET LIFE CYCLE  Servlets run on the Web server platform as part of the same process as the Web server itself.  The Webserver is responsible for initializing, invoking, and destroying a each servlet instance.  A Web server communicates with a servlet through a simple interface javax.servlet.Servlet.  This interface consists of three main methods:

Init() Service() Destroy() And two ancillary methods: GetServletConfig() GetServletinfo()   



Servlets are counterpart to applets. Servlets are to Web servers and applets are to Web browsers. An applet runs in a Web browser, performing actions it requests Stream, which can be used to get additional through a specific interface. A servlet does the same, running in the Web server.

The init() method When a servlet is first loaded, its init() method is invoked. This allows the servlet to perform any serup processing such as opening files or establishing connections to their servers. If a servlet has been permanently installed in a server, it loads when the server starts to run. Otherwise the server activates a servlet when it receives the first client request for the services provided by the servlet. Note that init() will only be called once; it will not be called again unless the servlet has been unloaded and then reloaded by the server. The init() method takes one argument, a reference to a ServletConfig object which provides initialization arguments for the servlet.

This object has a method geetContextServlet() that returns a ServletContext object containing information about the environment of the servlet.

The service() method The service() method is the heart of the servlet. Each request message from a client results in a single call to the servlet’s service() method. The service() method reads the request and produces the response message from its two parameters: A ServletRequest object with data from the client. The data consists of name/value paris of parameters and an InputStream. Servlet methods are provided that return the client’s parameter information. The Inputstream from the client can be obtained via the getInputStream from the client can be obtained via the getInputStream() method. This method returns a SerlvletInputStream, which can be used to get additional data from the client. A ServletResponse represents the servlte’s reply back to the client. When preparing a response, the method setContentType() is called first to set the MIME type of the reply. Next,the method getOutputStream or PrintWriter, respectively to sent data back to the client. The destroy() method The destroy() method is called to allow the servlet to clean up any resources such as open files or database connections before the servlet is unloaded. If clean-up operations are not required,this can be an empty method. The server waits to call the destroy() method until either all service calls are complete, or a certain amount of time has passed. This means that the destroy() method can be called while some longerrunning service() methods are sill running. It is important that destroy() method is deifned to avoid closing any necessary resuouces until all service() calls have been completed.

Simple interest.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class SimpleInterest extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { float principal = 0.0F; float interestRate = 0.0F; float interestAmount = 0.0F; // process input if any if ( (req.getParameterNames()).hasMoreElements() ) { // there is a request principal = Float.valueOf(req.getParameter("principal").trim()).floatValue(); interestRate = Float.valueOf(req.getParameter("rate").trim()).floatValue(); interestAmount = (principal * interestRate) /100; } // generate form and result res.setContentType("text/html"); String title = "Simple Interest Calculation"; PrintWriter out = res.getWriter(); out.println(""+title+""); out.println("

"+title+"

"); out.println("
"); out.println("Enter Principal amount:"); out.println(""); out.println("

Enter interest rate:"); out.println(""); out.println("

"); out.println("

Calculated Interest: "+interestAmount); out.println("

"); out.println("

SimpleInterest.java"); out.println(""); out.close(); } }

4. Explain the components of JSP.

16

INTRODUCTION • Java Server Pages are HTML pages embedded with snippets of Java code. – It is an inverse of a Java Servlet • JSPs run in two phases – Translation Phase – Execution Phase • In translation phase JSP page is compiled into a servlet – called JSP Page Implementation class • In execution phase the compliled JSP is processed



Four different elements are used in constructing JSPs – Scripting Elements • Declarations • Expressions – Directives – Actions – Implicit Objects – Comments

The Scriptlet: A scriptlet can contain any number of JAVA language statements,

variable or method declarations, or expressions that are valid in the page scripting language. Following is the syntax of Scriptlet: <% code fragment %>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP: Hello World Hello World!
<% out.println("Your IP address is " + request.getRemoteAddr()); %> JSP Declarations:

A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. Following is the syntax of JSP Declarations: <%! declaration; [ declaration; ]+ ... %>

You can write XML equivalent of the above syntax as follows: code fragment

Following is the simple example for JSP Declarations: <%! <%! <%! JSP

int i = 0; %> int a, b, c; %> Circle a = new Circle(2.0); %> Expression:

A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file. The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression. Following is the syntax of JSP Expression: <%= expression %>

You can write XML equivalent of the above syntax as follows: expression

Following is the simple example for JSP Expression: A Comment Test

Today's date: <%= (new java.util.Date())%>



This would generate following result:

Today's date: 11-Sep-2010 21:24:25 Directives • •



Messages sent to the JSP container – Aids the container in page translation Used for – Importing tag libraries – Import required classes – Set output buffering options – Include content from external files The jsp specification defines three directives – Page: provder information about page, such as scripting language that is used, content type, or buffer size – Include :used to include the content of external files – Taglib :used to import custom actions defined in tag libraries

Page Directives •



• •

Page directive sets page properties used during translation – JSP Page can have any number of directives – Import directive can only occur once – Embedded in <%@ and %> delimiters Different directives are – Language: (Default Java) Defines server side scripting language (e.g. java) – Extends: Declares the class which the servlet compiled from JSP needs to extend – Import: Declares the packages and classes that need to be imported for using in the java code (comma separated list) – Session: (Default true) Boolean which says if the session implicit variable is allowed or not – Buffer: defines buffer size of the jsp in kilobytes (if set to none no buffering is done) Page Directives Types con’t. Different directives are (cont’d.) – autoFlush:When true the buffer is flushed when max buffer size is reached (if set to false an exception is thrown when buffer exceeds the limit) – isThreadSafe: (default true) If false the compiled servlet implements SingleThreadModel interface – Info: String returned by the getServletInfo() of the compiled servlet – errorPage: Defines the relative URI of web resource to which the response should be forwarded in case of an exception – contentType: (Default text/html) Defines MIME type for the output response – isErrorPage: True for JSP pages that are defined as error pages – pageEncoding: Defines the character encoding for the jsp page

<%@ page language=“java” buffer=“10kb” autoflush=“true” errorPage=“/error.jsp”

import=“java.util.*, javax.sql.RowSet” %> Include Directive Basics • Used to insert template text and JSP code during the translation phase. – The content of the included file specified by the directive is included in the including JSP page • Example – <%@ include file=“included.jsp” %> JSP Actions:





JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. There is only one syntax for the Action element, as it conforms to the XML standard:







Action elements are basically predefined functions and there are following JSP actions available:

Syntax jsp:include jsp:include jsp:useBean jsp:setProperty jsp:getProperty jsp:forward jsp:plugin jsp:element jsp:attribute jsp:body jsp:text

Purpose Includes a file at the time the page is requested Includes a file at the time the page is requested Finds or instantiates a JavaBean Sets the property of a JavaBean Inserts the property of a JavaBean into the output Forwards the requester to a new page Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin Defines XML elements dynamically. Defines dynamically defined XML element's attribute. Defines dynamically defined XML element's body. Use to write template text in JSP pages and documents.

JSP Implicit Objects:

JSP supports nine automatically defined variables, which are also called implicit objects. These variables are: Objects Request Response Out

Description This is the HttpServletRequest object associated with the request. This is the HttpServletResponse object associated with the response to the client. This is the PrintWriter object used to send output to the

Session Application Config pageContext Page Exception

client. This is the HttpSession object associated with the request. This is the ServletContext object associated with application context. This is the ServletConfig object associated with the page. This encapsulates use of server-specific features like higher performance JspWriters. This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. The Exception object allows the exception data to be accessed by designated JSP.

JSP Comments:

JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page. Following is the syntax of JSP comments: <%-- This is JSP comment --%>

Following is the simple example for JSP Comments: A Comment Test

A Test of Comments

<%-- This comment will not be visible in the page source --%>

5. Explain the procedure for dynamic content generation with example. 10 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; /** * Example based on one in Enterprise Java by Savit, Wilcox and Jayaraman * MCGrawHill 1998 p180-186 * with the following changes: * reworked to match the current API in JSDK * two programs combined into one to provide a turn-round form @author Chris Wallace */ public class SimpleInterest extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { float principal = 0.0F; float interestRate = 0.0F; float interestAmount = 0.0F; // process input if any if ( (req.getParameterNames()).hasMoreElements() ) { // there is a request principal = Float.valueOf(req.getParameter("principal").trim()).floatValue(); interestRate = Float.valueOf(req.getParameter("rate").trim()).floatValue(); interestAmount = (principal * interestRate) /100; } // generate form and result res.setContentType("text/html"); String title = "Simple Interest Calculation"; PrintWriter out = res.getWriter(); out.println(""+title+""); out.println("

"+title+"

"); out.println("
"); out.println("Enter Principal amount:"); out.println(""); out.println("

Enter interest rate:"); out.println(""); out.println("

"); out.println("

Calculated Interest: "+interestAmount); out.println("

"); out.println("

SimpleInterest.java"); out.println(""); out.close(); } }

6. Distinguish between ASP and JSP. ASP ASP stands for Active Server Pages. ASP is released by Microsoft. ASP uses Visual Basic language. ASP application can be connected to MS SQL and MS Access database. ADO can be used to connect to other databases.

8

JSP JSP is the acronym of Java Server Pages. JSP is released by Sun Microsystems. JSP is a Java based language. JSP can be connected to any database by loading the appropriate driver and then connecting to the database through that driver. Microsoft IIS Server supports ASP on the Apache Tomcat Web Server and Linux Windows platform. based server support the website built using JSP. In addition, JSP also runs on IBM and JBOSS application servers. ASP is not a free of cost language because JSP is available for free of cost. You can ASP relies on Windows and IIS; both of create JSP application and execute them them are not available for free. using Apache Tomcat web server, all for free. ASP code can only be interpreted. JSP code can be interpreted as well as compiled.

CS1401-IC-UNIT-1&2_NoRestriction.pdf

... Scripts called as HTML. Whoops! There was a problem loading this page. CS1401-IC-UNIT-1&2_NoRestriction.pdf. CS1401-IC-UNIT-1&2_NoRestriction.pdf.

859KB Sizes 4 Downloads 251 Views

Recommend Documents

No documents