Java_J2EE_Job_Interview_Companion
.pdf120 |
Enterprise – Servlet |
|
|
|
|
|
|
|
redirecting - sendRedirect() |
Forward |
|
|
Sends a header back to the browser, which contains the name of |
Forward action takes place within the server without |
|
|
the resource to be redirected to. The browser will make a fresh |
the knowledge of the browser. Accepts relative path |
|
|
request from this header information. Need to provide absolute |
to the servlet or context root. |
|
|
URL path. |
|
|
|
Has an overhead of extra remote trip but has the advantage of |
No extra network trip. |
|
|
being able to refer to any resource on the same or different domain |
|
|
|
and also allows book marking of the page. |
|
|
|
|
|
|
Q 20: What are the considerations for servlet clustering? DCSI
A 20: The clustering promotes high availability and scalability. The considerations for servlet clustering are:
Objects stored in a session should be serializable to support in-memory replication of sessions. Also consider the overhead of serializing very large objects. Test the performance to make sure it is acceptable.
Design for idempotence. Failure of a request or impatient users clicking again can result in duplicate requests being submitted. So the Servlets should be able to tolerate duplicate requests.
Avoid using instance and static variables in read and write mode because different instances may exist on different JVMs. Any state should be held in an external resource such as a database.
Avoid storing values in a ServletContext. A ServletContext is not serializable and also the different instances may exist in different JVMs.
Avoid using java.io.* because the files may not exist on all backend machines. Instead use getResourceAsStream().
Q. How to perform I/O operations in a Servlet/JSP?
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);
Enterprise – Servlet |
121 |
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/formdata” 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? DCSI
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? LFDP 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.
|
F ilte r |
|
|
|
W e b C o n ta in e r |
|
|
|
|
|
S e rv le t, J S P , H T M L |
|
||
t |
F ilte r |
3 |
e |
|
u e s |
F ilte r |
2 |
o n s |
|
R e q |
R e s p |
|||
F ilte r |
1 |
|||
|
C lie n t |
|
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.
122 |
Enterprise – Servlet |
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:
124 |
Enterprise – Servlet |
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
Without ViewHelpers code for Logic-1 andLogic- |
WithViewHelpers like JavaBeans, CustomTags etc code for Logic-1 |
||
2 are duplicatedwithindifferent servlets/JSPs |
andLogic-2 are not duplicatedhence more maintainable andreusable. |
||
Servlet 1/JSP1 |
Servlet 1/JSP1 |
|
|
|
|
||
Logic 1 |
Logic 2 |
LogicLogic3 3 |
Logic 1 |
|
|
|
JavaBeans (Servlets,JSPs) |
|
|
|
CustomTags (JSPs only) |
Logic 3 |
|
|
|
Servlet 2/JSP2 |
Servlet 1/JSP1 |
Logic 2 |
|
|
|
|
JavaBeans (Servlets,JSPs) |
Logic 1 |
Logic 2 |
|
CustomTags (JSPs only) |
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 |
This pattern is structurally similar to the service to worker |
|
||
|
section) and dispatcher, with views and view helpers (refer |
but the emphasis is on a different usage pattern. This |
|
||
|
Q25 in Enterprise section) to handle client requests and |
combines the Front controller and the dispatcher with the |
|
||
|
dynamically prepares the response. |
view helpers but |
|
||
|
|
Controllers delegate the content retrieval to the view |
|
Controller does not delegate content retrieval to |
|
|
|
helpers, which populates the intermediate model |
|
view helpers because this activity is deferred to |
|
|
|
content for the view. |
|
view processing. |
|
|
|
Dispatcher is responsible for the view management |
|
Dispatcher is responsible for the view management |
|
|
|
and view navigation. |
|
and view navigation |
|
|
|
|
|
||
|
Promotes more up-front work by the front controller |
Relatively has a lightweight front controller and |
|
||
|
and dispatcher for the authentication, authorization, |
dispatcher with minimum functionality and most of the |
|
||
|
content retrieval, validation, view management and |
work is done by the view. |
|
||
|
navigation. |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Enterprise – Servlet |
125 |
Q 26: Explain Servlet URL mapping? SF
Q 26: The “URL” denotes a virtual path and “File” denotes a real path of the resource.
Servlet URL m apping
W ithout M apping in web.xm l
URL
URL eg
File
S erver R oot
D ocum ent root
W ith M apping in w eb.xm l deploym ent descriptor file
W e can define the servlet m apping in the w eb.xm l deploym net descriptor file as shown below: <w eb-app>
<servlet>
<servlet-nam e> M yServlet</servlet-nam e> <servlet-class> m yPath.M yServlet</servlet-class>
</servlet>
<servlet-m apping>
<servlet-nam e>M yServlet</servlet-nam e> <url-pattern>m ine/*.do</url-pattern>
</servlet-m apping> <w eb-app>
URL after m apping |
http://localhost:8080/m yApps/m ine/test.do |
Note: W hich m eans every request w hich has a pattern of http://localhost:8080/m yApps/ m ine/*.do w ill be handled by the m yPath.M yServlet class. (* denotes w ild character for any alphanum eric nam e). Also possible to m ap M yServlet to the pattern of /m ine/* , the * indicates any resource nam e followed by /m ine.
How do w e get the webapp nam e "m yApps"
The webapp 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 yAppsW eb.w ar</web-uri> <context-root> m yApps</context-root>
</w eb> </m odule>
........
<m odule id="EjbM odule_1"> <ejb>m yEJB.jar</ejb>
</m odule>
.....
</application>
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 |
129 |
Important: Servlets and JSPs are server side technologies and it is essential to understand the HTTP request/response paradigm. A common misconception is that the Java code embedded in the HTML page is transmitted to the browser with the HTML and executed in the browser. As shown in the diagram above, this is not true. A JSP is a server side component where the page is translated into a Java servlet and executed on the server. The generated servlet (from the JSP) outputs only HTML code to the browser.
As shown above in the diagram, if you set a request attribute in your servlet code, it can be retrieved in your JSP code, since it is still in scope. Once the response has been sent back to the user (i.e. the browser) the current request goes out of scope. When the user makes another request, a new request is created and the request attribute set by the JSP code in your previous request is not available to the new request object. If you set a session attribute in your JSP, then it will be available in your subsequent request because it is still in scope. You can access it by calling session.getAttribute(“JSPText”).
Q. How to get a pop-up window when clicking on a button?
By using Java Script in your HTML code. The following Java Script is executed in the client side within your web browser.
<SCRIPT type="text/javascript"> <!--
function displayWarningMessage() {
var answer = confirm("This process may take a while, please click 'OK' to continue."); if (!answer){
return false;
}
else{
return disableSendBtton();
}
}
// --></SCRIPT>
Q. What is client-side vs. server-side validation?
client-side validation (client-tier) |
server-side validation (presentation-tier) |
Java Script is used for client-side validation. |
Form data is submitted to the server and validation is |
Validation takes place in client-side within your |
carried out in the server. |
browser. Java Script can be used to submit your |
|
form data after successful validation. |
|
|
|
No extra network trip is required when there are |
Extra network round trip is required when there are |
validation errors because form does not have to |
validation errors because validation errors need to be |
be submitted. |
reported back to the client and the form data has to be |
|
resubmitted. |
Q. How do you prevent multiple submits due to repeated “refresh button” clicks?
Problem: Very often a user is completely unaware that a browser resends information to the server when a “refresh button” in Microsoft Internet Explorer or a “reload button” in Netscape/Mozilla is clicked. Even if a browser warns user, a user cannot often understand the technical meaning of the warning. This action can cause form data to be resubmitted, possibly with unexpected results such as duplicate/multiple purchases of a same item, attempting to delete the previously deleted item from the database resulting in a SQLException being thrown. Non-idempotent methods are methods that cause the state to change. But some operations like reading a list of products or customer details etc are safe because they do not alter the state of the model and the database. These methods are known as idempotent methods.
Solution-1: You can use a Post/Redirect/Get (aka PRG) pattern. This pattern involves the following steps:
Step-1: First a user filled form is submitted to the server (i.e. a Servlet) using a “POST” (also a “GET” method). Servlet performs a business operation by updating the state in the database and the business model.
Step-2: Servlet replies with redirect response (i.e. sendRedirect() operation as opposed to the forward() operation) for a view page.
Step-3: Browser loads a view using a “GET” where no user data is sent. This is usually a separate JSP page, which is safe from “multiple submits”. For e.g. reading data from a database, a confirmation page etc.