Friday, April 29, 2011

SCWCD Mock Exam 2 - Answers

Below are the Answers to the Questions that were part of the Practice Exam in the previous chapter. If the answer you chose matches the answer given here, great. In case it doesn't, don't worry. Just revisit the chapter that covers the topic and revise the chapter. You will be able to crack the exams easily!!!

Answers:

Question1:
E.
Question2:
A.
Question3:
ServletContextListener
Question4:
C.
Question5:
A, C.
Question6:
D.
Question7:
B.
Question8:
C.
Question9:
B.
Question10:
A and D.
Question11:
A and B.
Question12:
A and D.
Question13:
B and C.
Question14:
D.
Question15:
A.
Question16:
D.
Question17:
D.
Question18:
D.
Question19:
A and D.
Question20:
B.
Question21:
A and B.
Question22:
C.
Question23:
B.
Question24:
C.
Question25:
A.
Question26:
D.
Question27:
A and D.
Question28:
B and D.
Question29:
D.
Question30:
C and D.
Question31:
A.
Question32:
A, C, and D.
Question33:
D.
Question34:
C.
Question35:
C.
Question36:
A and D.
Question37:
B, C, and D.
Question38:
D.
Question39:
A.
Question40:
B and C.
Question41:
A.
Question42:
B.
Question43:
A.
Question44:
B.
Question45:
A.
Question46:
A.
Question47:
B.
Question48:
A.
Question49:
C and D.
Question50:
D.
Question51:
C.
Question52:
C and D.
Question53:
B.
Question54:
A.
Question55:
C.
Question56:
SingleThreadModel
Question57:
C.
Question58:
B and C.
Question59:
B.
Question60:
D.

Previous Chapter: Mock Exam 2

This is the Last Chapter in the SCWCD Certification Exam Series. So, there is no Next Chapter. However, you can access the Index of all chapters on the SCWCD Exam Series by Clicking Here

SCWCD Mock Exam 2

This chapter is the Second and last of our 2 practice Exams. It contains 60 Questions and you can take upto 90 minutes to answer all of them.

Remember that the exam contains the same number of Questions ‘60’ and you will be given the same 90 minutes only. So, make sure you time yourself and don't use more than the allotted time.

Questions

Question 1:

Which of the following can call the init method?
A. doPut
B. session
C. service
D. request
E. the container

Question 2:

Which corresponding method in the HttpServlet class do you use to retrieve the value of a text field on an HTML form?
A. doPost
B. getParameter(String fieldName)
C. doGet(String fieldName)
D. getHTTP(String fieldName)

Question 3:

Please provide the interface name which you implement to create a context listener.
______________________________

Question 4:

Which method is used to get a ServletContext object?
A. getContextServlet
B. getServlet
C. getContext
D. getServletContext

Question 5:

Which two of the following are HttpServlet class methods (choose two)?
A. doPut
B. getRequest
C. doPost
D. post

Question 6:

Which method does the container call at the end of the servlet lifecycle?
A. doDelete
B. end
C. finalize
D. destroy

Question 7:

What type of HTTP request is normally used for simple HTML page requests?
A. POST
B. GET
C. DELETE
D. CALL

Question 8:

The getInitParameterNames method returns what?
A. Enumeration of string objects with session-wide parameters.
B. String array with session-wide parameters.
C. Enumeration of string objects with application-wide parameters.
D. String array with application-wide parameters.

Question 9:

What types of events trigger a POST type request?
A. When a user clicks a hyperlink.
B. When a user clicks a button on an HTML form whose method is set to POST, as in method=post.
C. This is determined by the browser based on the size of the request.
D. This is determined by the server based on the size of the request.

Question 10:

Read the following code:
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{ response.setContentType("text/plain");
PrintWriter out = response.getWriter();
StringBuffer html = new StringBuffer();
html.append("< html >\n");
html.append("< head >< title >Servlet Example" + "< /title >< /head >\n");
html.append("< body >\n");
html.append("Servlet Example");
html.append("< /body >");
html.append("< /html >");
out.print( html.toString() );
}

Which two statements are true regarding this code (choose two)?
A. When a user sends a request to the container (assume servlet has not been loaded), this is the first method it calls.
B. When a user sends a request to the container (assume servlet has not been loaded), this is the second method it calls.
C. The doGet method will be called next.
D. The doGet method will not be called next.

Question 11:

What causes a servlet to load?
A. A Web server start.
B. The container detects that a class file has changed.
C. It is configured to do so periodically.
D. It is loaded upon every request.

Question 12:

Which two of the following are benefits of the POST method (choose two)?
A. It can send unlimited length data as part of its HTTP request body.
B. It allows bookmarks.
C. It uses simple query strings.
D. It hides data because it isn't passed as a query string, but is passed instead in the message body.

Question 13:

Which of the following are application-wide actions?
A. Context.setAttribute("applicationName", "Certification by Que");

B. config.getServletContext .setAttribute("applicationName", "Certification by Que");

C. config.getServletContext .getAttribute("applicationName", "Certification by Que");

D. Context .setAttribute("applicationName", "Certification by Que");

Question 14:

What is the benefit of using the HEAD HTTP method?
A. It hides the requester identity.
B. It masks the IP address.
C. It can handle any size request.
D. It is the smallest type request.

Question 15:

Which interface defines the methods for retrieving form parameters?
A. ServletRequest
B. ServletResponse
C. HTTPRequest
D. HTTPResponse

Question 16:

When does the container call init?
A. With each request for a given servlet.
B. Only on the first request for each user.
C. It is not called by the container.
D. Only at the beginning of the servlet lifecycle.

Question 17:

Which method do you use to retrieve a single value if you know the particular parameter name?
A. getParameterName(String parameterName)
B. getParameterValues(String parameterName)
C. getParameters(String parameterName)
D. getParameter(String parameterName)

Question 18:

Which method returns the URL to the resource that is mapped to a specified path?
A. getRealPath(String path)
B. getPath(String path)
C. getPathReal(String path)
D. getResource(String path)

Question 19:

Read the following code:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
// Serve the requested resource,
// including the data content.
}

Which two statements are true regarding this code (choose two)?
A. The doGet() method is called when the container receives an HTTP GET request.
B. The container always services a request with a doGet request as the last method called.
C. The request object has session scope.
D. The HTTP GET method may include parameters that are retrievable from the request object.

Question 20:

How do you perform programmatic server-side includes?
A. setForward(String url)
B. RequestDispatcher
C. Request
D. getResource(String url)

Question 21:

Which of the following is true?
A. ServletContext.getRequestDispatcher()— This method uses absolute paths.
B. ServletRequest.getRequestDispatcher (String path)— The path may be relative, but cannot extend outside current servlet context.
C. ServletRequest.getNamedDispatcher(String path)— The path may be relative.
D. ServletContext.getRequestDispatcher()— This method uses relative paths.

Question 22:

Which of the following is correct?
A. Enumeration names = request.getNames() ;
B. String[] names = request.getNames() ;
C. Enumeration parameterNames = request.getParameterNames() ;
D. String[] parameterNames = request.getParameterNames() ;

Question 23:

Suppose the container received an HTTP POST request. How would you process this request in the servlet's doGet method?
A. This isn't possible. The doPost method will receive the request, not the doGet method.
B.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
//often just throw it at doGet()
doGet(request, response);
}



C. If there is no form parameters the container will automatically send the request to the doGet method.
D.
protected void init(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
//often just throw it at doGet()
doGet(request, response);
}

Question 24:

Which method corresponds to the HTTP GET method?
A. get
B. httpGet
C. doGet
D. getHTTP

Question 25:

It happens often that pages move around and a URL becomes invalid. Throwing back a 404 error isn't nice. What could you do that is better?
A. Use the sendRedirect method to send viewers to a temporary page.
B. Use the sendTemporary method to send viewers to a temporary page.
C. Use the setTemporary method to specify a temporary page and set the context parameter to the new URL.
D. Use the redirect method to send viewers to a temporary page.

Question 26:

Which of the following method lists are in the correct lifecycle order?
A. request start doPost end
B. service start response destroy
C. request init getPost
D. init service destroy

Question 27:

Which two of the following are called only once during the lifetime of a servlet (choose two)?
A. destroy
B. doPut
C. service
D. init
E. config

Question 28:

Which two of the following HttpServlet class methods receives the response object (choose two)?
A. get
B. doPut
C. getHTTP
D. doGet

Question 29:

What happens if you redirect a request to another URL after some of the response has already been returned?
A. The container simply discards the partial response and jumps to the new URL.
B. The container gets confused.
C. The specification doesn't say what the container is supposed to do. It is up to the vendor to decide.
D. The container throws IllegalStateException.

