Talk:CSC667 final

Question 1: Explain the terms below
(a) Cookie (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=ExpiresDate; path = PATH

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

(b) Session (explain what it is and how it is implemented)

A session is data that is stored by the server which is tied to a particular client and can span multiple connections. It is usually implemented as a key stored in a cookie which gives access to the server.

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.

(c) 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 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

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.

(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.

(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.

(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.

3. Session tracking using Servlet or JSP
(a) How to create a Session in Servlet? (Show an example using actual codes.)

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. Set cookie using servlet:

// set a cookie

String name = request.getParameter ("cookieName");

if (name != null && name.length > 0) {

String value = 			request.getParameter("cookieValue");

Cookie c = new Cookie(name, value);

response.addCookie(c);}}}

Get Cookie

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class CookieExample extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException

{ response.setContentType("text/html");

PrintWriter out = response.getWriter;

// print out cookies

Cookie[] cookies = request.getCookies;

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

Cookie c = cookies[i];String name = c.getName;

String value = c.getValue;

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.

(b) How to store information (shopping cart – ordered items) into the session and retrieve back? When explicit casting is used and why?

(c) What happens if session expires or a client kills the browser? What can you do to prevent possible loss of information?

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)

 

 // (b)

 <% String display = "showLogin.html"; User user = loginBean.authenticate; if (user != null) { user.setIpAddr(request.getRemoteHost); session.setAttribute("user", user); // (c) //

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

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) look up a previously stored value of "user" and check if it is null, if null, redirect the page to "showlogin.html"'''

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

// (b) set "user" object to the stored value of "user" from previous page'''

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" 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 in a session for shopping cart to the value "anOrder" for further use'''

} 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 default page that was set"showDetails.jsp"'''

%> (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

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

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

All the different scopes behave as a single name space

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

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

(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

(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.

6. XML
(a) Explain what is validity and well-formness rules in XML.

(b) What are the advantages of using XML (list 3)

(c) Explain the difference of DOM and SAX parser

(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>

(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. (f) What is XSLT? How XSLT is used with XML?

(h) What would be results of executing XSLT below with hyper link connection to a given xml file?

 

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>

. 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?)

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

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

10. With a given XML file, show a DOM structure returned by DOM parser.
ABCCDEAbout tomorrow

 Hello Test

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?

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)

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

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.

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

Maintain many database connections Shared between the application clients

Question 15: prepared statements
How does prepared statement improve the performance of e-commerce applications? (Show using an example code)

Question 16: class.forname
. Explain what does “class.forname” do in general? (A code is given below to help you refresh your memory. Explanation could be related to it, but doesn’t have to because the example below doesn’t make good use of the original intention of class.forname of java)

Class.forName("org.gjt.mm.mysql.Driver");

String dbURL = "jdbc:mysql://localhost:3306/murach";

String username = "root"; String password = "";

Answer:

One of Java's strongest features is its ability to dynamically load code given the name of the class to load, without having to know the actual classname until runtime. This allows Java developers to build flexible, dynamic systems that can grow and change without requiring complete recompilation.

Loading Classes Dynamically from within Extensions.

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

A Java Bean is reusable software component.

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.

Question 19- more on tag libraries
Please explain how tag library is deployed. Explain step by step – how it is used in jsp page, what needs to be defined, how actual java codes are created by extending which class, etc. How and where the relation/association between the java class (tag handler class) and the tag names needs to be defined.

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

* 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.

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
Explain about “Host Security”, Web Service Security”, “Web Application Security”

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.

1.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.

2. 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.