Sunteți pe pagina 1din 57

1.

2.

3.

What makes J2EE suitable for distributed multitiered Applications? - The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are: o Client-tier components run on the client machine. o Web-tier components run on the J2EE server. o Business-tier components run on the J2EE server. o Enterprise information system (EIS)-tier software runs on the EIS server. What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications. What are the components of J2EE application? - A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components: Application clients and applets are client components. 2. Java Servlet and JavaServer Pages technology components are web components. 3. Enterprise JavaBeans components (enterprise beans) are business components. 4. Resource adapter components provided by EIS and tool vendors. What do Enterprise JavaBeans components contain? Enterprise JavaBeans components contains Business code,
1.

2.

3.

4.

5.

which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program. Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier. Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture. Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web

components by the J2EE specification. Even the server-side utility classes are not considered web components, either. 6. What can be considered as a web component? - J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content. 7. What is the container? - Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container. 8. What are container services? - A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading. 9. What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server. 10. What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications. Enterprise beans and their container run on the J2EE server. 11. What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together. 12. How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and

added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a components deployment settings. 13. What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications. 14. What are types of J2EE clients? - Following are the types of J2EE clients:
o o o

Applets Application clients Java Web Start-enabled rich clients, powered by Java Web Start technology. Wireless clients, based on Mobile Information Device Profile (MIDP) technology.

4.

What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a components deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.

5.

6.

7.

8.

What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file. What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesnt call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesnt directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA. What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations. What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is

typically a different resource adapter for each type of database or enterprise information system. 9. What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization. 10. What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS. 11. What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between. 12. How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an applications business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between

the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans. 13. What is the difference between URL instance and URLConnection instance? - A URL instance represents the location of a resource, and a URLConnection instance represents a link for accessing or communicating with the resource at the location. 14. What are the two important TCP Socket classes? - Socket and ServerSocket. ServerSocket is used for normal two-way socket communication. Socket class allows us to read and write through the sockets. getInputStream() and getOutputStream() are the two methods available in Socket class. 15. What technologies are included in J2EE? - The primary technologies in J2EE are: Enterprise JavaBeansTM (EJBsTM), JavaServer PagesTM (JSPsTM), Java Servlets, the Java Naming and Directory InterfaceTM (JNDITM), the Java Transaction API (JTA), CORBA, and the JDBCTM data access API. 16. What is the Java Authentication and Authorization Service (JAAS) 1.0? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. JAAS is a Java programing language version of the standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization. 17. Whats the difference between JNDI lookup(), list(), listBindings(), and search()? - lookup() attempts to find the specified object in the given context. I.e., it looks for a single, specific object and either finds it in the current context or it

fails. list() attempts to return an enumeration of all of the NameClassPairs of all of the objects in the current context. I.e., its a listing of all of the objects in the current context but only returns the objects name and the name of the class to which the object belongs. listBindings() attempts to return an enumeration of the Bindings of all of the objects in the current context. I.e., its a listing of all of the objects in the current context with the objects name, its class name, and a reference to the object itself. search() attempts to return an enumeration of all of the objects matching a given set of search criteria. It can search across multiple contexts (or not). It can return whatever attributes of the objects that you desire. Its by far the most complex and powerful of these options but is also the most expensive. 18. Components of JNDI - Naming Interface- The naming interface organizes information hierarchically and maps human-friendly names to addresses or objects that are machine-friendly. It allows access to named objects through multiple namespaces. Directory Interface - JNDI includes a directory service interface that provides access to directory objects, which can contain attributes, thereby providing attribute-based searching and schema support. Service Provider Interface - JNDI comes with the SPI, which supports the protocols provided by third parties. 19. What is the Max amount of information that can be saved in a Session Object? - As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier), which should not exceed more than 4K. If the data to be store is very huge, then its preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk.

20. Must

my bean-managed persistence mechanism use the WebLogic JTS driver? - BEA recommend that you use the TxDataSource for bean-managed persistence. 21. Do EJBs have to be homogeneously deployed across a cluster? Why? - Yes. Beginning with WebLogic Server version 6.0, EJBs must be homogeneously deployed across a cluster for the following reasons:
o o

o o

To keep clustering EJBs simple To avoid cross server calls which results in more efficiency. If EJBs are not deployed on all servers, cross server calls are much more likely. To ensure that every EJB is available locally To ensure that all classes are loaded in an undeployable way Every server must have access to each EJBs classes so that it can be bound into the local JNDI tree. If only a subset of the servers deploys the bean, the other servers will have to load the beans classes in their respective system classpaths which makes it impossible to undeploy the beans.

22. Is

an XSLT processor bundled in WebLogic Server? Yes, an XSLT processor, based on Apaches Xalan 2.0.1 processor, in WebLogic Server 6.1. 23. I plugged in a version of Apache Xalan that I downloaded from the Apache Web site, and now I get errors when I try to transform documents. What is the problem? - You must ensure that the version of Apache Xalan you download from the Apache Web site is compatible with Apache Xerces version 1.3.1. Because you cannot plug in a different version of Apache Xerces , the only version of Apache Xerces that is compatible with WebLogic Server 6.1 is 1.3.1. The built-in parser (based on version 1.3.1 of Apache Xerces) and