Question 30:

Read the following code:
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("< html >");
out.println("< head >< title >Servlet Error Handling " +
"Example< /title >< /head >");
out.println("< body >");
out.println("A skimpy, but complete servlet.");
out.println("< /body >");
out.println("< /html >");
}
}

Which two statements are true regarding this code (choose two)?
A. The doGet, doPost, or doPut method is called next depending on the type of request.
B. This code is invalid because it doesn't call one of the doGet, doPost, or doPut methods.
C. This code is valid and will handle all three types of HTTP requests including GET, POST, and PUT.
D. The next method invoked is destroy.

Question 31:

How do you set, get, and change application-level (not session-level) attributes and talk to the servlet container?
A. ServletContext
B. Context
C. Response
D. Request

Question 32:

Which three options are events that would trigger a GET type request (choose three)?
A. A form submission with the METHOD='GET'.
B. Uploading a file.
C. A user clicking a hyperlink.
D. Typing in the address text box on a browser.
E. Sending email.

Question 33:

How do you get application-level initialization parameters?
A. You use the getParameterValues method.
B. You use the getInitValues method.
C. You call the init method, which returns an array of initialization parameters.
D. You use the getInitParameter and getInitParameterNames methods.

Question 34:

You normally write a servlet by overriding the doPut, doGet, and doPost methods. Which class do they come from?
A. HttpServletRequest
B. HttpServletResponse
C. HttpServlet
D. HttpSession

Question 35:

Which two of the following options are benefits of the POST method (choose two)?
A. It is used for getting information such as a simple HTML page or the results of a database query.
B. It is a method that supports query strings of unlimited length.
C. It hides data because it isn't passed as a query string, but is passed instead in the message body.
D. It normally saves resources because of the way the request is compressed.

Question 36:

Which of the following methods belongs to the ServletContext class?
A. getInitParameterNames
B. getParameterValues
C. getParameterValues(String)
D. getInitParameter

Question 37:

The session scope includes which two of the following (choose two)?
A. Requests from several machines.
B. All hits from a single machine.
C. Multiple browser windows if they share cookies.
D. Multiple hits from the same browser across some period of time.

Question 38:

Which of the following methods corresponds to the HTTP PUT method?
A. getPUT
B. putHttp
C. httpPUT
D. doPut

Question 39:

Which method returns an enumeration of String objects containing the names of the parameters contained in the request or an empty enumeration if the request has no parameters?
A. getParameterNames
B. getMap
C. getParameterMap
D. getParameterValues

Question 40:

Read the following code:
< html >
< body >
Devyn likes < b >R/C Buggies< /b >. < br >
< %! int count = 100, factor=5; % >
< %=count * factor% >
< /body >
< /html >

Which two statements are true regarding this code (choose two)?
A. This is a JSP page, but it will not run because it is missing the JSP declaration.
B. The code will display: Devyn likes R/C Buggies. 500
C. This JSP page will be translated into servlet code, which will be compiled and invoked as a servlet going forward.
D. You can't declare two integers on the same line in JSP.

Question 41:

How do you get the absolute path for a given virtual path?
A. getabsolute Path(String path)
B. getPath(String path)
C. getPathabsolute (String path)
D. getPathabsolute ()

Question 42:

Which method do you use to retrieve multiple values for a given parameter?
A. getParameterValues
B. getParameterValues(String parameterName)
C. getParameters
D. getParameters(String parameterName)

Question 43:

How would you “print” a text message to the browser?
A. PrintWriter out = response.getWriter();
out.println(message);

B. response.println(message);

C. ServletOutputStream out = response.getWriter();
out.println(message);

D. ServletOutputStream out = response.ServletOutputStream();
out.println(message);K.

Question 44:

Which method obtains a resource located at the named path as an InputStream object?
A. getResourceStream(String path)
B. getResourceAsStream(String path)
C. getResource(String path)
D. getStream(String path)

Question 45:

A browser or application will sometimes send a request to a server just to check the status or get information (such as 'can you handle a file upload?') from the server. What method does it use to do this?
A. HEAD
B. PING
C. DELETE
D. POST

Question 46:

What does the getParameter(String) method do?
A. It returns the value of a request parameter.
B. This method is not valid. It really is getFormParameter.
C. It should be getParameter without a string parameter of its own.
D. It can be used to return an integer from a form field.

Question 47:

What happens if the container crashes?
A. The JVM calls finalize for all pending servlet requests.
B. Since it is crashing it doesn't do anything but disappear.
C. The destroy method is called if possible.
D. The log is noted and then pending requests get simple error returns.

Question 48:

The PUT type request is for which type of situation?
A. Uploading files to the server.
B. Submitting form field values.
C. Testing for valid URLs.
D. Using XML for exchanges.

Question 49:

Which of the following two options are ways to get a RequestDispatcher (choose two)?
A. getDispatcher
B. getDispatcherName
C. getNamedDispatcher
D. getRequestDispatcher

Question 50:

Which of the following two options are ways to invoke the doGet method (choose two)?
A. The init method calls doGet.
B. The container calls doGet.
C. The request object calls doGet.
D. The service method calls doGet.

Question 51:

Which method returns the values of a given request parameter as an array of strings, or returns null if the parameter does not exist?
A. getParameterMap
B. getParameterValues
C. getParameterValues
D. getParameters

Question 52:

What happens if you set a Web application-wide parameter through ServletContext, but don't provide a value?
A. This cannot happen.
B. An exception will be thrown.
C. Retrieving this parameter will return a string containing a servlet container version number.
D. Retrieving this parameter will return a string containing a servlet container name.

Question 53:

What is the most frequently used type of HTTP request?
A. POST
B. GET
C. DELETE
D. CALL

Question 54:

How do you get the request header names?
A. Enumeration e = request.getHeaderNames ;
B. String[] names = request.getHeaderNames ;
C. Enumeration e = request.getHeaders ;
D. String[] names = request.getHeaders ;

Question 55:

Suppose you want to open a binary file in a browser from a servlet. How would you declare and initialize the output stream?
A. ServletContext.getOutStream ;
B. ServletContext.getBinaryStream ;
C. ServletOutputStream out = response.getOutputStream ;
D. PrinterWriter out = response.getPrinterWriter ;

Question 56:

Please provide the interface name that allows you to make your servlet thread-safe.
_____________________________

Question 57:

How do you add the content-type header to the response?
A. response.setContentType ;
B. response.setType( contentType );
C. response.setContentType( String );
D. String type = request.getContentType ;

Question 58:

Which of the following two options are features of the GET method (choose two)?
A. It can handle most request types including file uploading and form submissions.
B. It is for getting information such as a simple HTML page or the results of a database query.
C. This method supports query strings. Servers usually limit query strings to about 1,000 characters.
D. This disallows bookmarks.

Question 59:

What happens if, when calling getParameterValues, the parameter has a single value?
A. It returns an error. You should use the getParameterValue method for single value parameters.
B. It returns an array with a length of one.
C. getParameterValues calls getValue for that single value.
D. It returns a string with that single value.

Question 60:

The POST type request is most often used for which of the following situations?
A. When uploading a file.
B. With query strings.
C. The POST request is a combination of a GET and PUT.
D. When submitting an HTML form.

Previous Chapter: Mock Exam 1 - Answers

Next Chapter: Mock Exam 2 - Answers

SCWCD Mock Exam 1 - Answers

Below are the Answers to the Questions that were part of the Practice Exam in the previous chapter. If the answer you chose matches the answer given here, great. In case it doesn't, don't worry. Just revisit the chapter that covers the topic and revise the chapter. You will be able to crack the exams easily!!!

Answers:

QUESTION 1:
A and D.
Question 2:
A and D.
Question 3:
C.
Question 4:
A, C, and D.
Question 5:
A and D.
Question 6:
B and D.
Question 7:
B.
Question 8:
D.
Question 9:
B and D.
Question 10:
A.
Question 11:
A and D.
Question 12:
D.
Question 13:
A.
Question 14:
C.
Question 15:
B.
Question 16:
D.
Question 17:
C and E.
Question 18:
A and B.
Question 19:
A and B.
Question 20:
B.
Question 21:
A and C.
Question 22:
C and D.
Question 23:
A and B.
Question 24:
A.
Question 25:
C and D.
Question 26:
A.
Question 27:
B and D.
Question 28:
C.
Question 29:
D.
Question 30:
C.
Question 31:
B and C.
Question 32:
A and C.
Question 33:
B.
Question 34:
B and C.
Question 35:
A.
Question 36:
A and B.
Question 37:
A and B.
Question 38:
A.
Question 39:
B.
Question 40:
B.
Question 41:
service.
Question 42:
A and C.
Question 43:
B and C.
Question 44:
B.
Question 45:
A and B.
Question 46:
C.
Question 47:
C and D.

