Talk:CSC667 final

(a) Explain Cookies

 * explain what it is and how to use, with HTTP syntax

What it is:

Cookies are a general mechanism which server side connections (such as CGI scripts) can use to both store and retrieve information on the client side of the connection.

The syntax for a respond header is: Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure

The syntax for Request header is: Cookie: Name1=value1;Name2=Value2

(b) Session

 * explain what it is and how it is implemented

what it is
 * A session is data that is stored by the server which is tied to a particular client and can span multiple connections.

implemented:
 * It is usually implemented as a key stored in a cookie which gives access to a data structure (hashMap,etc) on the server.

-- Because the HTTP protocol is a stateless protocol, a session is created to keep track of a user’s visit and state when visiting a web page. It is implemented easily by using Servlets which have pre-implemented methods to send session cookies to the browser.

(c) Session tracking w/o cookies

 * If cookie is disabled from the client’s browser, what are the possible options to do the session tracking?

Using Hidden fields and URL rewriting

URL rewriting This is done in such a way that the sid(session key (normally stored as jsessionid in a browser cookie)) is sent back to the server during the subsequent request cycles. Requests from the rewritten content can originate in two ways: submission of forms and clicks on hyperlinks in the page. To make sure the sid is sent back, hidden fields are added in all forms. The field’s name is a standard as in case of cookies and the value is the sid. And parameters are appended to all hyperlinks—name of the parameter being standard as in case of cookies and value being sid.

And in the case of forms (note the name of hidden field – it is standard)

 In the case of hyperlinks (note the name of the parameter – it is standard) ..somepage.jsp?GXHC_gx_session_id_AppName=511f4caec5a335ee

Alex's additional answer:

Force user to enable cookies to use the site.

2. Servlet and JSP
(a) What are the advantages of using Servlet/JSP over conventional CGI programming? (list at least 3) 1. •	Using Java servlets provides a platform-independent replacement for CGI scripts. 2. Servlets are more efficient then CGI, For CGI: •Overhead of starting a new process can dominate the execution time. •For N simultaneous request, the same code is loaded into memory N times. •When terminated, lose cache computation, DB connection & .. For Servlet •JVM stays running and handles each request using Java thread. •Only a single copy is loaded into memory •Straightforward to store data between requests 3. easier DB connection and easier learning curve •Provides an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions and other utilities. •No need to learn new programming languages if you are familiar with Java already. •Easy to implement DB connection pooling & resource-sharing optimization.

4. easier session tracking.. because servlets have session object that you can use build into them 5. has a robust API that has HttpRequest and Response object that can be used to process the request and response

b) What are the differences between Servlet and JSP? (When is servlet preferred and when is JSP perferred)

Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. A servlet is a Java class implementing the javax.servlet.Servlet interface that runs within a Web or application server's servlet engine, servicing client requests forwarded to it through the server. A Java Server Page contains a mixture of HTML, Java, JSP elements, and JSP directives. The elements in a Java Server Page will generally be compiled by the JSP engine into a servlet, but the JSP specification only requires that the JSP page execution entity follow the Servlet Protocol.

The advantage of Java Server Pages is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development. Rather than choosing between servlets and Java Server Pages, you will find that most non-trivial applications will want to use a combination of JSP and servlets.

Alternatives: A Java Servlet is a Java program that is run on the server There are Java classes for retrieving HTTP requests and returning HTTP responses A Java Servlet must return an entire HTML page, so all tuning of the page must be done in a Java program that needs to be re-compiled Java Server Pages (JSP) use HTML and XML tags to design the page and JSP scriplet tags to generate dynamic content (Easier for separation between designer & developer)use Java Beans and useful built-in objects for more convinience

Since servlet uses Java, the implementation that involves a lot of HTML or XML tags required the used of "out.print" statements. This could be tedious. In the case of JSP, JSP scriplet tags are used to create the dynamic content page. Thus, the code is more readable.

Servlets are java programs that run on a server. Servlets are preferred when the functionality needs to be on the server side only. IE. When a POST or GET request is received, the servlet can be overridden to do many functions other than a normal form POST or GET. JSP is a web page with java code inserted into it. The JSP can use Beans, or java classes to help retrieve, store, or output data back to the browser.

(c) Explain the life cycle of a JSP page in terms of translation, compilation, loading and execution in case of the first time access and the second access.

JSP page (MyFirstJSP.jsp) -> Translated to Servle (MyFirstJSP.servlet) Translate from file.jsp to file.servlet -> Compiled to class (MyFirstJSP.class) compilation to create file.class -> Loaded into memory (Initialization) the servlet engine loads the servlet’s *.class file in the JVM memory space and initializes any objects -> Execution (repeats) when a servlet request is made, a ServletRequest object is sent with all information about the request a ServletResponse object is used to return the response -> Destruction: the servlet cleans up allocated resources and shuts down

Any change in JSP page automatically repeats the whole life cycle.

The second time execution will only invoke the execution life cycle.

(d) Explain procedures to create your own MyServlet (a simple servlet that receives your name and generate a response that says a greeting to you) using the HttpServlet class.