transformer (based on version 2.0.1 of Apache Xalan) have been modified by BEA to be compatible with each other. 24. How do I increase WebLogic Server memory? - Increase the allocation of Java heap memory for WebLogic Server. (Set the minimum and the maximum to the same size.) Start WebLogic Server with the -ms32m option to increase the allocation, as in this example: 25. $ java ... -ms32m -mx32m ... This allocates 32 megabytes of Java heap memory to WebLogic Server, which improves performance and allows WebLogic Server to handle more simultaneous connections. You can increase this value if necessary.
26. What

causes Java.io exceptions in the log file of WebLogic Server? - You may see messages like these in the log file:

(Windows NT) java.io.IOException Connection Reset by Peer java.io.EOFException Connection Reset by Peer (Solaris) java.io.Exception: Broken pipe These messages occur when you are using servlets. A client initiates an HTTP request, and then performs a series of actions on the browser:
o o

Click Stop or enter equivalent command or keystrokes Click Refresh or enter equivalent command or keystrokes Send a new HTTP request.

The messages indicate that WebLogic Server has detected and recovered from an interrupted HTTP request.
27. What

is the function of T3 in WebLogic Server? - T3 provides a framework for WebLogic Server messages that support for enhancements. These enhancements include abbreviations and features, such as object replacement, that work in the context of WebLogic Server clusters and HTTP and other product tunneling. T3 predates Java Object Serialization and RMI, while closely tracking and leveraging these specifications. T3 is a superset of Java Object. Serialization or RMI; anything you can do in Java Object Serialization and RMI can be done over T3. T3 is mandated between WebLogic Servers and between programmatic clients and a WebLogic Server cluster. HTTP and IIOP are optional protocols that can be used to communicate between other processes and WebLogic Server. It depends on what you want to do. For example, when you want to communicate between a browser and WebLogic Server-use HTTP, or an ORB and WebLogic Server-IIOP. 28. What are the enhancements in EJB 2.0 specification with respect to Asynchronous communication? - EJB 2.0 mandates integration between JMS and EJB. We have specified the integration of Enterprise JavaBeans with the Java Message Service, and have introduced message-driven beans. A message-driven bean is a stateless component that is invoked by the container as a result of the arrival of a JMS message. The goal of the message-driven bean model is to make developing an enterprise bean that is asynchronously invoked to handle the processing of incoming JMS messages as simple as developing the same functionality in any other JMS MessageListener. 29. What are the enhancements in EJB 2.0 with respect to CMP? - EJB 2.0 extends CMP to include far more robust modeling capability, with support for declarative

management of relationships between entity EJBs. Developers no longer need to re-establish relationships between the various beans that make up their application the container will restore the connections automatically as beans are loaded, allowing bean developers to navigate between beans much as they would between any standard Java objects. EJB 2.0 also introduces for the first time a portable query language, based on the abstract schema, not on the more complex database schema. This provides a database and vendor-independent way to find entity beans at run time, based on a wide variety of search criteria. 30. Can you briefly describe local interfaces? - EJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally - that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence. 31. What are the special design care that must be taken when you work with local interfaces? - It is important to understand that the calling semantics of local interfaces are

different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision. 32. What happens if remove( ) is never invoked on a session bean? - In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool. 33. What is the difference between creating a distributed application using RMI and using a EJB architecture? - It is possible to create the same application using RMI and EJB. But in case of EJB the container provides the requisite services to the component if we use the proper syntax. It thus helps in easier development and lesser error and use of proven code and methodology. But the investment on application server is mandatory in that case. But this investment is warranted because it results in less complex and maintainable code to the client, which is what the end client wants. Almost all the leading application servers provide load balancing and performance tuning techniques. In case of RMI we have to code the services and include in the program the way to invoke these services.

34. Why

would a client application use JTA transactions? One possible example would be a scenario in which a client needs to employ two (or more) session beans, where each session bean is deployed on a different EJB server and each bean performs operations against external resources (for example, a database) and/or is managing one or more entity beans. In this scenario, the clients logic could required an all-or-nothing guarantee for the operations performed by the session beans; hence, the session bean usage could be bundled together with a JTA UserTransaction object. In the previous scenario, however, the client application developer should address the question of whether or not it would be better to encapsulate these operations in yet another session bean, and allow the session bean to handle the transactions via the EJB container. In general, lightweight clients are easier to maintain than heavyweight clients. Also, EJB environments are ideally suited for transaction management. Context c = new InitialContext(); UserTransaction ut = (UserTransaction) c.lookup("java:comp/UserTransaction"); ut.begin(); // perform multiple operations... ut.commit() ...

35. Can