Question 48:
A.
Question 49:
C and D.
Question 50:
A.
Question 51:
A.
Question 52:
D.
Question 53:
D.
Question 54:
B and C.
Question 55:
A.
Question 56:
A.
Question 57:
A and B.
Question 58:
C.
Question 59:
A.
Question 60:
A.

Previous Chapter: SCWCD Mock Exam 1

Next Chapter: SCWCD Mock Exam 2

SCWCD Mock Exam 1

This chapter is the first of our 2 practice Exams. It contains 60 Questions and you can take upto 90 minutes to answer all of them.

Remember that the exam contains the same number of Questions ‘60’ and you will be given the same 90 minutes only. So, make sure you time yourself and don't use more than the allotted time.

Questions:

Question 1:

Regarding a typical HTTP request/response cycle, which of the following places the described events in their proper order? (Choose two.)
A. The Web browser makes an HTTP request, the Web server receives the request, and the Web server hands off the request to the servlet container.
B. A client responds to a servlet validation ping, Web server receives the request, and the Web server hands off the request to the servlet container.
C. The servlet container receives a request. The container reads the configuration (web.xml), and then calls the appropriate servlet.
D. The servlet polls the request object to find out what to do, the servlet performs its logic, and then sends data back to the client via the response object.

Question 2:

Which of the following are true about JSP comments? (Choose two.)
A. The JSP syntax is < % - - comment - - % >
B. The JSP syntax is < ! - - comment - - >
C. The XML syntax is < jsp: comment >< /jsp: comment >
D. They document the JSP page but is not inserted into the response.

Question 3:

Servlets are a required API of which Java 2 platform?
A. J2ME
B. J2SE
C. J2EE
D. J2DE

Question 4:

Which of following methods represents the servlet life cycle described in the API? (Choose three.)
A. init
B. start
C. service
D. destroy
E. getServletInfo

Question 5:

Which two of the following are true regarding the container initializing a servlet before it can handle requests from clients? (choose two)
A. The container calls the init method.
B. The container calls the service method.
C. This is how you can keep track of request activities.
D. This is how you set up a catch/try block.

Question 6:

During initialization, the servlet instance can throw which exceptions? (Choose two.)
A. ServletUnavailableException
B. UnavailableException
C. ServletNotFoundException
D. ServletException

Question 7:

Which of the following statements regarding the forward method of the RequestDispatcher interface are true?
A. It must be called before the response buffer is full.
B. It can throw an IllegalStateException exception.
C. It requires an absolute path. A relative path won't work.
D. The client must have this feature turned on.

Question 8:

If during initialization, the servlet instance throws an exception, which of the following statements is true regarding the destroy() method?
A. The method is called finalize().
B. The container calls the destroy() method.
C. The container invokes the catch block.
D. The container doesn't call the destroy method after an exception.

Question 9:

Which exceptions can a servlet throw during the service of a request? (Choose two.)
A. RequestException
B. ServletException
C. HttpException
D. UnavailableException

Question 10:

Which two of the following are true about page directives in JSP?
A. They define attributes that apply to an entire JSP page.
B. If a variable is declared it must appear before it used in the JSP.
C. You can declare instance variables with them.
D. There can only be one.

Question 11:

Which two statements are true regarding how the servlet container will keep a servlet loaded? (choose two)
A. A servlet instance may be kept active in a servlet container for the lifetime of the servlet container.
B. When the session ends, the servlet is unloaded.
C. The specification defines a session to have a default timeout of 20 minutes.
D. There is no association between how long a servlet is loaded and the session.

Question 12:

Before the servlet container may destroy a servlet, what must be true?
A. Pending requests are flushed.
B. HttpSession calls finalize().
C. ServletContext calls finalize().
D. Threads that are currently running in the service method of the servlet must complete execution.

Question 13:

Regarding container paths and URL, which of the following equations is always true?
A. requestURI = contextPath + servletPath + pathInfo
B. requestURI = contextPath + pathInfo + servletPath
C. contextPath = requestURI + servletPath + pathInfo
D. servletPath = contextPath + pathInfo

Question 14:

How do you include an outside resource into a JSP page?
A. < jsp: include page="salesTax.jsp" >
this works
< /jsp: include >

B. < jsp: include uri="salesTax.jsp"/ >

C. < jsp: include page="salesTax.jsp" >
< jsp: param name="state" value="CA" / >
< jsp: param name="amount" value="359.92" / >
< /jsp: include >

D. < jsp: include uri="salesTax.jsp" >
< jsp: param name="state" value="CA" / >
< /jsp: include >.

Question 15:

What information does the client send back as part of a cookie?
A. date, location, name, and value
B. name and value
C. location, name, and value
D. server version, date, and SSL status

Question 16:

What is the lifetime of the request object?
A. Until all threads associated with the session are complete.
B. This is container vendor specific.
C. Like garbage collection, exact timing is not specified.
D. It depends on the scope of a servlet's service method.

Question 17:

Which of the following are true about includes in JSP? (Choose two.)
A. There is no such thing.
B. The XML syntax is < jsp: text > < /jsp: text >
C. The JSP syntax is < %@ include file="relativeURL" % >
D. The JSP syntax is < % include("string") % >
E. The included text is added to the JSP page at translation time, when the JSP page is compiled.

Question 18:

What does a servlet container do with buffering? (Choose two.)
A. It is allowed to buffer output going to the client.
B. It is not required to buffer output going to the client.
C. It is required to buffer output going to the client.
D. The container can be configured to buffer in the buffer.xml configuration file.

Question 19:

Which of the following are true about the declarations in JSP? (Choose two.)
A. The JSP syntax is < %@ declaration % >
B. The JSP syntax is: < %! declaration % >
C. The XML syntax is < jsp: declare >< /jsp: declare >
D. The JSP syntax is < % declaration % >.

Question 20:

How do you write a message to the WebApp log?
A. Response.log()
B. ServletContext.log(String)
C. Response.errorLog()
D. ServletContext.logger()

Question 21:

Headers may contain data that represents which data types? (Choose two.)
A. int
B. String
C. Date
D. Object

Question 22:

Using the sendError method has what side effect? (Choose two.)
A. There is no way to catch errors after calling sendError.
B. It automatically calls the destroy method.
C. It commits the response.
D. It terminates the response.

Question 23:

Which two of the following methods terminate the response so that afterward no more output may be added to the response buffer? (choose two)
A. The sendError method.
B. The sendRedirect method.
C. The sendTerminate method.
D. The sendComplete.

Question 24:

Which two of the following are true regarding the Hypertext Transfer Protocol (HTTP)? (choose two)
A. It is a stateful protocol.
B. It is a stateless protocol.
C. Servlets use sockets to make it stateful.
D. Servlets can only handle real connections so it is the container vendor's responsibility to manage this.

Question 25:

Which of the follow are features of URL rewriting?
A. It converts relative to absolute paths.
B. It redirects clients to another URL.
C. It is used for sessions.
D. It appends to a query string.

Question 26:

When is a session considered established?
A. When a client joins it.
B. When you create a cookie on the client.
C. When the client is notified about the session.
D. When the request object is created.

Question 27:

Which of the following methods may be used to send error information back to a client? (Choose two.)
A. HttpServletError.setError()
B. HttpServletResponse.sendError()
C. HttpServletError.sendStatus()
D. HttpServletResponse.setStatus()

Question 28:

What is the correct syntax for assigning a value to a bean's property?
A. < jsp: property name="houseLotBean" property="id" value="33245" / >
B. < jsp: useBean name="houseLotBean" property="id" value="33245" / >
C. < jsp: setProperty name="houseLotBean" property="id" value="33245" / >
D. < jsp: setProperty property="id" value="33245" / >

Question 29:

Any object bound into a session is available to which other servlets?
A. Those servlets that share the same response.
B. Those servlets that have access to HttpSession.
C. Those servlets in the same container.
D. Those servlets that belong to the same ServletContext.

Question 30:

Some objects may require notification when they are placed into, or removed from, a session. This information can be obtained by having the object implement which interface?
A. HttpSessionListener
B. ServletContextListener
C. HttpSessionBindingListener
D. HttpServletResponseListener

Question 31:

When will the life of the session expire? (Choose two.)
A. When you call the expunge() method.
B. When you set the setMaxInactiveInterval to -1.
C. When you call the invalidate() method.
D. When the service method completes.

Question 32:

What are the methods of the RequestDispatcher interface? (Choose two.)
A. include
B. getClient
C. forward
D. back

Question 33:

Using XML syntax, how do you add text to the JSP output stream?
A. < jsp: page text="your text here" / >
B. < jsp: text >
your text
< /jsp: text >

C. < jsp: include param="text" value="your text here"/ >
D. < jsp: text value="text here"/ >

Question 34:

A servlet being used from within an include has access to which of the following? (Choose two.)
A. javax.servlet.include.response_uri
B. javax.servlet.include.context_path
C. javax.servlet.include.servlet_path
D. javax.servlet.include.cookie_info

Question 35:

Which of the following statements is true about how a servlet binds an object attribute into an HttpSession implementation by name?
A. This is determined by the deployment descriptor.
B. It depends on how you extend a servlet.
C. It depends on the container.
D. It binds it to the HttpServletResponse object.

Question 36:

The HttpServlet abstract subclass has which of the following methods beyond the basic Servlet interface? (Choose two.)
A. doHead()
B. doGet()
C. doRemove()
D. doCookie()

Question 37:

Which of the following elements are legal in a JSP scriptlet? (Choose two.)
A. Statements
B. Variable declarations
C. jsp: useBean
D. XML action

Question 38:

Fill in the name of the method of HttpServletResponse used to notify the client of a servlet error (without parentheses and parameters).
______________

Question 39:

Which of the following is true about template data in JSP?
A. The XML syntax is < jsp: template > < /jsp: template >
B. The XML syntax is < jsp: text > < /jsp: text >
C. The JSP syntax is < % expression % >
D. It is processed by the JSP engine.

Question 40:

Regarding changing the status in the response header, which statement is true?
A. You use the addStatus method.
B. You use the setStatus method.
C. You use the page directive.
D. You use an XML action directive.

Question 41:

Provide the name of the method that the servlet container calls on every request.
______________

Question 42:

Regarding the taglib directive, which of the following two statements are true?
A. It names the tag library that defines the custom tags and specifies their tag prefix.
B. It is the tag-library directive, not the taglib directive.
C. It declares that the JSP page uses custom tags.
D. It declares that the JSP page can use beans as defined in the directive.

Question 43:

What happens when the session attribute of the page directive is false? (Choose two.)
A. The session attribute doesn't go in the page directive.
B. You cannot use the session object.
C. Referring to a session object in the code causes a translation-time error.
D. The session attribute can only be specified with XML, not JSP syntax.

Question 44:

How do you specify that a given JSP page can be used as an error page?
A. There is no tag for this. It must be done in the web.xml configuration file.
B. Set the isErrorPage attribute of the page directive to true.
C. Place it in the error directory.
D. Use the include element.

Question 45:

Regarding a JSP page that inherits a class, which two of the following are true?
A. Servlets can inherit a class so JSP pages can too.
B. It uses the extends="package.class" attribute of the page directive.
C. It can only inherit another JSP page, not a servlet.
D. It can only inherit a JSP page with the same superclass.

Question 46:

Which statement is true about JSP expressions?
A. You must convert them to strings to append them to the output stream.
B. The JSP syntax is < % expression % >
C. The JSP syntax is < %=expression % >
D. The JSP syntax is < % System.out.print(expression) % >

Question 47:

Regarding forwarding a request to a Web resource in JSP, what two of the following are true?
A. You use the page directive. Set the forward attribute to true.
B. You can't do this in JSP. Do it at the servlet level.
C. < jsp: forward page="< %= expression % >" / >
D. < jsp: forward page="relativeURL" >
< jsp: param name="parameterName" value="parameterValue" / > +
< /jsp: forward >

Question 48:

Which of the following are true about the include directive and the jsp: include element?
A. The include directive is processed when the JSP page is translated into a servlet class. The jsp: include element is processed when a JSP page is executed.
B. The include directive is processed when the JSP page is compiled into a servlet class. The jsp: include element is processed when a JSP page is translated.
C. The include directive is processed when the JSP page is translated into a servlet class. The jsp: include element is processed when a JSP page is translated.
D. The include directive is processed when the JSP page is executed into a servlet class. The jsp: include element is processed when a JSP page is executed.

Question 49:

How can a servlet set headers of an HTTP response? (Choose two.)
A. Using a query string.
B. Using POST.
C. Using addHeader.
D. Using setHeader.

Question 50:

What kind of scheme is the HTTP protocol?
A. request/response
B. store/forward
C. queuing
D. search/return

Question 51:

If you wanted to use a conditional piece of code, which of the following shows where would you place it?
A. < jsp: scriptlet > code goes here < /jsp: scriptlet >
B. < jsp: code > code goes here < /jsp: code >
C. < jsp: include > code goes here < /jsp: include >
D. < jsp: jsp > code goes here < /jsp: jsp >

Question 52:

How would you forward a request to another resource?
A. < jsp: forward url="page.htm" / >
B. < jsp: forward param="page.htm"/ >
C. < jsp: forward uri="page.htm" / >
D. < jsp: forward page="page.htm" / >

Question 53:

What does the sendError method do?
A. It sends an error message to the server.
B. It sends an error message to the client log.
C. It logs an error.
D. It sends an error response to the client using the specified status.

Question 54:

Requests are represented by which two of the following objects? (choose two)
A. Request
B. Servlet Request
C. HttpServletRequest
D. ContainerRequest

Question 55:

Regarding passing an exception object to the method that writes information to the log file, which statement is true?
A. You can pass a string but not an exception object to the method that logs a message.
B. You can pass an exception object to the ServletContext.errorLog method that logs a message.
C. The exception must be converted to a string first.
D. You can use the response.log method to write to the log.

Question 56:

Which of the following will include the text of a resource at translation time?
A. < %@ include file="relativeURLspec" % >
B. < %! include file="relativeURLspec" % >
C. < %jsp: include file="relativeURLspec" % >
D. < %@ page import="relativeURLspec" % >

Question 57:

Which two of the following are correct uses of the RequestDispatcher (assume req is a correctly instantiated object of HttpServletRequest)? (choose two)
A. req.getRequestDispatcher(forwardURL). forward(req, res);
B. req.getRequestDispatcher(includeURL). include(req, res);
C. req.getRequestDispatcher.include(req, res);
D. req.getRequestDispatcher.forward(req, res);

Question 58:

What happens if you send data to the client after sendError has been called?
A. The information is ignored by the server.
B. The information is ignored by the client.
C. The method will throw IllegalStateException.
D. The method will throw IllegalSendException.

Question 59:

Which design pattern acts as a proxy and reduces network traffic?
A. Value objects
B. Model-view-controller
C. Data access objects
D. Business delegate

Question 60:

Regarding the sendRedirect method, which two of the following statements are true? (Choose two.)
A. It is legal to call the sendRedirect method with a relative URL path.
B. It is legal to call the sendRedirect method with an absolute URL path.
C. You must redirect to a servlet that implements the same interface.
D. You must redirect to a resource that must be defined in the deployment descriptor.

Previous Chapter: Chapter 59 - Exam Preparation Tips

Chapter 59: Study and Exam Preparation Tips

This chapter is not something that you need to memorize but, from the exam point of view, this is a pretty important chapter. We will be covering some tips and tricks that can help you prepare better for the exam and get certified successfully.

Another good news is, we have already covered all you need to know to pass the SCWCD Exam. This is going to be the last chapter in this series (Of course, there are some sample exam questions that you can use to test your understanding of the topics).

So, lets get started!!!

Study Tips

• Don't just blindly memorize the stuff related to the exam
• Read them slowly and try to understand how every item works and what the purpose of each entity is
• Writing Code and Running them in your local computer is the best way to understand many of the concepts
• There is a lot of example code. Try deploying them onto your computer and test out the results. This would do wonders when compared to just monotonously reading articles.
• Finally, Study only when you are alert, reduce or avoid distractions as much as possible and take breaks when you become fatigued

Pre-Testing Yourself

Every Section in this series has some sample questions. Test your knowledge of the topics by answering them. Don't lose heart if you are unable to answer them all right. Nobody is perfect. Just re-visit the chapters, read them again and re-take the test.
• Most importantly, there are going to be 3 sets of Mock Exam Questions after this chapter. Time your Mock Exam and evaluate yourself. Note down your scores. Your scores in the mock exam will give you a fair idea of how well prepared you are for the exam and it will also help you identify pain-points that you may have to review/re-study to master.

During the Exam Session

