Likes

WCD-LAB @HOME 7-Ans 1

Investigate using EL to access complex data structures.


Preparation
No preparation is needed for this exercise.

Task
1. Open the project named SL314m061ab2 in the d:\labs\student\exercises directory and look at the classes domain.Customer and domain.Address.
2. Examine the launch page index, jsp. and the servet class web.Controller, to determine the basic structure of the application. Note that the application is missing the view CustomerView. jsp to which the controller servlet forwards.
3. Create the view class Customerinfo. jsp. Arrange that it displays the name and three addresses of the customer.
4. Test your application for the customer with the ID 1 (only one exists).
5. There are two distinct ways (syntactically) that you can access the three customer addresses-using arrays or using the three distinct fields. Whichever you used in step 3. modify your view to use the other approach, and retest your application.

WCD-LAB @HOME 2-Ans 2

HTTP headers that are sent by your browser.


Preparation
No preparation is needed for this exercise.

Task • Create index, jsp and a View JSP

In this project, the MVC model will be simplified a little. The intention is that you will create a sen'let to act as controller and a JSP to act as view, but will use a String object to carry the result data directly from the sen-let to the JSP.
1. Create a new project called SL3l4m4ii.
2. Edit the automatically created index.jsp file so that it carries a single link that will lead to a relative URL. /ListHeaders. You may use an HTML anchor to do this, or if you're feeling ambitious, a submit button on an othenvise empty form.
3. Add a new JSP to the project, call this file HeadersView. jsp.
4. Add to the view introductory text such as These are the headers of your browser .
5. Add an EL expression that will output the value of a text element in the request scope called headerList.

Task • Create the Controller Servlet

1. Add a sen-let to the project. Make the fully qualified name of the sen-let sl314.m4.HeaderServlet.
2. Set the URL pattern for the sen-let to ListHeaders.
3. In the sen-let. declare a StringBuilder called result. Set the value of the result to <UL>\n .
4. Obtain the enumeration of header names from the request object.

5. For each entry in the enumeration:
a. Append <LI> to result.
b. Append the header name to result.
c. Append = to result.
d. Extract the value of the header from the request and append that value to result.
e. Append </LI>\n to the result.
6. Append </UL>\nto result.
7. Add an attribute to the request called headerList and set the value to result.
8. Forward to HeadersView.jsp.
9. Finally, run the example and verify that you see headers such as host, user-agent. accept and others.

WCD-LAB @HOME 2-Ans 1

Create an MVC-based web application. The application will allow the user to determine the material traditionally associated with a given wedding anniversary.

Task - Design a JavaBeans Compliant Model

1. Consider the attributes needed to model the wedding anniversary problem. One writable attribute will be needed to represent the year number of the anniversary. Another, read-only, attribute will be needed to allow the view to present the name of the associated material.
2. Decide what you will call these attributes, and write them in the first column
3. Decide what the necessary corresponding methods will be to support those attributes in the JavaBeans naming conventions. Write those methods. Note that because one attribute is read-only, you will require a total of three methods, so one table cell will remain blank.
4. Decide what key name you will use to store the model in the request when it is forwarded. Write that down here:
5. Decide on the name of your model class, package name, and what, if any. base class it should extend. Write those down here:

Task
Implement the Model
1. In NetBeans. create a new web application project called SL3l4m03labl. This will also be the context root for the application.
2. Create a new class for the model and provide get and set methods as you specified.
3. In the file anniversaries.txt. you will find lists of anniversary material names with the year to which they apply. These data are provided in a form intended to simplify incorporating into a Java class. Use this form if it suits you or simply extract the raw data if you prefer to use that in creating your model. The file can be found under the Files tab (just to the right of the Projects tab in NetBeans) at the root directory of the solution for this lab.
4. (Optional) Create a trivial main method in your model to test the basic functioning of the methods.

Task • Create an HTML Form to Submit the Request
1. You will need a regular HTML form to allow the user of your application to enter the anniversary year they are interested in. When you created the project. NetBeans created an index, jsp file. Delete this file and create a new HTML page called index.html instead.
2. In the index.html file, you will create a form that prompts for a number of years. Decide what you will call the parameter when it is submitted to the web application. Write this parameter name.
3. The form will invoke an action, which will be the controller servlet that you will create shortly. Decide what the context root of this application will be. and the URL that will invoke the controller. Write these too in the Table 3-4 below.
4. Create the form in the index.html file.

Task • Create a View Component Using a JSP
1. Decide what you will call your view JSP. Write this down here:
2. Create the JSP for the view. It must present the year and anniversary material name returned by the model. Recall the name of the model as in Table 3-2 above. This will be needed along with the attribute names from Table 3-1 above to construct the EL expressions.