the bean class implement the EJBObject class directly? If not why? - It is better not to do it will make the Bean class a remote object and its methods can be accessed without the containers? security, and transaction implementations if our code by mistake passed it in one of its parameters. Its just a good design practice. 36. What does isIdentical() method return in case of different type of beans? - Stateless - true always. Stateful - depends whether the references point to the same session object.

Entity - Depends whether the primary key is the same and the home is same. 37. How should you type cast a remote object? Why? - A client program that is intended to be interoperable with all compliant EJB Container implementations must use the javax.rmi.PortableRemoteObject.narrow() method to perform type-narrowing of the client-side representations of the remote home and remote interfaces. Programs using the cast operator for narrowing the remote and remote home interfaces are likely to fail if the Container implementation uses RMI-IIOP as the underlying communication transport. 38. What should you do in a passive method? - You try to make all nontransient variables, which are not one of the following to null. For the given list the container takes care of serializing and restoring the object when activated. Serializable objects, null, UserTransaction, SessionContext, JNDI contexts in the beans context, reference to other beans, references to connection pools. Things that must be handled explicitly are like a open database connection etc. These must be closed and set to null and retrieved back in the activate method. 1. What is XML? XML is the Extensible Markup Language. It improves the functionality of the Web by letting you identify your information in a more accurate, flexible, and adaptable way. It is extensible because it is not a fixed format like HTML (which is a single, predefined markup language). Instead, XML is actually a meta languagea language for describing other languageswhich lets you design your own markup languages

for limitless different types of documents. XML can do this because its written in SGML, the international standard meta language for text document markup (ISO 8879). 2. What is a markup language? A markup language is a set of words and symbols for describing the identity of pieces of a document (for example this is a paragraph, this is a heading, this is a list, this is the caption of this figure, etc). Programs can use this with a style sheet to create output for screen, print, audio, video, Braille, etc. What is the query used to display all tables names in SQL Server (Query analyzer)? 2. select * from information_schema.tables 3. How many types of JDBC Drivers are present and what are they?- There are 4 types of JDBC Drivers o JDBC-ODBC Bridge Driver o Native API Partly Java Driver o Network protocol Driver o JDBC Net pure Java Driver 4. Can we implement an interface in a JSP?- No 5. What is the difference between ServletContext and PageContext?- ServletContext: Gives the information about the container. PageContext: Gives the information about the Request 6. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource,
1.

context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource. 7. How to pass information from JSP to included JSP?Using <%jsp:param> tag. 8. What is the difference between directive include and jsp include?- <%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime. 9. What is the difference between RequestDispatcher and sendRedirect?- RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects. 10. How does JSP handle runtime exceptions?- Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP. 11. How do you delete a Cookie within a JSP? 1. Cookie mycook = new Cookie("name","value"); 2. response.addCookie(mycook); 3. Cookie killmycook = new Cookie("mycook","value"); 4. killmycook.setMaxAge(0); 5. killmycook.setPath("/"); 6. killmycook.addCookie(killmycook); 12. How do I mix JSP and SSI #include?- If youre just including raw HTML, use the #include directive as usual inside your .jsp file. <!--#include file="data.inc"--> But its a little trickier if you want the server to evaluate any JSP code thats inside the included file. If your data.inc file contains jsp code you will have to use <%@ vinclude="data.inc" %>

The <!#include file="data.inc"> is used for including nonJSP files.


13. I

made my class Cloneable but I still get Cant access protected method clone. Why?- Some of the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but thats not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesnt do anything special and just calls super.clone(). 14. Why is XML such an important development?- It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for. 15. What is the fastest type of JDBC driver?- JDBC driver performance will depend on a number of issues: o the quality of the driver code, o the size of the driver code, o the database server and its load, o network topology, o the number of times your request is translated to a different API. In general, all things being equal, you can assume that the more your request and response change hands, the slower it will be. This means that Type 1 and Type 3 drivers will be slower than Type 2 drivers (the database calls are make at

least three translations versus two), and Type 4 drivers are the fastest (only one translation).
16. How

do I find whether a parameter exists in the request object?

boolean hasFoo = ! (request.getParameter("foo") == null || request.getParameter("foo").equals("")); or boolean hasParameter = request.getParameterMap().contains(thePar ameter); //(which works in Servlet 2.3+)
17. How

can I send user authentication information while makingURLConnection?- Youll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization. 18. What are the steps involved in establishing a JDBC connection? This action involves two steps: loading the JDBC driver and making the connection. 19. How can you load the drivers? Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it: Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line of code:

Class.forName(jdbc.DriverXYZ);
20. What

will Class.forName do while loading drivers? It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS. 21. How can you make the connection? To establish a connection you need to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea: String url = jdbc:odbc:Fred; Connection con = DriverManager.getConnection(url, Fernanda, J8?);
22. How

can you create JDBC statements and what are they? A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object Statement stmt = con.createStatement();

23. How

can you retrieve data from the ResultSet? JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