Following are some general tips that are applicable to anyone who is taking any exam and it applies to us for the SCWCD Exam too.

• Take a deep breath and try to relax when you first sit down for your exam session. It is important to control the pressure you might (naturally) feel when taking exams.
• You will be provided with scratch paper. Take a moment to write down any factual information and technical detail that you committed to short-term memory.
• Carefully read all information and instruction screens. These displays have been put together to give you information that is relevant to the exam you are taking.
• Read the exam questions carefully. Reread each question to identify all relevant details. Do not rush.
• Tackle the questions in the order they are presented. Skipping around will not build your confidence and most importantly it wastes time
• If you are unable to answer a question after 60 seconds, just move on to the next one. Don't waste too much time on any particular question.
• If session time remains after you have completed all questions, review your answers. Pay particular attention to questions that seem to have a lot of detail or that involve code analysis.
• As for changing your answers, the general rule of thumb here is don't change them. In most cases, a perfectly right answer might seem incorrect in the last few minutes when you review the answer. Avoid such impulsive changes. However, if an answer seems a definite incorrect answer, don't hesitate, just go ahead and choose the one you feel is right.

Last but not the least, All the very best and do well.

And – do come back and leave a comment on my blog once you clear the exam and get certified!!!

Previous Chapter: Self Test - Chapters 51 to 58

Next Chapter: SCWCD Mock Exam 1

Self Test: Chapters 51 to 58

Questions

Question 1

Which design pattern has as its primary responsibility to decouple presentation and service tiers, and a central director?
A. Value Object
B. Composite View
C. Business Delegate
D. Model-View-Controller

Question 2

Which design pattern has as its primary responsibility to exchange data between tiers?
A. Value Object
B. Composite View
C. Business Delegate
D. Model-View-Controller

Question 3

Which design pattern has as its primary responsibility to abstract data sources and provide transparent access to the data in these sources?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Model-View-Controller
E. None of the above

Question 4

Which design pattern has as its primary responsibility to isolate the presentation and the business tiers from each other by adding a director between the two, making it is easier to manage changes on either side?
A. Session Facade
B. Data Access Object
C. Business Delegate
D. Model-View-Controller
E. Aggregate Entity

Question 5

Which one of the following is most likely used for cache?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Cache Object
E. Aggregate Entity

Question 6

Which design pattern acts as a switchboard, dispatching incoming requests to the correct resource?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Front Controller

Question 7

Which design pattern is most likely to care about RDBMS, OODBMS, and flat files?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Cache Object
E. Aggregate Entity

Question 8

Which design pattern does the following force most affect?
Persistent storage APIs vary between vendors, which causes a lack of uniform APIs to address the requirements for accessing storages.
A. Value Object
B. Data Access Object
C. Business Delegate
D. Cache Object
E. Aggregate Entity

Question 9

Which design pattern has as its primary role to provide control and protection for the business service?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Cache Object
E. Aggregate Entity

Question 10

Which design pattern is most likely to be used as a proxy?
A. Business Delegate
B. Data Access Object
C. Model-View-Controller
D. Value Object

Question 11

Which design pattern reduces the number of remote network method calls required to obtain the attribute values from the entity beans?
A. Business Delegate
B. Data Access Object
C. Model-View-Controller
D. Value Object

Question 12

Which design pattern that usually is a good candidate to work with entity beans becomes less useful when a cache is used to persist data?
A. Business Delegate
B. Data Access Object
C. Model-View-Controller
D. Value Object

Answers

Question 1

D. The Model-View-Controller pattern has as its primary responsibility to decouple presentation and data/business logic tiers, by using a director or switchboard between them.

Question 2

A. The Value Object pattern has as its primary responsibility to exchange data between tiers. Although the Business Delegate and Model-View-Controller also do this, it isn't their primary responsibility.

Question 3

B. The Data Access Object pattern has as its primary responsibility to abstract data sources and provide transparent access to the data in these sources. The Business Delegate and Model-View-Controller may do so, but the Data Access Object always does this.

Question 4

D. The Model-View-Controller pattern has as its primary responsibility to minimize the impact of changing the client or business tier. Remember that this is a very high-level pattern, so it often uses other patterns.

Question 5

A. The Value Object pattern is most likely used for cache. Notice that its whole purpose is to collect data from somewhere far and bring it close in a neat package. The Data Access Object and Business Delegate often actually use a Value Object underneath. The Cache Object is fiction and the Aggregate Entity is not one of the four that you might see on the exam.

Question 6

D. The front controller pattern acts as a switch board, dispatching incoming requests to the correct resource.

Question 7

B. The Data Access Object design pattern is one that deals with RDBMS, OODBMS, excel, flat files, and more. This is pattern you use to isolate the access API from the actual data repository implementation. Value Object and Business Delegate don't do this. The other two patterns mentioned are distracters.

Question 8

B. The Data Access Object design pattern is affected most by varying persistent storage APIs due to different vendors and non-uniform APIs to address the requirements to access storages. Whenever you see the word persistent, think Data Access Object design pattern.

Question 9

C. The Business Delegate design pattern has as its primary role to provide control and protection for the business service. Although you can't just ignore the rest of the Question, normally when a Question focuses on the business service, think Business Delegate design pattern.

Question 10

A. The Business Delegate design pattern is most likely to be used as a proxy. Its whole purpose is being the mediator between a business service and the rest of the world, especially, but not limited to, clients. This is what proxies do, too.

Question 11

D. The Value Object design pattern reduces the number of remote network method calls required to obtain the attribute values from the entity beans. Although the four patterns in the answers do this, it's the main reason for using a Value Object.

Question 12

B. The Data Access Object design pattern is usually a good candidate to work with data that is remote or and costly to query often, but becomes a bad choice with container-managed persistence. This is tricky because the container often, but not always, will persist data as a primary function.

Previous Chapter: Quick Recap - Chapters 51 to 58

Next Chapter: Chapter 59 - Exam Preparation Tips

Quick Recap: Chapters 51 to 58

Let us quickly review whatever we learnt about Design Patterns in the previous few chapters

• A design pattern describes a proven solution to a recurring design problem, placing particular emphasis on the context and forces surrounding the problem, and the consequences and impact of the solution
• There are 5 design patterns in the SCWCD Exam:
     o Value Object Pattern
     o Data Access Object Pattern
     o Business Delegate Pattern
     o Model View Controller Pattern &
     o Front Controller Pattern
• The Value Object pattern provides the best way to exchange data across tiers or system boundaries, especially when there is network communication involved. This is a pattern that solves performance issues around network latency
• The DAO pattern provides the connection between the business logic tier and the resource (usually a database) tier. The Data Access Object represents a general interface to the resources layer: It handles all calls to it. JDBC is the most commonly used example of this
• The Business Delegate pattern reduces the dependency between tiers. It is an attempt to make tiers interchangeable so one can access or utilize the services of any other
• The Model-View-Controller architecture compartmentalizes the data and business logic (model) from the presentation (view) from the user action interpreter (controller).
• The Front Controller pattern presents one entry point to a Web site or service. It provides a centralized entry point that controls and manages Web request handling. It eliminates the dependency of the user on a direct resource.

The Key Terms we learnt in the previous few chapters are:

• Design Patterns
• Model-View-Controller
• Value Object
• Data Access Object
• Front Controller
• Business Delegate

Previous Chapter: Chapter 58 - Other Design Patterns

Next Chapter: Self Test - Chapters 51 to 58

Chapter 58: Design Patterns Beyond the SCWCD Exam

Design Patterns is a very big subject and we could just go on and on and on about them. The good news is that, the SCWCD exam covers only 5 design patterns which we have already seen. So, if you want you can conveniently ignore this chapter. But, I strongly urge you to read it, not to memorize but to improve your understanding of design patterns.

So, lets get started!!!

Other Design Patterns:

There are numerous other design patterns that are in use in the programming world. They are categorized into various types based on their purpose. Let us take a look at their categories and names.

1. Architectural Patterns
      a. Decorator Pattern
      b. Front Controller
      c. Model View Controller
2. Advanced Architectural Patterns
      a. Composite View Pattern
      b. Service to Worker Pattern
      c. View Helper Pattern
3. Scalability Patterns
      a. Asynchronous Page Pattern
      b. Caching Filter Pattern
      c. Resource Pool Pattern
4. Business Tier Patterns
      a. Entity Facade Pattern
5. Data Transfer Patterns
      a. Data Transfer Hash Pattern
      b. Data Transfer Object (DTO) Pattern
      c. Row Set DTO Pattern
