• No se han encontrado resultados

CUÁL ES LA CAUSA DE QUE LOS NUESTROS NO TENGAN NINGUNA HISTORIA ESCRITA DE SUS HECHOS

In document SEBASTIÁN FOX MORCILLO: (página 106-111)

Problem: Since web applications are deployed as WAR files on the application server’s web container, the full path and relative paths to these files vary for each server.

Solution -1: You can configure the file paths in web.xml using <init-param> tags and retrieve file paths in your Servlets/JSPs. But this technique requires changes to the web.xml deployment descriptor file, to point to the correct path.

Solution -2: You can overcome these configuration issues by using the features of java.lang.ClassLoader and javax.servlet.ServletContext classes. There are various ways of reading a file using the ServletContext API methods such as getResource(String resource),getResourceAsStream(String resource), getResourcePaths(String path) and getRealPath(String path). The getRealPath(String path) method translates virtual URL into real path refer Q26 in Enterprise section.

//Get the file “products.xml” under the WEB-INF folder of your application as inputstream InputStream is = config.getServletContext().getResourceAsStream(“/products.xml”);

Alternatively you can use the APIs from ClassLoader as follows. The file “products.xml” should be placed under WEB-INF/classes directory where all web application classes reside.

//Get the URL for the file and create a stream explicitly

URL url = config.getServletContext().getResource(“/products.xml”);

BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream));

OR //use the context class loader

URL url = Thread.currentThread().getContextClassLoader().getResource(“products-out.xml”);

BufferedWriter bw = new BufferedWriter(new FileWriter(url.getFile());

Q. How do you send a file to a browser from your web application? I.e. how do you download a file from your web application? Files can be downloaded from a web application by using the right combination of headers.

//set the header to a non-standard value for attachments to be saved by the browser with the //Save-As dialog so that it is unrecognized by the browsers because often browsers try to do //something special when they recognize the content-type.

response.setContentType(“application/x-download”);

//use Content-Disposition “attachment” to invoke “Save As” dialog and “inline” for displaying //the file content on the browser without invoking the “Save As” dialog.

response.setHeader(“Content-disposition”, “attachment;filename=” + fileName);

Q. How do you send a file from a browser to your web application? i.e. How do you upload a file to your web application?

There are better and more secured ways to upload your files instead of using using web. For example FTP, secure FTP etc. But if you need to do it via your web application then your default encoding and GET methods are not suitable for file upload and a form containing file input fields must specify the encoding type “multipart/form-data” and the POST method in the <form ..> tag as shown below:

<form enctype=”multipart/form-data” method=”POST” action=”/MyServlet”>

<input type=”file” name=”products” />

<input type=”submit” name=”Upload” value=”upload” />

</form>

When the user clicks the “Upload” button, the client browser locates the local file and sends it to the server using HTTP POST. When it reaches your server, your implementing servlet should process the POST data in order to extract the encoded file. Unfortunately, application servers implementing the Servlet and JSP specifications are not required to handle the multipart/form-data encoding. Fortunately there are number of libraries available such as Apache Commons File Upload, which is a small Java package that lets you obtain the content of the uploaded file from the encoded form data. The API of this package is flexible enough to keep small files in memory while large files are stored on disk in a “temp” directory. You can specify a size threshold to determine when to keep in memory and when to write to disk.

Q 21: If an object is stored in a session and subsequently you change the state of the object, will this state change replicated to all the other distributed sessions in the cluster? DC SI

A 21: No. Session replication is the term that is used when your current service state is being replicated across multiple application instances. Session replication occurs when we replicate the information (i.e. session attributes) that are stored in your HttpSession. The container propagates the changes only when you call the setAttribute(……) method. So mutating the objects in a session and then by-passing the setAttribute(………..) will not replicate the state change. CO

Example If you have an ArrayList in the session representing shopping cart objects and if you just call getAttribute(…) to retrieve the ArrayList and then add or change something without calling the setAttribute(…) then the container may not know that you have added or changed something in the ArrayList. So the session will not be replicated.

Q 22: What is a filter, and how does it work? LF DP FAQ

A 22: A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses but typically do not themselves create responses. Filters can also be used to transform the response from the Servlet or JSP before sending it back to client. Filters improve reusability by placing recurring tasks in the filter as a reusable unit.

W e b C o n t a in e r

S e r v le t, J S P , H T M L

F ilte r 2 F ilte r 3

F ilte r 1

Request Response

C lie n t

F ilt e r

A good way to think of Servlet filters is as a chain of steps that a request and response must go through before reaching a Servlet, JSP, or static resource such as an HTML page in a Web application.

The filters can be used for caching and compressing content, logging and auditing, image conversions (scaling up or down etc), authenticating incoming requests, XSL transformation of XML content, localization of the request and the response, site hit count etc. The filters are configured through the web.xml file as follows:

<web-app>

<filter>

<filter-name>HitCounterFilter</filter-name>

<filter-class>myPkg.HitCounterFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>HitCounterFilter</filter-name>

<url-pattern>/usersection/*</url-pattern>

</filter-mapping>

...

</web-app>

The HitCounterFilter will intercept the requests from the URL pattern /usersection followed by any resource name.

Design Pattern: Servlet filters use the slightly modified version of the chain of responsibility design pattern.

Unlike the classic (only one object in the chain handle the request) chain of responsibility where filters allow multiple objects (filters) in a chain to handle the request. If you want to modify the request or the response in the chain you can use the decorator pattern (Refer Q11 in How would you go about… section).

Q 23: Explain declarative security for Web applications? SE

A 23: Servlet containers implement declarative security. The administration is done through the deployment descriptor web.xml file. With declarative security the Servlets and JSP pages will be free from any security aware code.

You can protect your URLs through web.xml as shown below:

web-app>

<security-constraint>

<web-resource-collection>

<web-resource-name>PrivateAndSensitive</web-resource-name>

<url-pattern>/private/*</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>executive</role-name>

<role-name>admin</role-name>

</auth-constraint>

</security-constraint>

<!-- form based authorization -->

<login-config>

<auth-method>FORM</auth-method>

<form-login-config>

<form-login-page>/login.jsp</form-login-page>

<form-error-page>/error.jsp</form-error-page>

</form-login-config>

</login-config>

</web-app>

The user will be prompted for the configured login.jsp when restricted resources are accessed. The container also keeps track of which users have been previously authenticated.

Benefits: Very little coding is required and developers can concentrate on the application they are building and system administrators can administer the security settings without or with minimal developer intervention. Let’s look at a sample programmatic security in a Web module like a servlet: CO

User user = new User();

Principal principal = request.getUserPrincipal();

if (request.isUserInRole("boss")) user.setRole(user.BOSS_ROLE);

Q 24: Explain the Front Controller design pattern or explain J2EE design patterns? DP FAQ

A 24: Problem: A J2EE system requires a centralized access point for HTTP request handling to support the integration of system services like security, data validation etc, content retrieval, view management, and dispatching. When the user accesses the view directly without going through a centralized mechanism, two problems may occur:

ƒ Each view is required to provide its own system services often resulting in duplicate code.

ƒ View navigation is left to the views. This may result in shared code for view content and view navigation.

ƒ Distributed control is more difficult to maintain, since changes will often need to be made in numerous places.

Solution: Generally you write specific servlets for specific request handling. These servlets are responsible for data validation, error handling, invoking business services and finally forwarding the request to a specific JSP view to display the results to the user.

J2EE Front Controller Pattern

Client FrontController ApplicationFlowController

View

Command (eg: Struts Action)

<<servlet>>

FrontControllerServlet <<JSP>>

FrontControllerJSP client

request delegates

dispatches

invokes

The Front Controller suggests that we only have one Servlet (instead of having specific Servlet for each specific request) centralizing the handling of all the requests and delegating the functions like validation, invoking business services etc to a command or a helper component. For example Struts framework uses the command design pattern to delegate the business services to an action class.

Benefits

ƒ Avoid duplicating the control logic like security check, flow control etc.

ƒ Apply the common logic, which is shared by multiple requests in the Front controller.

ƒ Separate the system processing logic from the view processing logic.

ƒ Provides a controlled and centralized access point for your system.

Q 25: Briefly discuss the following patterns Composite view, View helper, Dispatcher view and Service to worker? Or explain J2EE design patterns? DP FAQ

A 25:

ƒ Composite View: Creates an aggregate view from atomic sub-views. The Composite view entirely focuses on the view. The view is typically a JSP page, which has the HTML, JSP Tags etc. The JSP display pages mostly have a side bar, header, footer and main content area. These are the views of the view. The sub-views can be either static or dynamic. The best practice is to have these sub-sub-views as separate JSP pages and include them in the whole view. This will enable reuse of JSP sub-views and improves maintainability by having to change them at one place only.

Composite View

BasicView

View CompositeView

1

ƒ View Helper: When processing logic is embedded inside the controller or view it causes code duplication in all the pages. This causes maintenance problems, as any change to piece of logic has to be done in all the views. In the view helper pattern the view delegates its processing responsibilities to its helper classes. The helper classes JavaBeans: used to compute and store the presentation data and Custom Tags: used for computation of logic and displaying them iteratively complement each other.

Benefits Avoids embedding programming logic in the views and facilitates division of labor between Java developers and Web page designers.

View Helper Pattern

Logic 3

With View Helpers like JavaBeans, CustomTags etc code for Logic-1 and Logic-2 are not duplicated hence more maintainable and reusable.

Servlet 1/JSP 1 Servlet 1/JSP 1

Logic 1 Logic 2

Logic 3

Servlet 2/JSP 2

Logic 1 Logic 2

Without View Helpers code for 1 and Logic-2 are duplicated within different servlets/JSPs

Logic 1 JavaBeans (Servlets,JSPs)

CustomTags (JSPs only)

Logic 2 JavaBeans (Servlets,JSPs)

CustomTags (JSPs only) Servlet 1/JSP 1

Logic 3

ƒ Service to Worker and Dispatcher View: These two patterns are a combination of Front Controller and View Helper patterns with a dispatcher component. One of the responsibilities of a Front Controller is choosing a view and dispatching the request to an appropriate view. This behavior can be partitioned into a separate component known as a dispatcher. But these two patterns differ in the way they suggest different division of responsibility among the components.

Service to Worker Dispatcher View

Combines the front controller (Refer Q24 in Enterprise section) and dispatcher, with views and view helpers (refer Q25 in Enterprise section) to handle client requests and dynamically prepares the response.

ƒ Controllers delegate the content retrieval to the view helpers, which populates the intermediate model content for the view.

ƒ Dispatcher is responsible for the view management and view navigation.

This pattern is structurally similar to the service to worker but the emphasis is on a different usage pattern. This combines the Front controller and the dispatcher with the view helpers but

ƒ Controller does not delegate content retrieval to view helpers because this activity is deferred to view processing.

ƒ Dispatcher is responsible for the view management and view navigation

Promotes more up-front work by the front controller and dispatcher for the authentication, authorization, content retrieval, validation, view management and navigation.

Relatively has a lightweight front controller and dispatcher with minimum functionality and most of the work is done by the view.

Q 26: Explain Servlet URL mapping? SF

Q 26: The “URL” denotes a virtual path and “File” denotes a real path of the resource.

S ervlet U R L m apping

http://<hostnam e:port>/<w ebapp nam e>/servlet /<pathnam e>/<resourcenam e>

http://localhost:8080/m yApps/servlet/m yP ath/M yS ervlet U R L

U R L eg

S E R V E R _H O M E \W ebA pps\m yA pps\W E B -IN F \C lasses\m yP ath\M yS ervlet File

S erver R oot D o cu m ent root

W e can define the servlet m apping in the w eb.xm l deploym net descriptor file as show n below :

<w eb-app>

<servlet>

<servlet-nam e> M yS ervlet</servlet-nam e>

<servlet-class> m yP ath.M yS ervlet</servlet-class>

</servlet>

<servlet-m apping>

<servlet-nam e> M yS ervlet</servlet-nam e>

<url-pattern>m ine/*.do</url-pattern>

</servlet-m apping>

<w eb-app>

http://localhost:8080/m yA pps/m ine/test.do U R L after m apping

N o te: W hich m eans every request w hich has a pattern of h ttp://lo calh ost:8080/m yA pp s/ m ine/*.do w ill be handled by the m yP ath .M yS ervlet class. (* denotes w ild character for any alphanum eric nam e). A lso possible to m ap M yS ervlet to the pattern of /m ine/* , the * indicates any resource nam e follow ed by /m ine.

The w ebapp nam e is defined in the application .xm l deploym ent descriptor file. The <context-root > denotes the w eb app nam eas show n below

<application>

...

<m odule id="W ebM odule_1">

<w eb>

<w eb-uri>m yA ppsW eb.w ar</w eb-uri>

<context-root> m yA pp s</context-root>

</w eb>

</m odule>

...

<m odule id="E jbM odule_1">

<ejb>m yE JB .jar</ejb>

</m odule>

...

</application>

H ow do w e get the w ebapp nam e "m yA pps"

W ithout M apping in w eb.xm l

W ith M apping in w eb.xm l deploym ent descriptor file

In the Model 2 MVC architecture, servlets process requests and select JSPs (discussed in next section) for views. So servlets act as controllers. Servlets intercept the incoming HTTP requests from the client (browser) and then dispatch the request to the business logic model (e.g. EJB, POJO - Plain Old Java Object, JavaBeans etc). Then select the next JSP view for display and deliver the view as HTML to client as the presentation (response). It is the best practice to use Web tier UI frameworks like Struts, Spring MVC, JavaServer Faces (JSF), Tapestry etc, which uses proven and tested design patterns for medium to large scale applications. Before you learn these frameworks, you should understand the web fundamentals relating to servlets, JSPs, HTTP request/response paradigm, state management, deployment structure, web container/application server services etc.

Enterprise - JSP

Desktop applications (e.g. Swing) are presentation-centric, which means when you click a menu item you know which window would be displayed and how it would look. Web applications are resource-centric as opposed to being presentation-centric. Web applications should be thought of as follows: A browser should request from a server a resource (not a page) and depending on the availability of that resource and the model state, server would generate different presentation like a regular “read-only” web page or a form with input controls, or a “page-not-found” message for the requested resource. So think in terms of resources, not pages.

Servlets and JSPs are server-side presentation-tier components managed by the web container within an application server. Web applications make use of http protocol, which is a stateless request-response based paradigm. JSP technology extends the servlet technology, which means anything you can do with a servlet you can do with a JSP as well.

Q 27: What’s wrong with Servlets? What is a JSP? What is it used for? What do you know about model 0, model 1 and model 2 patterns? In “model 2” architecture, if you set a request attribute in your JSP, would you be able to access it in your subsequent request within your servlet code? How do you prevent multiple submits due to repeated

“refresh button” clicks? What do you understand by the term JSP translation phase or compilation phase? SF FAQ

A 27: As shown in Q9 in Enterprise section, writing out.println (…) statements using servlet is cumbersome and hard to maintain, especially if you need to send a long HTML page with little dynamic code content. Worse still, every single change requires recompilation of your servlet.

JSP (request/response paradigm)

RMI/IIOP JNDI JTA JDBC JMS JavaMail JAF

Web Browser-1 client-1

Web Browser-3 client-2

crm.jsp

single instance of converted servlet from the jsp code you wrote handles requests from multiple browser instances by assigning a thread from

the thread-pool for each request.

Note: The converted servlet crm_jsp.class will contain all the required out.println(...) constructs, so that you do not have to write them.

In document SEBASTIÁN FOX MORCILLO: (página 106-111)