ResultSet rs = stmt.executeQuery(SELECT COF_NAME, PRICE FROM COFFEES); String s = rs.getString(COF_NAME); The method getString is invoked on the ResultSet object rs, so getString() will retrieve (get) the value stored in the column COF_NAME in the current row of rs.
24. What

are the different types of Statements? Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall) 25. How can you use PreparedStatement? This special type of statement is derived from class Statement.If you need a Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. 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 PreparedStatements SQL statement without having to compile it first. 26. PreparedStatement updateSales = 27. con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); 28. What does setAutoCommit do? When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:

con.setAutoCommit(false); Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly. con.setAutoCommit(false); PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); updateSales.setInt(1, 50); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(); PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); con.commit(); con.setAutoCommit(true);
29. How

do you call a stored procedure from JDBC? The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery();


30. How

do I retrieve warnings? SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the

execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object: SQLWarning warning = stmt.getWarnings(); if (warning != null) { System.out.println("n---Warning--n"); while (warning != null) { System.out.println("Message: " + warning.getMessage()); System.out.println("SQLState: " + warning.getSQLState()); System.out.print("Vendor error code: "); System.out.println(warning.getErrorCode() ); System.out.println(""); warning = warning.getNextWarning(); } }
31. How

can you move the cursor in scrollable result sets? One of the new features in the JDBC 2.0 API is the ability to move a result sets cursor backward as well as forward. There

are also methods that let you move the cursor to a particular row and check the position of the cursor. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIV E, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery(SELECT COF_NAME, PRICE FROM COFFEES); The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
32. Whats

the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE? You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can