6. Database Patterns
      a. DAO Factory
      b. Data Access Object (DAO) Pattern
      c. Lazy Load Pattern
      d. Procedure Access Object Pattern
      e. Serialized Entity Pattern
      f. Table Inheritance Pattern
      g. Tuple Table Pattern
7. Business Tier Interface Patterns
      a. Business Delegate Pattern
      b. Business Delegate Factory
      c. Service Adapter Pattern
      d. Service Locator Pattern
      e. Session Facade Pattern
8. Concurrency Patterns
      a. ACID Transaction Pattern
      b. Lockable Object Pattern
      c. Lock Manager Pattern
      d. Optimistic Concurrency Pattern
      e. Pessimistic Concurrency Pattern
      f. Transactional Context Pattern
      g. Version Number Pattern

As you can see, there are numerous other patterns in use and to be honest, this list is not exhaustive. This is purely a FYI kind of chapter. Whatever you need to know about design patterns was already covered in the previous chapters, and this chapter is just to tell you that, those 5 are just a drop in the ocean and not the whole thing.

Previous Chapter: Chapter 57 - Front Controller Pattern

Next Chapter: Quick Recap - Chapters 51 to 58

Chapter 57: Front Controller Pattern

This chapter is going to deal with the last pattern on the SCWCD exam – The Front Controller Pattern.

What is Front Controller Pattern?

The Front Controller pattern presents one entry point to a Web site or service. It provides a centralized entry point that controls and manages Web request handling. It eliminates the dependency of the user on a direct resource. Suppose you wanted to get the latest version of the servlet specification. You would be better off going to a central page that presents options that change over time than bookmarking the servlet specification directly as your bookmark might get outdated if a new version of the specification is hosted in a different page.

Is

This pattern is a presentation controller that allows the resources to change without breaking all the bookmarks to a given resource. Many sites use this. For example, Microsoft often changes the content in its MSDN library. However, there is front end for it that rarely changes. This way, you can bookmark that front-end URL and not worry about what they do behind it.

Is Not

This is not a pattern for a data storage viewer. It isn't a way for you to control data retrieval. Rather, it is a steady interface to the underlying Web resources that behave as the presentation tier.

Analogy

This pattern is like a travel agent. On every trip you start by stopping at the agency. You tell the agent where you want to go and she will take care of the arrangements. The actual flight, train, bus, and hotel details change between trips, but she always helps you get there.

Problem

When the user accesses resources directly without going through a centralized mechanism, the resource may have moved. Also, each view is on its own and required to provide its own system services. Lastly, each view has to provide navigation, but this is a problem as it doesn't know about the context or the global site.

Responsibility

This controller must delegate the request to the proper resource and view.

Aim

This pattern isolates the actual resources from direct access by the user.

Primary Activity

This pattern matches the correct resource to the request.

Context

Simplified Web sites expose all its resources directly. As a site grows, there comes a time when it is better to decouple the navigation from the resources. There needs to be a controller that manages the requests and decides which resource best satisfies the request.

Benefits

• It is better to have a central controller allocate shared resources rather than have individual resources fend for themselves independently.
• The location of resources may change.
• This pattern adds only a little more work to building a Web site at first.
• Multiple resources share common needs such as security (that is, authentication and authorization).

Usage

Large Web sites especially benefit from a front controller.

Consequences

• Caching is always good between parts that exchange a lot of data.
• This pattern changes the interface with the intent of making the API more stable from the presentation tier perspective.
• This pattern will now handle any exceptions, whether from the business tier itself or from the plumbing between it and the requester.
• This pattern isolates the presentation and the business tiers by adding a mediator between the two, making it easier to manage changes on either side.

Uses

• Servlet Front Strategy— This pattern is implemented as a servlet, which manages the aspects of request handling that are related to business processing and control flow. Because this strategy is not specifically related to display formatting, it is a bad idea to implement this component as a JSP page.
• Command and Controller Strategy— This strategy provides a generic interface to the helper components. The controller delegates responsibility to the helper components, which minimizes the coupling among these components.
• Logical Resource Mapping Strategy— In this case users request logical names rather than physical locations. This way the physical location can be mapped to the logical names dynamically, say, in a database or XML document.

Other Related Patterns

• View Helper Pattern— The Front Controller is combined with the View Helper pattern to provide containers for factoring business logic out of the view and to provide a central point of control and dispatch. Logic is factored forward into the front controller and back into the Helpers.
• Service to Worker— The Service to Worker pattern is the result of combining the View Helper Pattern with a Dispatcher, in coordination with the Front Controller pattern.
• Dispatcher View— The Dispatcher View pattern is the result of combining the View Helper Pattern with a Dispatcher, in coordination with the Front Controller pattern.

Previous Chapter: Chapter 56 - MVC Pattern

Next chapter: Chapter 58 - Other Design Patterns

Chapter 56: Model View Controller Pattern

In this chapter, we are going to take a look at one of the most commonly used design patterns in J2EE Application development – the Model View Controller – MVC Pattern.

What is the Model View Controller Design Pattern?

The Model-View-Controller architecture compartmentalizes the data and business logic (model) from the presentation (view) from the user action interpreter (controller). This pattern is the hardest on the exam. The idea is closely related to the recent move from two-tier to three-tier architectures. The 3 tiers in a MVC Architecture of a J2EE Application are:

1. Model – Usually JavaBeans
2. View – Usually JSPs
3. Controller – Usually Servlets

Is

This pattern is a clear functional separation of roles. It is a formalization of the data-business-presentation movement that dominated three-tier architectures over the last decade.

Is Not

This pattern is very abstract. It is not simply a front end to a datasource connection.

Analogy

This would be like an automobile. The speed of a car is affected by the accelerator pedal (Controller), the speed is shown by the speedometer (View), and the speed is determined by the engine power (Model).

Problem

Different views of the same data are a common need. Conversely, the same client needs access to different models.

Responsibility

This pattern carefully manages communication between the client and model data and functionality. It must allow changing the client or changing the model with minimal impact on the system.

Aim

The main goal is separation of concerns. This pattern attempts to minimize the impact of changing any of the three pieces.

Primary Activity

This pattern decouples views from data and business logic; MVC interjects a controller between them, which interprets user actions into operations on the business logic and the selection of the next view to send to the user.

Context

An application is expected to support varying client and business logic tiers.

Benefits

• Various clients and data models are being developed. These two tiers need to talk to each other.
• Non-interface-specific code is duplicated in many applications.
• The same enterprise data will be accessed by different views: for example, HTML, WML, JFC/Swing, and XML.
• The same enterprise data will be accessed (requested, modified, and deleted) from various actions (HTML links, JFC/Swing events, SOAP XML calls).

Usage

Although the primary purpose of MVC is for building UIs, it can be used to establish an analogous notification protocol between non-visual objects. The Observer/Observable objects in java.util were designed with this pattern in mind.

Consequences

• Clients access a controller that accesses the model instead of the data directly.
• Another layer has to be built which adds work.
• It is easier to break a project into pieces because both the view and model developers are targeting the controller API.

Uses

Almost all J2EE applications use the MVC Pattern. Even JFC Swings technology of Java uses the MVC Pattern. Also, Struts and Velocity use this pattern as their underlying framework.

Previous Chapter: Chapter 55 - Business Delegate Pattern

Next chapter: Chapter 57 - Front Controller Pattern

Chapter 55: Business Delegate Pattern

In this chapter, we are going to take a detailed look at the Business Delegate Pattern.

What is Business Delegate Pattern?

The Business Delegate pattern reduces the dependency between tiers. It is an attempt to make tiers interchangeable so one can access or utilize the services of any other.

Is

This pattern is a proxy that hides the complexity of remote service lookup and error recovery. It makes it easier to communicate requests and results from one layer to another.

Is Not

This is not a pattern for a layer itself. It isn't a way for you to create a business logic component or structure. Rather, it is an interface to a tier so that you can change the underlying components and not disturb the presentation tier.

Analogy

This pattern is like an ambassador. Like all good ambassadors, it can pass on the message from the host country to any other.

Problem

Whenever there is a dependency on a remote service, the probability of change between the caller and the called increases. How can you reduce the chances of the layer depending on the remote service breaking should the remote service change? This pattern helps protect the local layer from changes made to the remote service.
Ex: Lets say, the presentation tier interacts directly with a remote business logic layer. What if the business services change and the old API becomes invalid? If this happens the presentation tier will break.

Responsibility

This delegate is the proxy between the local layer and the remote service layer. It is responsible for reliably allowing the front layer to access the remote service.

Aim

This pattern isolates the presentation layer from changes in the business tier API.