To receive the name: Create a class that extends HttpServlet Overload the function public void doGet(HttpServletRequest request, HttpServletResponse response) Set the content type by : response.setContentType("text/html"); Create the output object: PrintWriter out = response.getWriter; (assume that there is only 1 input field ) Get the name by: String value = request.getParameter(name); Print output by : out.println("Hello "+ value);

How to create a Session in Servlet?
Cookies are a mechanism that a servlet uses to have clients hold a small amount of state-information associated with the user. Servlets can use the information in a cookie as the user enters a site (as a low-security user sign-on,for example), as the user navigates around a site (as a repository of user preferences for example), or both.

HTTP servlets also have objects that provide cookies. The servlet writer uses the cookie API to save data with the client and to retrieve this data.

Source Code for Creating a Session:

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

public class SessionExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {   response.setContentType("text/html"); PrintWriter out = response.getWriter; HttpSession session = request.getSession(true); // print session info Date created = new Date( 							session.getCreationTime); Date accessed = new 						Date(session.getLastAccessedTime); out.println("ID " + session.getId); out.println("Created: " + created); out.println("Last Accessed: " + accessed); String dataName = request.getParameter("dataName"); if (dataName != null && dataName.length > 0) {String dataValue = request.getParameter("dataValue"); session.setAttribute(dataName, dataValue);} // print session contents Enumeration e = session.getAttributeNames; while (e.hasMoreElements) { String name = 		String)e.nextElement;	 value = session.getAttribute(name).toString;    out.println(name + " = " + value);}}}

Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user(that is, requests originating from the same browser) across some period of time.

session-tracking capabilities. The servlet writer can use these APIs to maintain state between the servlet and the client that persists across multiple connections during some time period.

Shopping Cart
How to store information (shopping cart – ordered items) into the session and retrieve back?

Create the MyCart object and save it into the session by using the implicit object session: session.setAttribute("cart", MyCart);

To retrieve back the shopping cart which contains the entire order : session.getAttribute("cart") session.getAttributre returns the Object type

'''When explicit casting is used and why? ' The object you get from the session is just of type Object''. In order to use it, you need to explicitly cast it to the object type you expect it to be. Only after doing this can you access the methods on the object. Object cart = session.getAttribute("cart"); cart.getItemList  ''' throws exception from tanya: i believe the above line will actually throw a compiler error, becuase .getItemList is not a function defined in object so the complier should complain. MyCart cart = (MyCart)session.getAttribute("cart"); out.print(" there are : " + cart.getItemList.size + " items in your cart"); etc...

Loss Of Session
What happens if session expires or a client kills the browser? What can you do to prevent possible loss of information?