be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened: Statement stmt = con.createStatement(ResultSet.TYPE_SCROL L_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES"); srs.afterLast(); while (srs.previous()) { String name = srs.getString("COF_NAME"); float price = srs.getFloat("PRICE"); System.out.println(name + " " + price); }
33. How

to Make Updates to Updatable Result Sets? Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.

Connection con = DriverManager.getConnection("jdbc:mySubpr otocol:mySubName"); Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL _SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet uprs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES"); What is JMS? A: JMS is an acronym used for Java Messaging Service. It is Java's answer to creating software using asynchronous messaging. It is one of the official specifications of the J2EE technologies and is a key technology. How JMS is different from RPC? A: In RPC the method invoker waits for the method to finish execution and return the control back to the invoker. Thus it is completely synchronous in nature. While in JMS the message sender just sends the message to the destination and continues it's own processing. The sender does not wait for the receiver to respond. This is asynchronous behavior. What are the advantages of JMS? A: JMS is asynchronous in nature. Thus not all the pieces need to be up all the time for the application

to function as a whole. Even if the receiver is down the MOM will store the messages on it's behalf and will send them once it comes back up. Thus at least a part of application can still function as there is no blocking. What are the different types of messages available in the JMS API? A: Message, TextMessage, BytesMessage, StreamMessage, ObjectMessage, MapMessage are the different messages available in the JMS API. What is the difference between topic and queue? A: A topic is typically used for one to many messaging i.e. it supports publish subscribe model of messaging. While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging. What is the role of JMS in enterprise solution development? A: JMS is typically used in the following scenarios 1. Enterprise Application Integration: - Where a legacy application is integrated with a new application via messaging. 2. B2B or Business to Business: - Businesses can interact with each other via messaging because JMS allows organizations to cooperate without tightly coupling their business systems. 3. Geographically dispersed units: - JMS can ensure safe exchange of data amongst the geographically dispersed units of an organization.

4. One to many applications: - The applications that need to push data in packet to huge number of clients in a one-to-many fashion are good candidates for the use JMS. Typical such applications are Auction Sites, Stock Quote Services etc. What is the difference between BytesMessage and StreamMessage?? A: BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read. What is Struts? A: The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on

the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm. Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems. The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns. What is Struts Validator Framework? A: Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the

Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings. What are the different kinds of enterprise beans? A: Stateless session bean- An instance of these nonpersistent EJBs provides a service without storing an interaction or conversation state between methods. Any instance can be used for any client. Stateful session bean- An instance of these non-persistent EJBs maintains state across methods and transactions. Each instance is associated with a particular client. Entity bean- An instance of these persistent EJBs represents an object view of the data, usually rows in a database. They have a primary key as a unique identifier. Entity bean persistence can be either container-managed or bean-managed. Message-driven bean- An instance of these EJBs is integrated with the Java Message Service (JMS) to provide the ability for message-driven beans to act as a standard JMS message consumer and perform asynchronous processing between the server and the JMS message producer. What are the methods of Entity Bean?What is the difference between Container-Managed Persistent (CMP) bean and Bean-Managed Persistent(BMP) ?

A: Container-managed persistence beans are the simplest for the bean developer to create and the most difficult for the EJB server to support. This is because all the logic for synchronizing the bean's state with the database is handled automatically by the container. This means that the bean developer doesn't need to write any data access logic, while the EJB server is supposed to take care of all the persistence needs automatically. With CMP, the container manages the persistence of the entity bean. A CMP bean developer doesn't need to worry about JDBC code and transactions, because the Container performs database calls and transaction management instead of the programmer. Vendor tools are used to map the entity fields to the database and absolutely no database access code is written in the bean class. All table mapping is specified in the deployment descriptor. Otherwise, a BMP bean developer takes the load of linking an application and a database on his shoulders. The bean-managed persistence (BMP) enterprise bean manages synchronizing its state with the database as directed by the container. The bean uses a database API to read and write its fields to the database, but the container tells it when to do each synchronization operation and manages the transactions for the bean automatically. Beanmanaged persistence gives the bean developer the flexibility to perform persistence operations that are too complicated for the container or to use a data source that is not supported by the container.BMP beans are not 100% database-independent, because

they may contain database-specific code, but CMP beans are unable to perform complicated DML (data manipulation language) statements. EJB 2.0 specification introduced some new ways of querying database (by using the EJB QL - query language). Explain the life cycle methods of a Servlet. A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method. public void init(ServletConfig config) throws ServletException public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy() First the servlet is constructed, then initialized wih the init() method. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized. Explain the directory structure of a web application. A: The directory structure of a web application consists of two parts. A private directory called WEB-INF A public resource directory which contains public resource folder.

WEB-INF folder consists of 1. web.xml 2. classes directory 3. lib directory What are the common mechanisms used for session tracking? A: Cookies SSL sessions URL- rewriting Explain ServletContext. A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application. What is preinitialization of a servlet? A: A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any

request comes in is called preloading or preinitializing a servlet. What is the difference between Difference between doGet() and doPost()? A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1? p1=v1&p2=v2&...&pN=vN doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string What is the difference between HttpServlet and GenericServlet? A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract. What is the difference between ServletContext and ServletConfig? A: ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a

file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet. Jsp What is a Hidden Comment? A: A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page. You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>. JSP Syntax <%-- comment --%> Examples <%@ page language="java" %> <html> <head><title>A Hidden Comment </title></head>

<body> <%-- This comment will not be visible to the colent in the page source --%> </body> </html> What is a Expression? A: An expression tag 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 text in a JSP file. Like <%= someexpression %> <%= (new java.util.Date()).toLocaleString() %> You cannot use a semicolon to end an expression What is a Declaration? A: A declaration declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file. <%! somedeclarations %> <%! int i = 0; %> <%! int a, b, c; %>

What is a Scriptlet? A: A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can 1.Declare variables or methods to use later in the file (see also Declaration). 2.Write expressions valid in the page scripting language (see also Expression). 3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag. You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it. What are implicit objects? List them? A: Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below request response pageContext session

application out config page exception

Explain the life-cycle mehtods in JSP? A: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService(). The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance. The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects. The jspDestroy()- The container calls this when it

decides take the instance out of service. It is the last method called n the servlet instance. How can I enable session tracking for JSP pages if the browser has disabled cookies? A: We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was

earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting. hello1.jsp <%@ page session=\"true\" %> <% Integer num = new Integer(100); session.putValue("num",num); String url =response.encodeURL("hello2.jsp"); %> <a href=\'<%=url%>\'>hello2.jsp</a> hello2.jsp <%@ page session="true" %> <% Integer i= (Integer )session.getValue("num"); out.println("Num value in session is " + i.intValue()); %> What is JavaScript? Javascript is an easy-to-use programming language that can be embedded in the header of your web pages. It can enhance the dynamics and interactive features of your page by allowing you to

perform calculations, check forms, write interactive games, add special effects, customize graphics selections, create security passwords and more. What's the difference between JavaScript and Java? Actually, the 2 languages have almost nothing in common except for the name. Although Java is technically an interpreted programming language, it is coded in a similar fashion to C++, with separate header and class files, compiled together prior to execution. It is powerful enough to write major applications and insert them in a web page as a special object called an "applet." Java has been generating a lot of excitment because of its unique ability to run the same program on IBM, Mac, and Unix computers. Java is not considered an easy-to-use language for nonprogrammers. Javascript is much simpler to use than Java. With Javascript, if I want check a form for errors, I just type an if-then statement at the top of my page. No compiling, no applets, just a simple sequence. Calculator examples These are examples of forms that do not send any data to the server but tries to do a useful operation in the browser itself. <SCRIPT> function doCalculate() { var val1, val2 var result val1 = parseInt(document.calcForm.val1.value) val2 = parseInt(document.calcForm.val2.value) if (document.calcForm.op[0].checked) {

result = val1 + val2 } else { result = val1 - val2 } document.calcForm.result.value = result } </SCRIPT> <FORM NAME="calcForm"> Value 1:<INPUT TYPE=text NAME="val1" SIZE=6><P> Add:<INPUT TYPE=radio NAME="op" VALUE="plus"> Subtract:<INPUT TYPE=radio NAME="op" VALUE="minus"><BR> Value 2:<INPUT TYPE=text NAME="val2" SIZE=6><BR> Result:<INPUT TYPE=text NAME="result" SIZE=10><BR> <INPUT TYPE=button NAME="calculate" VALUE="Calculate" onClick="doCalculate()"> </FORM>
1.