Task • Create the Controller
1. The final step in constructing this application is to create a controller to tie it all together. Create an HttpServlet. and ensure that it responds to the URL that you selected in Table 3-4 above.
2. Modify the processRequest method so that it:
a. Extracts the year parameter named
b. Creates an instance of the model.
c. Sets the year value in the model (consider the data type-is this a String or an int? If you convert, do not try to help the user but simply swallow any exceptions and produce a clean output. Error handling is a topic of later modules.)
d. Stores the model in the request scope using the name
e. Forwards to the view, named

Task - Run the Application

1. Right-click the project and run it.
2. Your browser should be launched automatically, and should show the input form. Enter a number of years, and press the submit button.
3. You should see appropriate output in the subsequent browser page.

Core Java Subjective Question

1.Identify the features of New API (NIO).
Ans:
i)The new API works more consistently across platforms.
ii)It makes it easier to write programs that gracefully handle the failure of file system operations.
iii)It provides more efficient access to a larger set of file attributes.

2.Differentiate between checked and unchecked exceptions.
Ans:
Checked Exception:
i)Every class that is a subclass of Exception except RuntimeException and its subclasses falls into the category of checked exceptions.
ii)You must ?handle or declare? these exceptions with a try or throws statement.

Unchecked Exception:
i)java.lang.RuntimeException and java.lang.Error and their subclasses are categorized as unchecked exceptions.
ii)You may use a try-catch statement to help discover the source of these exceptions, but when an application is ready for production use, there should be little code remaining that deals with RuntimeException and its subclasses.

3.Explain public, static, and void keywords in the following statement:
public static void main(String args[])
Ans:
i)public: The public keyword indicates that the method can be accessed from anyobject in a Java program.
ii)static: The static keyword is used with the main() method that associates the method with its class. You need not create an object of the class to call the main() method.
iii)void: The void keyword signifies that the main() method returns no value.

4.Identify the limitations of the java.io.File class.
Ans:
The java.io.File class has the following limitations:
i)Many methods did not throw exceptions when they failed, so it was impossible to obtain useful error messages.
ii)Several operations were missing (file copy, move, and so on).
iii)The rename method did not work consistently across platforms.
iv)There was no real support for symbolic links.
v)More support for metadata was desired, such as file permissions, file owner, and other security attributes.
vi)Accessing file metadata was inefficient?every call for metadata resulted in a system call, which made the operations very inefficient.
vii)Many of the File methods did not scale. Requesting a large directory listing on a server could result in a hang.
viii)It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.

5.Identify the five classes of the java.util.concurrent package and explain any two classes.
Ans:
i)Semaphore: Is a classic concurrency tool.
ii)CountDownLatch: A very simple yet very common utility for blocking until a given number of signals, events, or conditions hold.
iii)CyclicBarrier: A resettable multiway synchronization point useful in some styles of parallel programming.
iv)Phaser: Provides a more flexible form of barrier that may be used to control phased computation among multiple threads.
v)Exchanger: Allows two threads to exchange objects at a rendezvous point, and is useful in several pipeline designs.

6.Steve has been asked to automate the Library Management System either in C++ or Java. Steve has chosen to develop the project in Java. Identify the reason.
Ans:
One of the major problem areas in most of the object-oriented languages, such as C++, is to handle memory allocation. Programmers need to explicitly handle memory in the program for its optimum utilization. To handle memory allocation, they use pointers that enable a program to refer to memory location of the computer. However, Java does not support pointers and consists of the built-in functionality to manage memory.

7.You have created a class with two instance variables.You need to initialize the variables automatically when a class is initialized. Identify the method that you will use you to achieve this. In addition, describe the characteristics of this method.
Ans:
You can initialize the variable by using the constructor. The characteristics of a constructor are:
-       A constructor has the same name as the class itself.
-       There is no return type for a constructor. A constructor returns the instance of the class instead of a value.
-        A constructor is used to assign values to the data members of each objectcreated from a class

8.Differentiate between interface and abstract class.
Ans:
1.The methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
2.Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.
3.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
4.Java interface should be implemented using keyword, implements; A Java abstract class should be extended using keyword, extends.
5.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
6.A Java class can implement multiple interfaces but it can extend only one abstract class.
7.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
8.In comparison with Java abstract classes, Java interfaces are slow as it requires extra indirection.


WCD-LAB @HOME 6-Ans 2

Invertigate the compilation of JSPs to servlets


                       INVESTIGATE THE COMPILATION OF JSPsto servlets
1.Create a new java Webproject.
 2.Add a little body text tothe JSP.
3.Run the project.
4.Right click the JSP and select View Servlet from the pop-up menu.
5.Examine the contents of thr servlet , and notice how it corresponds to ypur
   original JSP.
6.Make.the following changes to your JSP,and each change ,re-run the
  project,thenexamine the servlet source again.
      a.Add apage initalize declaration for a private int variable.
       b.Add apage dirctive to import java.util.*.
       c.Add an expression to output the result of doubling the private int
              variable you added in stepa above.
     d.Add code to iterate overthe number 1 to 10, prinating a message as a part
        of an unnumberd list each time tround.Be sure to explicit
        curly braces for the loop boudaries.
   e. Edit thenow?Exmine the generated servlet and determine what
      Went Wrong.

      Retrive sessionin information using jsp tags
1.Create a new page called shoe ADDRESS.JSP
2.Using elements of the show Address.jsp page for assistance,create a standalone
   page that shows the currrent values ofa bean called addressBean thst is in the
 session scope.Note that this page will be loaded by typing its URLd directly
  accessiable because it is in the session scope.
3.test the page to show the values from the previous from submission.

WCD-LAB @HOME 6-Ans 1

1. Investigate EL implicit objects and the JSTL forlach tag.

                       INVESTIGATE EL Implicit opjrctand the JSTL for Each tag.
1.Create a new java web project project named
2.In the resulting index.jsp page , change the titke and heading to HTTP Headers.
3.Create a taglib directive to make the core JSTL taga available with a
   prefix of c.Consult the"Tag Example"section of Module 6 student guide if
    you need a reminder of the syntax for this.
4.prepare anunumbered listin the body of the document.
5.Inside the unnumber list tags,place a :for Each tag that will enumerate the
   elements of thr HTTP headers arry.Consult"El Implicit Object"in Module
   6in the student guide if you need help in findingthe header arry.
6.Test the program.

WCD-LAB @HOME 5-Ans 2

2. In the ExoticaTravels Web application, if any changes are made to the list of hotel and cab servicers name, the application code needs to be updated to reflect these changes. Therefore, you need to enhance the functionality of the ExoticaTravels Web application such that any changes made to the hotel and cab servicers list does not affect the application.


Note: To perform this exercise, you need to use the solution created in Exercise 01 of Chapter 04.



import java.io.IOException;
impot\rtjava.io.PrintWriter;
impot javax.Servlet.ServletException;
import javax.Servlet.annotation.WebServlet;
import javax,Servler.http.HttpServlet;
import javax.servlet.http.HttpServleltRequest;
import javax.Servlet.http.HttpServletResponse;
import javax.Servlet.http.HttpSession;

 public class HotelBookingServelt extends HttpServelt
    {
       protected void ProcessRequest(HttpServletRequest
request ,HttpServeltResponse response)
            throw ServletException.IOException
            {
   response .setContentTypes("text/html;charset=UTF-8");
   printWriter out = response.getWriter();
   HttpSession session=request.getSession();
   string hotelNames=this.getInitParameter
("HotelNames");
                      String hotelNameSplit[]=hotelName.split(" , ");
      try
                  {
                      String destination=request.getParameter
  ("destionation");
                          session.setAttribute("destination",
   destination);
                     out.println("<title>Tour package Booking
page</title>");
 out.println("<div align=right'>);
                    out.println("<a
href='LogoutServlet'>Logout</a>");
                   out.println("</div");
                    out.println("<tabel>");
                   out.println("<from
action='CabBookingServlet'>");
                out.println("<tr><td><h3>Tour package
 Booking</h3></td></tr>");
                     out.println("<tr><td>Select ahotel</td>");
                     out.println("<td><select name='hotel'>");
                     for(int i=0;<hotelNameSplit.length;i++)
                     out.println("option value=' "+hotelNameSplit
[i]+" '>"+hotelNameSplit[i]+"</option");
                 
                     out.println</select></h1></td>");
                     out.println("<tr><td>Number of days</td>");
name='noofdays'></td></tr>");
                      out.println("<tr><td><input types='submit'
value='next'></td>");
               out.println("</form>");
               out.println("<from
action='Tourpackagepage.jsp'>");
                       out.println("<td><input type='submit'
value='back'></td></tr>");
                  out.println("</form>");
                   out.println("<?table>");
                }
                      finally
                                 {
                                           out.close();
                    }
    }
@Override
   protected void goGet(HttpServletRequest request,
httpServletResponse response)
       throws ServletException.IOException
         {
     processRequest(request.response);
   }
@override
    protected void doPost(HttpServletRequest request,
HttpServletResponse response)
                  throw ServletException, IOException
        {
              processRequesr(request ,response);
                   }

   @override
   public String getServletInfo()
      {
         return"short description";
       }  
}