Primary Activity

This pattern matches presentation component calls to the correct business tier methods.

Context

The current approach to multi-tier systems is to couple the presentation tier directly to the entire business service API; sometimes this coupling is made across a network.

Benefits

• Presentation-tier clients (including devices) need access to business services.
• The business tier API may change.
• The industry trend for large systems is to minimize coupling between presentation-tier clients and the business service API. This isolates the two so that a change in either side can be managed by the middle layer.
• There is a need for a cache between tiers.
• This pattern adds more work to building a system.

Usage

Large systems change components often. There is often a change in the business tier that breaks the access portion of clients.

Consequences

• Caching is always good between parts that exchange a lot of data.
• This pattern changes the interface with the intent of making the API more stable from the presentation tier perspective.
• This pattern will now handle any exceptions, whether from the business tier itself or from the plumbing between it and the requester.
• This pattern isolates the presentation and the business tiers from each other by adding a director between the two, making it is easier to manage changes on either side.

Uses

• B2B systems usually employ an XML exchange for communicating between disparate systems.
• Proxy services represent this pattern.
• Look up services usually represent this pattern, too.
• This pattern can be thought of as an underlying design feature of Java's overloading capability such as the System.out.print() group of methods. Using the same method name, you can print almost anything to the console, because the printing service handles the different data types. This pattern is bigger than that, but overloading illustrates the idea.

Other Related Patterns

• Service Locator Pattern— This pattern provides a common API for any business service lookup and access code.
• Proxy Pattern— Provides a stand-in for objects in the business tier.
• Adapter Pattern— You can use the Adapter pattern to provide coupling for disparate systems.

Previous Chapter: Chapter 54 - DAO Pattern

Next Chapter: Chapter 56 - MVC Pattern

Chapter 54: Data Access Object Pattern

In this chapter, we are going to take a detailed look at the DAO or Data Access Object Design Pattern.

What is Data Access Object Pattern?

The DAO pattern provides the connection between the business logic tier and the resource (usually a database) tier. The Data Access Object represents a general interface to the resources layer: It handles all calls to it. JDBC is the most commonly used example of this. Almost all J2EE Applications that access the database have a direct or indirect implementation of the DAO Pattern.

Is

This pattern is an object that encapsulates a set of behaviors for accessing databases, files, and other resources. This way you have only one API to deal with rather than a different one for every type of resource.

Is Not

This is not a pattern for a resource itself. Frankly speaking, this isn't a way to build a database or file manager.

Analogy

This is like using an ATM machine. The same interface will fetch the information requested from the back end, even though the bank changed database products the previous week.

Problem

Applications often need to use persistent data. This data persists in many forms such as files, relational databases, XML storage, and other types of repositories. All these stores have different APIs. Interfacing with so many APIs presents a problem when designing clients.

Responsibility

This pattern provides a uniform API to any persistent data storage.

Aim

This pattern attempts to consolidate the accessing of data from a complex source or set of sources to one object. This will reduce the network overhead by minimizing the number of network calls to get data, but the reduction of network traffic is not the main intention of this pattern.

Primary Activity

Getting and setting data from and to a permanent data source.

Context

Access methods to data vary between types of storage and vendor.

Benefits

Various parts of an application require access to persistent stores like databases and files. The APIs are inconsistent between types of stores and even between different vendors of the same type of storage. There needs to be a layer that has a uniform API to access these disparate data sources.

Usage

Any application that requires access to several data source types or even an application that accesses only one, but may switch in the future. The SQL is encapsulated in the method. That way if the SQL or datasource change, the layers above won't because the API remains constant.

Consequences

• Clients and components can now access data with the same API, which makes the variety of sources transparent and reduces complexity.
• This makes changing data sources easy and reduces errors.

Uses

At one level, JDBC uses an Abstract Factory technique to provide one API to many databases and types of files; the very essence of this pattern. However, the emphasis Sun places on this pattern is that of encapsulating the SQL so the implementation of actually querying the database is hidden from the next layer.

Other Related Patterns

Abstract Factory: Sun uses this factory for data access object strategy. They base it on the abstract factory method.

Previous Chapter: Chapter 53 - Value Object Pattern

Next Chapter: Chapter 55 - Business Delegate Pattern

Chapter 53: Value Object Pattern

Value Object
In this chapter, we are going to take a detailed look at the Value Object Pattern.

What is Value Object Pattern?

The Value Object pattern provides the best way to exchange data across tiers or system boundaries, especially when there is network communication involved. This is a pattern that solves performance issues around network latency. Do I have to tell you that, this is a very useful pattern?

Is

This pattern is an object that encapsulates a set of values that is moved across the boundary so that attempts to get the values of those attributes are local calls.

Is Not

This pattern is not a concrete object. You wouldn't use it to create an object. You could use it to hold values of that object.

Analogy

This would be like placing several letters in a box to be mailed once a week instead of mailing the letters separately and multiple times over the week. The box is mailed once. When the box arrives, the mail carrier can just reach in the box for the next letter; she doesn't have to contact the origin, which would take a long time.

Problem

In J2EE, server-resident business applications often use session beans and entity beans. The session beans are responsible for functionality that is involved in one-to-one transactions with the client. In contrast, the entity beans are used to handle persistent data. So, the client will make many calls to the session bean to get data. That represents a lot of traffic, to and from a remote location because the bean may be at a server at a remote location. Likewise, the session bean may make many calls to the entity bean getting and setting attributes. The Value Object pattern encapsulates the data fields of an entity bean; VO has nothing to do with session beans (except that it is usually a session method call that returns a VO, instead of a remote entity reference).

This activity is inefficient. We need a way to eliminate all these potential network calls reducing overhead and providing a more direct access approach.

Responsibility

This pattern provides a mechanism to exchange many remote calls to local, direct calls.

Aim

This pattern attempts to reduce the network overhead by minimizing the number of network calls to get data from the business tier.

Primary Activity

Used to collect remote data into an object that is sent to the client, so now the client makes local calls to get values rather than remote ones.

Context

Multi-tier applications that need to exchange sets of data between the client and server often.

Benefits

• J2EE applications often use enterprise beans. All calls to these beans are performed via remote interfaces to the bean due to Java's architecture. This introduces overhead.
• The frequency of reads is greater than updates because the client gets the data from the business tier for presentation.
• The client usually needs a set of data, not just one attribute.
• Client calls to enterprise beans accessed over the network affects WebApp performance because of the sum of network latency of multiple attribute access to the entity bean.
• Regardless of Java's bean architecture, it would be better to collect attributes into one object and get them from it rather than make invoking remote methods for the same information.

Usage

This pattern is useful when you need a collection of data from a remote source or, more likely, when a client has to make several calls for data from entity beans.

Consequences

• Simplifies Entity Bean and Remote Interface— Sun suggests using getData() and setData() methods on certain entity beans as a way to get and set a value object containing the set of attribute values. Calling the getData() method once replaces multiple calls to get methods. Likewise, the setData() method replaces many set calls.
• Using this pattern transfers a set of values in one method call improving overall performance, especially over the network. It represents coarse versus fine-grained interfaces.
• The client can update, delete, and read the values that are now local at will. When done, it can update the data source in one call. However, there may be a problem with synchronization as the other clients won't know about the changes until the update call. In the case of updates, there can be two conflicting update calls by two clients, so this must be synchronized somehow.

Uses

The ResultSet of JDBC is a collection of data returned from the data source resulting from a query. The data is now local in the ResultSet object so all calls to it are local rather than many calls to the data source directly.

Other Related Patterns

• Aggregate Entity that uses Value Object to get data across tiers.
• Session Fa├žade, which is the business interface for clients of J2EE applications. This pattern often uses value objects as an exchange mechanism with participating entity beans.
• Value List Handler is another pattern that provides lists of value objects constructed dynamically by accessing the persistent store at request time.
• Value Object Assembler builds composite value objects from different data sources. The data sources are usually session beans or entity beans that may be requested to provide their data as value objects.

Previous Chapter: Chapter 52 - Design Pattern Elements

Next Chapter: Chapter 54 - Data Access Object Pattern

Chapter 52: Design Pattern Elements

Before we dig into the specifics of the Design Patterns that are part of the SCWCD Exam, we need to know one important thing. “The Elements of a Design Pattern”. This is what you are going to learn in this chapter.

So, lets get started!!!

Elements of a Design Pattern:

There are many ways to define a pattern, but the classical way is to describe its elements, or the aspects of a pattern.

The 3 main elements in any Design pattern are:
• Context
• Problem and
• Solution