Tags. The tags are instructions (directions) embedded in .html files used by the browsers to decide how to display the subsequent contents of the document. When a tag comes in a pair, i.e. with corresponding beginning and ending tags, the instruction encoded by the beginning tag concerns the (hyper)text enclosed between the pair: <b> Dear friends, </b>

2.

Tag attributes and tag attribute values. Every tag consists of a tag name, optionally followed by a list of attributes with

corresponding values, all placed between left and right angle brackets (< and >). The ending tag names consist of the name of the corresponding starting tag preceded by a slash. Tag attributes are written after the tag name and separated by space. Some of the attributes take values. A tag attribute value is written after an equal sign (=) following the attribute name. For example: <hr size=6 width="30%" noshade> hr is the name of the tag; size, width, noshade are attributes; size and width require values, noshade does not take any value. Structure of a web page Head <head> <title> Title of the browser window! </title> </head> Body <body> Here you put the text (incl. links) you want to be viewed in the web page. You use tags, and tag attributes with appropriate values to give structure of the content of your document. ..... ..... </body> Tables Border Lines in Tables

The attributes border, cellspacing and cellpadding are optional for the <table> tag.

The attribute border tells the browser to draw border lines around the table and its cells. Without it, by default, the browser displays the table with no border lines. When used in isolation with a number value, the attribute border creates the outside border lines with the specified size. If you do not include cellspacing and cellpadding attributes, these are set to 1 pixel. If you include border with no value, the browser draws the border lines with default values depending on the browser. The value of the cellspacing attribute controls the size of the space between adjacent cells, and along the outer edges of the cells along the outer sides of a table. The cellpadding attribute controls the amount of space between the edges of a cell and its contents (the text that you put inside a cell).

Combining border, cellspacing and cellpadding attributes

By default the value of the cellspacing attribute is 1 pixel, which means that if you do not include this attribute, the text will be pretty close to the borders of the cells. If you put cellpadding=0, you get the contents in the cells touching their respective cell borders. The choice cellpadding=5 gives pretty aesthetic result when you do not need some extra space around the contents of the cell.

The most common combinations of the border and cellspacing attributes:

If you use border with no value and together with cellspacing, the cell spacing grows by 2 pixels. border=1 cellspacing=0 produces the narrowest interior and exterior borders: 2 pixels wide border lines. Example border=n cellspacing=0 produces the narrowest interior borders (2 pixels wide), with an external border that is n+1 pixels wide. You have to choose a particular number n. For example, you will get external border 5 pixels wide, and the internal borders 2 pisels, if you have (Example) : border=4 cellspacing=0

border=1 cellspacing=n produces equal-width interior and exterior borders, n+2 wide, all with chiseled edges 1 pixel wide. For example, you will get all borders 6 pixels wide if you have (Example) : border=1 cellspacing=4

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"> <html> <head> <title>Narrowest Table Borders</title> </head> <body> <!--

This is html creating a simple table with the narrowest borders! --> <h1>Narrowest Table Borders</h1> <table border=1 cellspacing=0 cellpadding=5>

<tr bgcolor="#808000"> <th> Lecture </th> <th> Day </th> <th> Date </th> <th> Lecture Topic</th> <th> Sections </th> <th> Assignment </th> </tr> <tr bgcolor="#EFDAAD"> <td> 1 </td> <td> Tuesday </td> <td> Aug 29 </td> <td> Lesson 1 </td> <td> 1.0-1.2 </td> <td> p. 9 #6-10 <br> 32, 45, 50, 52 <br> </td> </tr> <tr bgcolor="#EFDAAD"> <td> 2 </td> <td> Thursday </td> <td> Aug 31 </td> <td> Lesson 2 </td> <td> 1.3-1.4 </td> <td>p.25-28 #7-10 </td> </tr>

</table> <hr> <address><a href="mailto:rloukano@titan.iwu.edu">Roussan ka Loukanova</a></address> <!-- Created: Mon Oct 2 18:12:45 CDT 2000 --> <!-- hhmts start --> Last modified: Mon Oct 1 13:58:51 CDT 2001 <!-- hhmts end --> </body> </html> Frame Tags:

A frameset is the collection of frames displayed inside of a browser's window. The content of the frameset is enclosed between the tags <frameset> and </frameset>. The collection of frames is defined in a "column" and "rows" structure, by the two attributes rows and cols of the tag <frameset>. It is required that at least one of these two attributes present inside the <frameset> tag. They specify the number and sizes of the columns and rows of the frames. o Both accept values that are comma separated lists of sizes, either in pixels, or relative percentage, or a * standing for "remaining space". The number of sizes given (i.e. the length of the lists) defines the number of columns and rows in the frameset. For example: <frameset rows="150,300,150" cols="100,300"> creates 3 rows and two 2 columns with the specified sizes in pixels. <frameset rows="60%,20%,20%"

cols="25%,75%"> creates also 3 rows and two 2 columns with sizes expressed as a percentage of the window. <frameset cols="150,*,150"> The asterisk * tells the browser to create the first and third columns with 150 pixels width while the middle one will occupy the remaining space of the window. <frameset rows="*,150,*"> The <frame> tag is used to specify which document (or html file) to be displayed in a particular frame. The address (i.e. the directory path) of the document is given as value of the attribute src of the <frame> tag. Here is an example of a frame, Frames Layout. The code of the frame is: <html> <head> <title>Frames Layout</title> </head> <frameset rows="60%,*" cols="65%,20%,*"> <frame src="frame1.html"> <frame src="frame2.html"> <frame src="frame3.html" name="fill_me"> <frame src="frame4.html" scrolling="yes"> <frame src="frame5.html"> <frame src="frame6.html"> <noframes> Sorry, this document can be viewed only with a frame capable browser. </noframes> </frameset> </html>

The value of the attribute name (inside the <frame> tag) gives a name to the frame, so that this name can be used as value of the target attribute in the hyperlinks for uploading linked documents. For example, in the html code for the frame above the attribute name was used in the fourth frame. The name of a named frame box, in the above example, fill_me, can be used for the target of a link in a document different from those initially downloaded inside the frame boxes. If the above frame Frames Layout has been opened in a window different from the window of the frame (as is the current lecture note), by selecting the link Hello! the document hello.html will be displayed inside the frame named fill_me. Otherwise, i.e. if the frame Frames Layout is not opened, the hello.html document will be opened in a new window named fill_me. In any case, we use the link: <a href="hello.html" target="fill_me">

Internet Addresses and Links The URL (Uniform Resource Locator ) Every document on the World Wide Web has a unique address. The URL specifies the location of a web resource, regardless of the type and content of that resource. All URL have the following syntax:

Protocol://serverName/DirectoryPathName

Protocol is the type of software by which the browser and the document server communicate to exchange the document.

http:// (Hyper Text Transfer Protocol). To retrieve a document named FileName.html located on a specific server in a specific directory we type in the browser window its URL address with the following syntax: http://serverName/DirectoryPathName/FileN ame.html ftp (File Transfer Protocol). We use it to retrieve documents from archives (ftp servers). Usually the documents are large and placed in tape archives (the files have a suffix .tar). They also can be additionally compressed, i.e. "zipped", in which case the files have a suffix .zip or .gz. To download archival documents from a ftp server, use the syntax: ftp://serverName/DirectoryPathName/FileNa me.html After downloading the file you have to untar it, and if it has been compressed ("zipped") file you have to unzip it. The appropriate software for these tasks vary depending on the system. For example in our system, you can unzipped a downloaded file by typing on the UNIX command line: gunzip file_name.ps.gz OR: gunzip file_name.tar.gz and then: tar -xvf file_name.tar You can decompress a file that has an extention .zip, for example file_name.zip by the following UNIX command: unzip file_name.zip

Follow the UNIX's instructions if there are such in response to the above command. For more information on archives you can go to:

http://www.gnu.org/manual/ file You can use this protocol to test your web pages. The syntax is (the syntax may differ depending on the operating system): file://localhost/home/userName/DirectoryP athName/FileName.html file:/home/userName/DirectoryPathName/Fil eName.html For example: file:/home/rloukano/public_html/cs120/in_ notes/links_images.html mailto This protocol is used to provide an email link in your pages. The syntax is: mailto:UserName@ServerName

Absolute and Relative URL


Absolute URL: it is the complete address of a resource, as discussed above. Relative URL: the document address is abbreviated w.r. to the "base address" of the location of the document in which you are putting the link. For ex., if the browser retrieves a document named document.html with address: http://www.iwu.edu/~username/some_dir/doc ument.html you can put a link inside the document document.html to a different document another_document.html which is located inside a subdirectory dir1 of the directory some_dir by using its relative address: dir1/another_document.html

Links You can create a hypertext link, i.e. a hyperlink inside your document to another document. When you click on a link, the browser displays the selected page.

To add a link you use the pair of attributes: <a> ... </a>. The address of the document for a link is given as the value of href attribute. For example: <a href="http://www.yahoo.com/">yahoo</a> For example, my favorite information site is yahoo . Relative URL addresses can be used in links. o File in the same directory. The syntax is: <a href="fileName.html"> For example, in one of the html programs for the web site of our class cs120, I have a link to the announcements, which is created by the following link: <a href="program.html">Class Program</a> o File in a Subdirectory. A relative address can be used to open an html file in a subdirectory of the directory of the current page. The syntax is: <a href="directoryName/fileName.html"> For ex., <a href="in_notes/html_1.html">Intro to HTML, p.1</a> Or: <a href="in_notes/lists/ulist.html" target="new">unordered list example! </a> o File in a Parent Directory. A relative address can be used to open an html file in the parent directory of the directory of the current page. The syntax is:

<a href="../fileName.html"> It can be located even inside an upper level: <a href="../../fileName.html"> o File in a Subdirectory of the Parent Directory. A relative address can be used to open an html file in the parent directory of the directory of the current page. The syntax is: <a href="../dir3/fileName.html"> Link to a particular place (section) inside of the same document: o Mark (i.e. label) the place inside the document where you want the browser to "jump" when the user clicks on a link. You do it by using the attribute name of the tag a. For example, if you want the link to take the user to a section in the text which is the phrase "golden fish" you type it between the tags: <a name="ref">"golden fish"</a> o Create the link which when selected by the user will make the browser to "jump" to the section marked with the label ref: <a href="#ref"> ... </a> For ex., if we click on the link, it takes us to the section with a title "Links" in this page.

Link in a document named document_1.html to a particular place (section) inside of another document document_2.html: o Mark (i.e. label) the place inside document_2.html where you want the browser to "jump" when the user clicks on a link. You do it in the same way as described above. o Inside document_1.html: create the link which when selected by the user will make the browser to "jump" to the section marked with ref inside document_2.html:

<a href="document_2.html#ref"> ... </a> For ex., if we click on the link, it takes us inside the section "Ordered Lists" in lecture notes on lists.

The target attribute of the tag <a> lets you specify where to display the contents of a selected hyperlink. Often it is used with named multiple browser windows. The value of the attribute target is the name of the window in which the referenced document to be displayed. If no window with the given name hasn't yet been open, the document will be loaded in a new window appropriately named. For example, in the above example yahoo was opened in the current window. Now we can get it in a new window: yahoo. In next lectures we will learn that a document can be displayed in a frame by using the attribute target. You can change the color of the hyperlinks in a document by the attributes link, vlink and alink of the body tag. These three attributes take values that specify a color name or a RGB value. They are set by default if you do not explicitly specify them (they are deprecated in HTML 4). o link specifies the color of the hyperlinks that haven't yet been selected by the user; o vlink specifies the color of the hyperlinks visited by the user; o alink specifies the color of the currently selected hyperlink.

JavaScript is a scripting language designed and first implemented by Netscape (with help from Sun Microsystems). Netscape first introduced a JavaScript interpreter in Navigator 2. The interpreter was an extra software component in the browser that was capable of interpreting JavaSript source code inside an HTML document. This meant that Web page authors using no more than a simple text

editor could place special instructions or programs directly inside Web pages to make them more dynamic and interactive. For example, JavaScript can be used to:

validate user input in an HTML form before sending the data to a server; build forms that respond to user input without accessing a server; change the appearance of HTML documents and dynamically write HTML into separate Windows; open and close new Netscape windows or frames; manipulate HTML "layers" including hiding, moving, and allowing the user to drag them around a browser window; build small but complete client side programs.

The definition of the JavaScript language and the ability of the Netscape browser (and others..) to process it are still evolving. As the language grows, and Netscape, Microsoft, and others issue new versions of their browsers, programmers are discovering new and exciting things they can do with JavaScript and Web pages. Advantages of JavaScript JavaScript gives web authors an unprecedented degree of control over the behaviour of Netscape and the behaviour of their documents. You can do things with 20 lines of JavaScript that will significantly reduce the load on your server, give the user better feed back, and enhance the appearance of your web pages. JavaScript is often the most efficient solution to many Web authoring problems. JavaScript is also an easy language to get started using. With little more than a text editor a few helpful websites and some interest it is possible to produce some but useful scripts.

Disadvantages of JavaScript The first browser that reliably implemented JavaScript was Netscape 2.02. Since then, new features have been added to the language and have been supported by later versions of Netscape's browsers. Different versions of Netscape will behave differently depending on the language features you use. It is possible to write JavaScript programs that use advanced JavaScript features but do not cause problems (JavaScript errors) on older browsers. However, doing this is can be a complex and labour intensive process. Unfortunately, even the same version of Netscape may behave differently depending on the operating system it is run on. The language is very new and still evolving. Few software development tools exist to help you write and debug your scripts. And while you can do a lot with JavaScript, some things like animation, scrolling/animated banners and notices, and complex programming are often better done using animated GIFs, Netscape Plugins such as Flash, or Java applets. To make matters more complicated, Microsoft's support for JavaScript (they call it Jscript) in Internet Explorer has been evolving at a different pace than Netscape's. And while Microsoft has done a reasonable job of implementing the Javascript language they have decided to introduce differences in how the language interacts with the more recent and advanced methods for manipulating Web pages and responding to user input losely referred to as dynamic HTML. The growing market share of Internet Explorer and these differences have made it difficult for anyone to reliably use the more advanced features of dynamic HTML on the Web. From a scripter's perspective this situation is quite discouraging. It will take a number of years before a standard for dynamic HTML/Javascript is in place and the vast majority of the browsers on the Web completely support the standard. Also bad is the fact

that so many of the different browser versions have serious bugs in how Javascript interacts with HTML objects. Documenting these and working out code work arounds could easily occupy a small group of people full time.

S-ar putea să vă placă și