 * If someone kills the browser it may actually keep their cookies around, so you might be able to restore their session
 * If a cookie/session expires then there is no way of knowing who the user is
 * they will be assigned a new session next time they connect
 * To prevent data loss You can do several things
 * Store some informatoin in a persistant cookie
 * this is a 'remember me' function
 * when they return to the site, with no session, you check the cookie and log them on again
 * This does not prevent data loss from the session itself, though, since you only have what you stored in the cookie
 * You can save session data to the database. This lets you get at it from across sessions, since you can link it to a user id and not to a random session key
 * You can store session data in a special data struture in the server (in application scope) and then reference that.
 * This is like a database, but without an actual database.
 * It is just a custom 'session' object that is stoerd somewhere else
 * session['some item I stored there"] would become :
 * application['sesssions'].get(my_user_id).getItem("some item I stored there");

It is also possible to use IP session tracking to save a user’s session, but this method is dangerous so should not be used.


 * There are other, more complicated ways, but forget about it.

4. Write comments where (a) – (f) is marked about the bold-faced code
'''<%@ page language="java" import="com.wrox.projsp.ch05.*, java.util.*" errorPage="error.jsp" %>'''

// (a) declare page directive to attribute "java" import all classes from "com.wrox.projsp.ch05" and "java.util" to be used later on in the page redirect the page to "error.jsp" if an uncaught exception has been thrown in the page.

page directive: The page directive is used to define attributes that apply to an entire JSP page

  



// (b) declare JavaBean object name "loginBean" from the class "com.wrox.projsp.ch05.Login" set the scope of the page to "page" so that the object "loginBean" can be accesible only on that page. set all properties in the "loginBean" from the html form.

 <% String display = "showLogin.html"; User user = loginBean.authenticate; if (user != null) { user.setIpAddr(reqItalic textuest.getRemoteHost); session.setAttribute("user", user); // (c)  //  creates a new object with name 'monitor' and type java HashMap // init the string String display = "showLogin.html";  display to page showLogin.html // User user = loginBean.authenticate; verify the user's identity. // if (user != null) { //check if the user is not authenticated //user.setIpAddr(reqItalic textuest.getRemoteHost); //if the user is logged in, the set the users IP address //based on the value obtained from the request.getRemoteHost method //session.setAttribute("user", user); //set "user" attribute for the session to the current user //  Declare java bean object called monitor which is a HashMap. Declare the string object called display // and assinged the value "showLogin.html" into the variable display. //     If user exits, set the user's IP address and set the session atrtibute with //     name="user" and value= user. // ALTERNATIVE:... for bold only: // sets the session attribute “user” to the User object returned by authenticate

monitor.put(user, session); System.out.println("Assigned new session for: " + user); session.setMaxInactiveInterval(900); display = "browse.jsp"; } %> "/>

// (d) if the user is not a valid user (not exits on the db), redirect the page to "showLogin.html" //    to prompt user to login with valid user information.

// "Correct" Answer: Forwards the user to the page indicated by the 'display' variable, since we cannot infer on whether the attribute "user" is null or not.

5. Write comments like in question No.4
<%@ page import="com.wrox.projsp.ch05.*" errorPage="error.jsp" %> Process the Order <% '''if(session.getValue("user") == null) { response.sendRedirect("showLogin.html"); }

// (a) Check if the session contain the attribute "user". If it is null, //  redirect the page to "showLogin.html"'''

'''User user = (User)session.getValue("user");

// (b) gets the value of the the parameter name "user", which is stored in the session, and cast the value as a User object and stores the value in to user object.

String display = "showDetails.jsp"; int mode = (new Integer(request.getParameter("action"))).intValue; System.out.println("Action" + mode); Order order = null; switch(mode) { /* 0 = add / modify 1 = complete 2 = clear 3 = display case(0): case(2): '''String itemIds[] = request.getParameterValues("itemId");

// (c) grab values from "itemid" (this is a form field which can have multiple items selected, like a list menu or a radio button group) and store it in string array itemIds[]'''

If (itemIds != null && itemIds.length != 0) { order = new Order(user); order.setItemIds(itemIds); '''session.setAttribute("anOrder", order);

// (d) if the string array itemIds is not null and array is not empty set order of the user and also the item. Store the order object under the 'anOrder' key in a session for further use'''

// ALTERNATIVE: (d) stores the item ids from the request parameter as a session attribute “anOrder” as an Order object

} else session.removeAttribute("anOrder"); break; case(1): // Complete the order here order = (Order)session.getAttribute("anOrder"); System.out.println("Order: " + order); order.complete((Catalog)pageContext.getAttribute("catalog", pageContext.APPLICATION_SCOPE)); display = "receipt.html"; break; } '''response.sendRedirect(display);

// (e) redirect the page to the value of the display string which could be the showDetails.jsp or receipt.html''' // ALTERNATIVE (e): redirects the user to receipt.html… indicating a successful order

%> (f) Explain about the scope (page, request, session, application) of java beans in JSP

Page - objects with page scope are accessible only within the page where they are created

Request - objects with request scope are accessible from pages processing the same request where they were created

The request scope is larger than the page scope; beans created in the request scope will last from the time they are first created until the last of the data is sent to the user.

Session - objects with session scope are accessible from pages processing requests that are in the same session as the one in which they were created

Support multiple request while maintaining the same session.

Application - objects with application scope are accessible from pages processing requests that are in the same application as the one in which they were created If you want the contents of the bean to be used so long as your server is up (share contents across all sessions), you can set the scope as application. All the different scopes behave as a single name space

(g) List and explain about the implicit objects (provided without explicit declaration) in JSP.

by Marlon :)

Object         Class or Interface  	       Description

page 	       jsp.HttpJspPage 	       Page's servlet instance config 	       ServletConfig 	               Servlet configuration information pageContext 	jsp.pageContext 	Provides access to all the namespaces associated with a JSP page and access to several page attributes request 	http.HttpServletRequest 	Data included with the HTTP Request response 	http.HttpServletResponse 	HTTP Response data, e.g. cookies out 	       jsp.JspWriter 	                Output stream for page context session 	http.HttpSession 	       User specific session data application 	ServletContext 	                Data shared by all application pages

Additional description:

Out: This object is instantiated implicitly from JSP Writer class and can be used for displaying anything within delimiters. For e.g. out.println(“Hi Buddy”);

Request: It is also an implicit object of class HttpServletRequest class and using this object request parameters can be accessed. For e.g. in case of retrieval of parameters from last form is as follows: request.getParameters(“Name”); Where “Name” is the form element.

Response: It is also an implicit object of class HttpServletResponse class and using this object response(sent back to browser) parameters can be modified or set. For e.g. in case of modifying the HTTP headers you can use this object.

Response.setBufferSize(“50”);

Session: Session object is of class HttpSession and used to maintain the session information. It stores the information in Name-Value pair. For e.g. session.setValue(“Name”,”Jakes”); session.setValue(“Age”,”22”);

Application: This object belongs to class SevletContext and used to maintain certain information throughout the scope of Application. For e.g. Application.setValue(“servername”,”www.myserver.com”);

PageContext: This object is of class pageContext and is utilized to access the other implicit objects.

These objects do not need to be declared or instantiated by the JSP author, but are provided by the container (jsp engine) in the implementation class: request Object (javax.servlet.ServletRequest), response Object, (javax.servlet.ServletResponse), session Object (javax.servlet.http.HttpSession) application Object, out Object, config Object, page Object, pageContext Object (javax.servlet.jsp.PageContext), exception
 * link http://ww2.cis.temple.edu/cis308/Lectures/Unit%202/Servlets_ImplicitObjects/JSP_Objects.htm

(h) Explain directory structure for tomcat web applications – Where is the application home directory placed, where html/jsp, java bean or servlet classes are stored?

application stored in the webapps of tomcat html and jsp are stored in webcontent java bean and servlet classes are stored in the src file

The application home directory is placed inside the tomcat webappps directory.

html/jsp files are also stored under webapps directory.

java bean or servlet classes are stored in /webapps/WEB-INF/classes directory.

Additional Answers: /conf  : This directory contains the main configuration files for Tomcat. The two most important are the server.xml and the global web.xml. /server : This directory contains the Tomcat Java Archive files. /lib   : This directory contains Java Archive files that Tomcat is dependent upon. /logs  : This directory contains Tomcat's log files. /src   : This directory contains the source code used by the Tomcat server. Once Tomcat is released, it will probably contain interfaces and abstract classes only. /webapps: All web applications are deployed in this directory; it contains the WAR file. /work  : This is the directory in which Tomcat will place all servlets that are generated from JSPs. If you want to see exactly how a particular JSP is interpreted, look in this directory.

ALTERNATIVE (Alex):

If web application war file is someapp.war

The application home directory is in tomcat/webapps

The servlet classes are stored in tomcat/webapps/someapp/WEB-INF/classes

The html/jsp files are stored in the tomcat/webapps/someapp

(i) What is war file and used for? contains --server-side utility classes (database beans, shopping carts, and so on). Often these classes conform to the JavaBeans component architecture. -- Static Web content (HTML, image, and sound files, and so on). -- Client-side classes (applets and utility classes). Basically used for tomcat to load that file.

Additional Answer: Web ARchive file (WAR) used for Packing the Web Application to deploy the web application by distributing this file Command : jar cvf onjava.war.

(a) Explain what is validity and well-formness rules in XML.
To be valid an XML document must be

- Well-formed

- Must have a Document Type Definition (DTD)

- Must comply with the constraints specified in the DTD

well-formness

-All XML documents must be well-formed

Well-formedness rules:

--Open and close all tags

--Empty tags end with />

--There is a unique root element

--Elements may not overlap

--Attribute values are quoted

--< and & are only used to start tags and entities

Parsers are required to reject malformed documents. This improves compatibility and interoperability.

--Open and close all tags

--Empty tags end with />

--There is a unique root element

--Elements may not overlap

--Attribute values are quoted

--< and & are only used to start tags and entities

Only the five predefined entity references are used

(b) What are the advantages of using XML (list 3)
Domain-Specific Markup Languages --A DTD precisely describes the format

--DTDs verify that documents adhere to the format

--Ensures interoperability of unrelated tools

Self-Describing Data

--DTDs explain the format so reverse engineering isn't as necessary

--Comments in DTDs can go even further

<!ELEMENT YEAR (#PCDATA)> Interchange of Data Among Applications

--E-commerce and syndication

--DTDs make sure that two independent applications speak the same language

--DTDs detect malformed data

--DTDs verify correct data

Structured and Integrated Data

--Can specify relationships between elements using element declarations

--Can assemble data from multiple sources using external entity references declared in the DTD

'''Additional Answer: '''

* Uses human, not computer, language. XML is readable (and understandable, even by novices) and no more difficult to code than HTML. * Completely compatible with Java and 100% portable. Any application that can process XML (on any platform) can use your information. * Extendable. Create your own tags (or use tags created by others) that use the native language of your domain, have the attributes you need, and make sense to you and your users.

(c) Explain the difference of DOM and SAX parser
DOM Parser – tree structure

SAX Parser – event driven approach

DOM Parser makes use of SAX parser to parse and then create a tree structure

(d) Generate one well-formed and valid XML file
from the given DTD. It''' should contain at least 10 elements and 1 attribute to make sure you understand DTD.

<!ELEMENT SONG (TITLE, COMPOSER+, PRODUCER*, PUBLISHER*, LENGTH?, YEAR?, ARTIST+)> <!ELEMENT TITLE (#PCDATA)> <!ELEMENT COMPOSER (#PCDATA)> <!ELEMENT PRODUCER (#PCDATA)> <!ELEMENT PUBLISHER (#PCDATA)> <!ELEMENT YEAR (#PCDATA)> <!ELEMENT ARTIST (#PCDATA)> <!ATTLIST SONG LENGTH CDATA #IMPLIED>

Anwers:  <!DOCTYPE SONG SYSTEM "song.dtd">  Hot Cop Jacques Morali Henri Belolo Victor Willis</COMPOSER> Gwen Stefani</COMPOSER> <PRODUCER>Jacques Morali</PRODUCER> <PUBLISHER>PolyGram Records</PUBLISHER> <YEAR>1978</YEAR> <ARTIST>Village People</ARTIST> <ARTIST>Alicia Keys</ARTIST> </SONG>

(e) Explain how xml file is displayed on the browser
([i]by itself, [ii]with stylesheet, [iii]with applet or plug in)

(f) List two major advantages of XML over HTML
and explain about reason for each advantage.'''

–	the World Wide Web Consortium (W3C) directs the effort

•	XML isn't a markup language, like HTML, but rather a system for defining other markup languages.

•	XML is a common syntax for expressing structure in data, and as a result a way for others to define new tags

•	The parent of HTML and XML is Standard Generalized Markup Language (SGML) an ISO standard for electronic document exchange

•	SGML competes with other standards, mainly de facto standards, like Adobe PDF (Acrobat), Microsoft RTF (Rich Text Format) and popular word processor file formats like Microsoft Word.

•	both XML and HTML are document formats derived from SGML.

–	Thus they all share certain characteristics, such as a similar syntax and the use of bracketed tags.

–	But HTML is an application of SGML, whereas XML is a subset of SGML.

•	XML documents can be

–	read by any SGML authoring or viewing tool.

–	XML is less complex than SGML, and it is designed to work across a limited-bandwidth network such as the Internet.

Additional answers:

The basic advantages of XML over HTML are that XML lets a web designer define tags that are meaningful for the particular documents or database output to be used, and that it enforces an unambiguous structure that supports error-checking.

(g) What is XSLT? How XSLT is used with XML?
•	XSL (eXtensible Stylesheet Language) consists of two parts: XSL Transformations and XSL Formatting Objects. An XSLT stylesheet is an XML document defining a transformation for a class of XML documents.

•	A stylesheet seperates contents and logical structure from presentation.

•	Not intended as completely general-purpose XML transformation language - designed for XSL Formatting Objects. Nevertheless: XSLT is generally useful.

•	XSLT is declarative and based on pattern-matching and templates

(h) The results of executing XSLT below
What would be results of executing XSLT below with hyper link connection to a given xml file? <xsl:template match="/"> </xsl:template></xsl:stylesheet>

http://thecity.sfsu.edu/~wellman/cdcatalog.jpg

7. With a given DTD, make an example of VALID XML file.
(You may start with the root element excluding processing instructions) <!ELEMENT planner ( year* )> <!ELEMENT year ( date+ )> <!ATTLIST year value CDATA #REQUIRED> <!ELEMENT date ( note+ )> <!ATTLIST date month CDATA #REQUIRED> <!ATTLIST date day CDATA #REQUIRED> <!ELEMENT note ( subject & contents )> <!ELEMENT subject ( #PCDATA )> <!ELEMENT contents ( #PCDATA )> <!ATTLIST note time CDATA #IMPLIED> Answer:

<date month="January" day="Saturday" > <note time="6:03" > CSc667 Sample Final Question I wish we had a review session

8. Explain the difference of DOM parser and SAX parser.
Show one Java sentence that invokes builder.parse method when requesting actual parsing in both parser cases in terms of return value and its parameters.

And explain shortly how they are handled in different way. (which one is event driven?)

Answer:

Document Object Model (DOM) is a description of how an HTML or XML document is represented in an object-oriented fashion. The document is accessed in a tree form. Such an implementation requires that the entire content of a document be parsed and stored in memory. Hence, DOM is best used for applications where the document elements have to be accessed and manipulated in an unpredictable sequence and repeatedly. If the application involves a sequential or one-time selective read or write per processed document, DOM presents a considerable overhead.

Invoke example:

Document document = builder.parse("someXML.xml");

SAX is a serial access parser API for XML. SAX provides a mechanism for reading data from an XML document. The SAX parser is implemented as an event-driven model in which the programmer provides callback methods which are invoked by the parser as part of its traversal of the XML document.

Invoke example:

SAXParser saxParser;

saxParser.parse( "someXML.xml", someHandler );

DOM Parser makes use of SAX parser to parse and then create a tree structure

Question 9
Which parser is more efficient when making a Web Browser? Why?

In what kind of applications is the other parser more efficient?

here is what i think, after reading the fragment below
 * you should use SAX for web browser, because all the browser does is read the xml document, it doesn't need to keep it in memory or do manipulations with it
 * you should use the DOM parser if you are modifying xml documents that you are parsing....

long answer  When you need to process XML documents, you must first decide whether to use DOM (Document Object Model) or SAX (Simple API for XML), the two main XML APIs in use today. You can use either (or both at the same time) to process XML documents, but DOM loads the document into memory to process it. SAX, on the other hand, can examine an incoming XML stream so that not all of the XML code need reside in memory simultaneously.

You choose between DOM and SAX in much the same way that you might choose between tables or views in a database: Select the approach that suits the situation. If you want to simply explore an XML document and not manipulate it, then choose SAX. The differences between SAX and DOM

There are a number of key distinctions between SAX and DOM, including:

● DOM is preferred for complicated jobs, such as when the XML schema is inherently intricate or when you need random access to the data in the document. SAX moves in a linear fashion from the start of the document down through each node to locate a particular node or otherwise provide information about the document.

● DOM builds a type description for every node in the XML document it loads into memory. Collectively, these descriptions result in an easily traversable, though potentially huge, tree structure. If the XML is verbose, DOM represents runaway inflation. For example, a 300-KB XML document can result in a 3,000,000-KB DOM tree structure in RAM or virtual memory. By contrast, a SAX document is not deconstructed at all, nor is it cached in memory (though, of course, parts of it reside briefly in memory buffers as the XML stream is read through). SAX is a “lighter” technology—imposing little burden on your system. SAX is the equivalent of watching a marathon go by; DOM is like inviting all the racers home for dinner.

So which do you choose? If you're doing something complicated such as advanced XSLT transformations or XPath filtering, choose DOM. You'd also pick DOM if you're actually creating or modifying the XML documents.

On the other hand, choose SAX for searching or reading XML documents. SAX can quickly scan a large XML document, then stop when it finds a match to your search criterion and hand you the appropriate fragment from the document.

In some situations, the best choice is to employ both DOM and SAX for different aspects of a single solution. For example, you might want to load XML into memory and modify it with DOM, but then transmit the final result by emitting a SAX stream from the DOM tree.

10. With a given XML file, show a DOM structure returned by DOM parser.
<to>ABC</to><fr>CDE</fr><sj>About tomorrow</sj>

<body type = "text/html"> Hello Test

http://thecity.sfsu.edu/~wellman/mail.jpg

Question 11-- Synchronize
For what the "synchronized" keyword is used and show how they are used in java code?

When/why do you have to care about the synchronization in the e-commerce applications?

Answer:

The Synchronized keyword is used to ensure there are no race conditions when multiple processes or threads are trying to access or change objects. The synchronized keyword is used when declaring a method:

Ex: public synchronized void doStuff{ ...   }

In an e-commerce application, you may want to use the synchronized keyword in methods to protect a single thread from other threads that are trying accessing and modifying data. Synchronize allows for a single thread to finish the method it called before other threads or connections can perform that same method.

Question 12- Java Applets
Explain why Java Applets have more security issues than Java Applications and what are the examples of those security related restrictions for Applets?

In addition to those security issues, what are the limitations that applet has? (list one)

(This is not complete answer)

Java applications run inside JVM and hence JVM controls their execution preventing them from accessing resources outside of resources allocated for JVM runtime.

Java applets are distributed over the net as compiled class files and hence there is no way to be sure that they aren't containing malicious code.

The main idea is to prevent applets from inspecting or changing files on the client file system. Also, the intent is to prevent applets from using network connections to circumvent file protections or people's expectations of privacy.

In general, applets loaded over the net are prevented from reading and writing files on the client file system, and from making network connections except to the originating host.

In addition, applets loaded over the net are prevented from starting other programs on the client. Applets loaded over the net are also not allowed to load libraries, or to define native method calls. If an applet could define native method calls, that would give the applet direct access to the underlying computer.

The applet security manager is the Java mechanism for enforcing the applet restrictions described above. Applets cannot create or reference their own security manager.

Question 13 JDBC
Explain about JDBC – how is it used in e-commerce and what is the advantage of using JDBC?

Answer:

JDBC (Java Database Connectivity)

JDBC allow you to use java to:

- Connect to a database

- Query the database

- Display the results of the query

In e-commerce, databases are used to store and retrieve information about users, products, and orders. By using the JDBC along with JavaBeans, JSPs can retrieve information to display dynamic pages, or save information to be stored in the database.

ALTERNATIVE:

JDBC stands for Java DataBase Connectivity. This is used so that java programs have the ability to connect to, and execute database queries easily. It is used in e-commerce to maintain user transactions, inventory, and user information. The advantage of using JDBC is that different types of database systems can be implemented via a JDBC driver, but the code written using the JDBC interface does not need to be changed.

Question 14 Connection Pool
What is connection pool? How/why does it improve overall performance?


 * Maintains many database connections. Shared between the application clients

Using connection pools decreases access time to a DB and hence it improves execution times of applications which work with databases.

Note: Connection pooling is supported only on the Java 2 SDK, v 1.4.1, and later releases.

If you have used a SQL or other similar tool to connect to a database and act on the data, you probably know that getting the connection and logging in is the part that takes the most time. An application can easily spend several seconds every time it needs to establish a connection.

In releases prior to JDBC 2.0 every database session requires a new connection and login even if the previous connection and login used the same table and user account. If you are using a JDBC release prior to 2.0 and want to improve performance, you can cache JDBC connections instead.

Cached connections are kept in a runtime object pool and can be used and reused as needed by the application. One way to implement the object pool is to make a simple hashtable of connection objects. However, a more flexible way to do it is to write a wrapper JDBC Driver that is an intermediary between the client application and database.

The JDCConnectionPool.java class makes connections available to calling program in its getConnection method. This method searches for an available connection in the connection pool. If no connection is available from the pool, a new connection is created. If a connection is available from the pool, the getConnection method leases the connection and returns it to the calling program.

public synchronized Connection getConnection throws SQLException {

JDCConnection c; for(int i = 0; i < connections.size; i++) { c = (JDCConnection)connections.elementAt(i); if (c.lease) { return c;    } }

Connection conn = DriverManager.getConnection( url, user, password); c = new JDCConnection(conn, this); c.lease; connections.addElement(c); return c; }

The JDCConnection.java class represents a JDBC connection in the connection pool, and is essentially a wrapper around a real JDBC connection. The JDCConnection object maintains a state flag to indicate if the connection is in use and the time the connection was taken from the pool.

Question 16: class.forname
'''Explain what does “class.forname” does in general? ''' Class.forName("org.gjt.mm.mysql.Driver"); String dbURL = "jdbc:mysql://localhost:3306/murach"; this.conn = DriverManager.getConnection(dbURL, user, pwd );

But actually, the question she asks isn't the real question, since you could just say Class.forName(string param) dynamically creates an instance of the class specified. Class.forName("java.lang.Long") would create a new Long class. Same as saying new java.lang.Long. This lets us dynamically specify which class to load at runtime, not compile time.

The process breaks down like this : This is where the class.forName comes in Why does this work, so now JDBC knows about how to handle "mysql" Why use Class.forName at all?
 * the JDBC url contains a :mysql: section. This tells it which driver to load
 * the JDBC thingy looks in it's list of registered drivers for one to handle "mysql"
 * there is none there normally, so you ahve to load it
 * all Class.forName does it dynamically create an instance of a class from a string representing it's fully qualified name
 * You could create a new instance of that driver with a call to 'new org.gjt.mm.mysql.Driver, and it would still work
 * When the driver class is loaded it registers itself with JDBC as being able to handle "mysql" connections.
 * now when jdbc asks for "jdbc:mysql:..." it will create a new instance of mysql.Driver and set it's properties
 * well, the only real reason to use it is so you can put the "org.gjt.mm.mysql.Driver" string in a config file somewhere and change it if you need to

ALTERNATIVE: Alex's simple answer:

Class.ForName initializes the class indicated inside the parameter, in the code example above, it initializes the org.gjt.mm.mysql.Driver class.

Question 17 - Java Bean
What is Java Bean – what is requirement to be classified as JavaBean?

Answer:

- A reusable component that can be used in any Java application development environment. JavaBeans are dropped into an application container, such as a form, and can perform functions ranging from a simple animation to complex calculations.

added by tanya: this might be a more complete answer about the requirement The required conventions are:
 * The class should be serializable (able to persistently save and restore its state)
 * It should have a no-argument constructor
 * Its properties should be accessed using get, set and is methods that follow a standard naming convention
 * It should contain any required event-handling methods

Question 18- tag library
What is Tag Library? JavaServer Pages technology, actions are elements that can create and access programming language objects and affect the output stream. The JSP specification defines 6 standard actions that must be provided by any compliant JSP implementation.

In addition to the standard actions, JSP v1.1 technology supports the development of reusable modules called custom actions. A custom action is invoked by using a custom tag in a JSP page. A tag library is a collection of custom tags.

What is the major advantages of using Tag Libraries (list three)

Why build and use JSP tags?

Following are some of the uses which to mind :

* Tags allow separation of Java ( server-side ) and HTML ( client-side ) code. Very important when you are building big projects and have separate people for client and server-side development. * Tags allow easy reuse of Java code.

* You can build and pack a custom tag library with useful functions and provide it to the end-user.

* Due to their ease of use tags can be used by non-Java programmers e.g. HTML developers.

* Tags are easier to maintain. You don't have to edit every JSP page when you want to make a change, just change the JSP tag and change will be manifested by all the JSP pages.

ALTERNATIVE Alex-type answer:

A tag library is an easier way of using different java code inside JSPs to help organize code clutter. Instead of having scriptlets all over the page, we can customize tags to call java code instead of having the direct java code there. This also enables other jsps to use the same code without having to use the same scriplets all over.

Decreases code clutter

Improves reuse of java code.

Reduces maintenance of code

Easier on web designers who don’t know Java.

Question 19- more on tag libraries

 * Tag is compiled into a jar (or built into the project)
 * If it is a jar, it needs to be /WEB-INF/lib directory

taglib> 2.0    1.1     My Tag http://my.url.if.I.need.it/tld.html HTML select tag for states fireBox com.hollywood.fireBox My drowndown box for running with the devil name (this corresponds to getName/setName on object) true true (are expr's like ${invoice.total} are allowed?
 * A tag libray is created (.tls) with something like this format which describes the paramters and their types/possible values:

<%@ taglib uri="/WEB-INF/mytaglib.tld" prefix="minedammit" %> <minedammit:fireBox name="nicole" .../>
 * These tag libs can be placed anywhere, but gnerally they are put in /WEB-INF/ or in /tld
 * Then you reference the tag library the standard way in the header
 * Then you use it, genius
 * Bada-bing

ALTERNATIVE:

First, we would have to write a java class that defines the procedure of what we want our tag to do.

Then we would also have to create a tag library definition which then gives our java class a name and what required parameters are necessary when using our tag.

Then finally, we would include the tag library file which has our tag names into the .jsp page with the jsp directive <%@ taglib uri="../WEB-INF/someTabLib.tld" prefix="myTag" %>

Then in the jsp, we would simply use: <myTag : functionToUse /> for example.

Question 20 - MVC model
What is MVC model? What does each letter mean? Discuss how it is used in your term project.

Alex version:

Model - The backend.. DB, system configuration file(s)..

View - What a user would see to interact with the application.

Controller - The logic invoked by the "View" model to communicate between the "Model" and "View";


 * Model - The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model.


 * View -The view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented. It is the view's responsibility to maintain consistency in its presentation when the model changes. This can be achieved by using a push model, where the view registers itself with the model for change notifications, or a pull model, where the view is responsible for calling the model when it needs to retrieve the most current data.


 * Controller - The controller translates interactions with the view into actions to be performed by the model. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas in a Web application, they appear as GET and POST HTTP requests. The actions performed by the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view.

andrew's answer

 * Model
 * Generally represents the data/backend junk. It is what is passed by the biz layer (actions/etc) to the views to render.  The views do not need to know how these objects get to them, only that they are there.
 * View
 * A (theoretcially) decoupled view of a model. This could be a web page or a normal java applet.
 * Controller
 * The thing that sits in the back and handles user requests. It :
 * accepts a request
 * does data access/manipulation (gets list of orders, delete customer,etc)
 * puts any results that are needed by the view into a container (usually request object)
 * invokes/notifies the view there is new data

A related topic is the concept of an 'action'. An action can be the whole controller, or just part of one. Most MVC frameworks that aren't insane use a controller/action model, where there is one conroller (module) with many methods (actions) that are called. For instance, http://host/user/update would call the 'update' action on the 'user' contoller.

Our Project implementation use the MVC strategy as follows:

JavaServer Pages to render the view, Servlet as the controller, and Enterprise JavaBeansTM (EJBTM) components as the model. The Job Center application illustrates this strategy.

Question 21 WSDL
What is “web services”? How are UDDI or WSDL used to support web services?

From presentation slides:

A web service is any service that is available over the internet, uses a standardized XML messaging system, and is not tied to any one operating system or programming language.

WSDL Web Service Description Language :

-In a nutshell, WSDL is an XML grammar for specifying a public interface for a web service. This public interface can include information on all publicly available functions, data type information for all XML messages, address information for locating the specified service. WSDL is not tied to a specific XML messaging system and it also includes built-in extensions for describing SOAP services.

-Allows developers to describe the ‘functional’ characteristics of a Web service—what actions or functions the service performs in terms of the messages it receives and sends. It consists of two parts: A reusable abstract part that describes the operational behavior of Web services by recounting the messages that go in and out from services A concrete part that allows you to describe how and where to access a service implementation

UDDI Universal Description, Discovery and Integration :

UDDI was created by Microsoft, IBM and Ariba. UDDI consists of two parts: First UDDI is a technical specification for building a distributed directory of businesses and web services. Data is stored within a specific XML format. Second The UDDI Business registry is a fully operational implementation of the UDDI specification.

Data captured within UDDI is divided into three main categories: White Pages includes general information about a specific company. Yellow Pages includes general classification data for either the company or the service offered. Green Pages includes technical information about a web service.

Question 22: security

 * Host Security
 * Securing the acutal computer that the web site is on
 * Host-based security is also allowing only certain trusted computers to connect to your network. This means that only the computers in your DMZ (your web servers) are even allowed to connect to your database server.  This prevents people from hacking your database server directl.


 * Web Service Security
 * WS-Security, possibly? A suite of extensible standards that let you encrypt soap packets, pass authentication and authorization information, etc.


 * Web Application Security
 * Not sure what she means by this, as usual. Perhaps she means
 * User authentication on web applicatoins
 * Prevention of cross site scripting (injecting bad javascript into the site, ie in a product description)
 * Avoiding SQL injection attacks

Question 23 AJAX
What is "AJAX"? What are advantages of using AJAX and What are possible risks?

Answer:

Ajax is the method of using Javascript, DHTML and the XMLHttpRequest object to perform a GET or POST and return a result without reloading the HTML page.

Advantages of Using AJAX:

The AJAX technique makes web pages more responsive by exchanging data with a server behind the scenes, instead of reloading an entire web page each time a user makes a change.

With AJAX, web applications can be faster, more interactive, and more user friendly.


 * Rich User Interface
 * Ajax allows us to create highly interactive user interface. A user don’t like page refresh continuously. In Ajax, we can do lot of things without any page refresh. Ajax is crossing the barriers between windows applications and web applications. Ajax communities are fans of rich user interface.
 * High Performance
 * Another advantage of Ajax is better performance than traditional web applications. In the Ajax applications there will be no post back to the server that will render entire GUI as HTML. Ajax request is only for page data. So it enable us better performance.

The possible risks: The main risk of Ajax is it’s complexity for implementation.Developers have to write complex JavaScript code for implementing Ajax. If your company has good expertise in writing JavaScript code, you can start Ajax enabled applications.

Browsers may have JavaScript and/or XML display/parsing issues, so the intended application may not work correctly (if at all) on all browsers. Browser hacks will have to be implemented to work around these issues.

Something Extra - AJAX Tutorial For Fun http://javascript.internet.com/ajaxTutorials/

Question 15: how does prepared statements improve performance of e-commerce websites?
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html

The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement's SQL statement without having to compile it first.

e.g. we have a function which updates data in a database table:

public void updateData(UserBean user, int id) throws Exception { String sqlstmt = "delete from user where id = " + id; this.update = this.con.prepareStatement(sqlstmt); this.update.executeUpdate; this.update = this.con.prepareStatement (" INSERT INTO user (id, userid, password)" +                        " VALUES(?,?,?)"); this.update.setInt( 1, user.getId); this.update.setString( 2, user.getUserid ); this.update.setString( 3, user.getPassword ); this.update.executeUpdate; }

Summary:

Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Also these statements can take parameters and we can use the same statement and supply it with different values each time you execute it. These are big advantages for e-commerce websites because they access databases very often.