The following are their definitions:
• Context is the recurring situation in which a problem to be solved is found.
• Problems are the so-called forces, such as marketing and technological forces, that occur in this context.
• Solution is the defined design that reorganizes or manipulates, some say resolves, the problem forces into a desired outcome within that context.
The design pattern is not only these three, but the relationship between the three and the formal language that describes the whole business.

For the sake of easy understanding & explanation, the following are the elements that would be used while explaining each of the design patterns that are covered in this series:
• Is — A direct explanation of what the pattern is.
• Is Not — An attempt at contrasting the concept because it is often helpful to understand what something is by looking at what it isn't.
• Analogy — This provides a comparison based on general aspects. Analogies, hopefully, give you a way to connect what you already know to these patterns which may be new to you.
• Problem — A statement of the problem that describes the patterns reason/purpose and intent.
• Responsibility — This describes what the pattern is accountable for; the primary things it accomplishes.
• Aim — These are the goals and objectives the pattern should reach within the given context.
• Primary Activity — What the main activities done by the pattern are.
• Context — The conditions and environment in which the problem and its solution recur. In other words, where should you consider and apply this pattern?
• Benefits — Why use a particular pattern, its benefits or advantages.
• Usage — Which kinds of situations are good candidates for this pattern.
• Consequences — This describes the result of using the pattern, the final state of the system. There are good and bad consequences of applying the pattern. It may solve one problem, but give rise to a new one.
• Uses — This tells you one or more examples of how this pattern is being used.
• Other Related Patterns — This names other patterns that are related by context, solution, or consequences. The related pattern may solve the same problem in another way or share the same context, but resolve different forces.

Patterns on the Exam

From the SCWCD Exam perspective, you need to worry about only 5 patters and we will be covering all of them, one by one. As a precursor, the 5 patters are:
1. Value Object
2. Data Access Object
3. Business Delegate
4. Front Controller &
5. Model View Controller (MVC)

Exam Trivia:
If you see any other pattern name, ignore it unless the question is one of those about which one is not a pattern.

Previous Chapter: Chapter 51 - Introduction to Design Patterns

Next chapter: Chapter 53 - Value Object Pattern

Chapter 51: Introduction to Design Patterns

Design Patterns are a very important topic from the SCWCD Exam perspective as well as from being a J2EE Programmer perspective. Any experienced J2EE programmer is expected to know about a few of the J2EE Design Patterns. These patterns are used extensively and are very useful to create enterprise class J2EE Web Applications. In this next few chapters, we are going to look in detail, some of the most commonly used Design Patters (Of Course, only the ones that are part of the SCWCD Exam)

This chapter, is going to be a short and sweet introduction to the J2EE Design Patterns.

So, lets get started!!!

A word of Caution: This chapter assumes you've read the previous chapters (well, obviously) and that you are familiar with object-oriented programming concepts, including the popular UML diagramming notation.

History of Design Patterns

The term “pattern” comes from the architect Christopher Alexander who wrote several books on Construction and Building. Although he was interested in urban planning and building architecture, his notions were clearly useful in many areas. Alexander, a building architect, was the first to “codify” patterns for architecture. Alexander didn't invent the idea of patterns nor was he the first to see them in designs. Of course, they were there before him, but his work on urban planning and building architecture isolated the idea better than anyone before him. Alexander was an architect extraordinaire. He is one of those rare people who take a step back and question why people do things the way they do. He gave the result of his inquiry the name Pattern Language and defined it at length in his seminal book by the same name.

While Alexander was thinking buildings and foundations, it became clear to many that his design patterns were abstract enough to be useful elsewhere. That is when the Gang of Four (GoF as we will refer to them henceforth), as Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides are now known, applied his patterns to software in their classic Design Patterns: Elements of Reusable Object-Oriented Software (1995, Addison-Wesley). It took a while, but the GoF have started a ground swell. There are now dozens of books, and numerous websites in the internet, about design patterns.

What is a Design Pattern?

Design patterns are often defined as “a solution to a problem in a context.” This falls short of the abstract definition that experts prefer.

Sun defines them in the following way: “A design pattern describes a proven solution to a recurring design problem, placing particular emphasis on the context and forces surrounding the problem, and the consequences and impact of the solution.”

Design Patterns are everywhere and are used (knowingly or unknowingly) by almost all J2EE Developers. Don’t worry my friend, you will be using them too and by the time you are done reading the next few chapters, you will be a Design Pattern Expert.

Previous Chapter: Self Test - Chapters 47 to 50

Next Chapter: Chapter 52 - Design Pattern Elements

Self Test: Chapters 47 to 50

Questions:

Question 1:

Which two statements apply to the following code snippet? (Choose two.)
< servlet >
< servlet-name >
testServlet
< /servlet-name >
< servlet-class >
myPackage.MyTestServlet
< /servlet-class >
< /servlet >

A. It is a mapping between a servlet name and the fully-qualified name of the servlet class.
B. It is a map between a URL and a servlet.
C. This code belongs in the WebApp deployment descriptor.
D. It tells the container where to install the servlet.

Question 2:

Which two of the following statements most closely relate to HTTPS Client Authentication?
A. It uses a Status-Code element (three-digit integer).
B. It uses predefined form fields.
C. It is the most secure form of authentication.
D. It uses SSL.

Question 3:

Which directory is the location for myApp.jar?
A. /WEB-INF/
B. /WEB-INF/classes/
C. /WEB-INF/lib/D. /

Question 4:

In which two elements can you define initialization parameters?
A. servlet
B. context-param
C. welcome-file
D. login-config

Question 5:

Which three of the following are elements of the Web Application Descriptor?
A. servlet
B. context-param
C. listener
D. error

Question 6:

What is the configuration that the deployment descriptor uses to handle each exception?
A. error-page
B. exception
C. error
D. exception-page

Question 7:

What is the deployment descriptor file named?
A. server.conf
B. server.xml
C. web.xml
D. web.conf

Question 8:

Which directory is the location for Web application class files?
A. /WEB-INF/
B. /WEB-INF/classes/
C. /WEB-INF/classpath/
D. /META-INF/classes

Question 9:

What does the security-role element do?
A. It configures the authentication method that should be used by the form login mechanism.
B. It defines the status codes for security breaches.
C. It contains a mapping between an error code or exception type to the path of a resource in the Web application.
D. It describes and names the security role.

Question 10:

Which directory is the location for the deployment descriptor?
A. /WEB-INF/
B. /WEB-INF/classes/
C. /WEB-INF/lib/D. /

Question 11:

Which of the following best defines authentication?
A. The means used to prove that information has not been modified by a third party while in transit.
B. This is access control where interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.
C. You have permission to use a given page.
D. The means by which communicating entities prove to one another that they are acting on behalf of specific identities.

Question 12:

What is the best definition for auditing?
A. This is access control where it defines who can interact with what resources.
B. Maintaining a record of Web application activity.
C. This is a check of the Web application when it is used for commercial transactions.
D. This prevents Web site attacks.

Answers:

Question 1:

A and C. The servlet element establishes a mapping between a servlet name and the fully-qualified name of the servlet class. You would place this code in the WebApp deployment descriptor.

Question 2:
C and D. This is end user authentication using HTTPS (HTTP over SSL). This mechanism uses public key encryption that requires the user to possess a Public Key Certificate (PKC). This is the highest level security of the four here.

Question 3:

C. The jar files go in the /WEB-INF/lib/ directory.

Question 4:

A and B. The initialization parameters are defined in both the context-param and the servlet elements of the Web deployment descriptor.

Question 5:

A, B, and C. All of these are elements except there is no error element. It should have been error-page.

Question 6:

A. The error-page element, which defines what resource the container should use for a given exception.
< web-app >
< error-page >
< error-code >404< / error-code >
< location > /404.html < /location >
< /error-page >
< /web-app >


Question 7:

C. web.xml is the deployment descriptor file.

Question 8:

B. You place your servlets and utility classes in /WEB-INF/classes/.

Question 9:

D. The security-role element contains the definition of a security role. The definition consists of an optional description of the security role, and the security role name.

Question 10:

A. web.xml is the deployment descriptor file in /WEB-INF/web.xml.

Question 11:

D. Authentication is the means by which communicating entities prove to one another that they are acting on behalf of specific identities. In other words, it is the attempt to prove that you are really you.

Question 12:

B. Maintain a record of Web application activity. For example, you can log resource accesses including times and requester IP and ID. This usually involves a log somewhere.

Previous Chapter: Quick Recap - Chapters 47 to 50

Next Chapter: Chapter 51 - Introduction to Design Patterns
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers