Monday, November 28, 2005

Are doGet and doPost methods in servlets thread safe? Should we Synchronize them to make thread safe.

The answer is "NO", the doGet and doPost (any doXyz) methods are not synchronized and thus not thread-safe. However, it is a very bad practice to synchronize these methods for your own servlet classes. The reason is that it reduces the servlet's ability to scale; IOW(In Other Words), to handle large numbers of concurrent requests.

Synchronize the smallest block of code that accesses or modifies a shared memory state. Remember: synchronizing reduces the scalability and at times the responsiveness of your webapp (any application, really) so try to limit or even remove the need for synchronization.

There are six fundamental variable scopes in a webapp. Which of these scopes are truly thread-safe?

  • Application (servlet context) scope attributes
  • Session scope attributes
  • Request scope attributes
  • Local method variable (or JSP page scope attributes)
  • Servlet instance variable
  • Servlet class variable

In general, only the local/method variables and Request scope attributes are thread-safe. Whenever, you access or modify a variable/attribute in any of the other scopes you should synchronize.

Note:

This topic (making a webapp thread-safe) is rather complex and one that cannot be resolved in a single answer. So, what I would recommend is that you study fundamental aspects of concurrent programming. I wouldrecommend Doug Lea's book Concurrent Programming in Java. It is a rich study of this broad topic. However, I will warn you that it is also very dense reading.... not exactly a Head-First experience. This is just the beginning of a very rich and interesting topic.

Click here to read more about thread safety

Tuesday, November 22, 2005

Establishing a connection with a database from servlet.

Connection Pooling

Friday, November 18, 2005

Which one is Instantiated first. Servlet or Filter?


Here is what the specification says:

When a web application is deployed into a container, the following steps must be performed, in this order, before the web application begins processing client requests.

• Instantiate an instance of each event listener identified by a element in the deployment descriptor.

• For instantiated listener instances that implement ServletContextListener, call the contextInitialized() method.

• Instantiate an instance of each filter identified by a element in the deployment descriptor and call each filter instance’s init() method.

• Instantiate an instance of each servlet identified by a element that includes a element in the order defined by the load-onstartup element values, and call each servlet instance’s init() method.

So filters are instantiated before Servlets.

Give a scenario where we use Filters.

One way I use filters is for authentication. When an internal controller(servlet) of the web app is requested, a filter checks to make sure that an authentication token is in the session. if so, the request is allowed to proceed normally. Otherwise, the filter forwards to the login mechanism.


JavaScripts are Cool and Useful

JavaScript can display a real-time clock to your page. This is a really professional way to add that special touch to your web page. And, watch as the clock on your page updates every second.

Add Dynamic Clock to your Web Page


A script that sets a time limit on how long a surfer can spend viewing the document. The time left will be constantly shown at the status bar below. After time has expired (ie: 1 minute and 30 seconds), the browser will automatically navigate to another page, forcing the surfer out.

Tuesday, November 15, 2005

Notes for

1. getResourceAsStream(String path) and
2. getResourcePaths(String path)


in ServletContext interface.

getResourceAsStream

getResourcePaths


What does Pooling means with respect to servlets?

Servlets are multi-threaded. You only need one instance to service all of your requests because each request is handled in a separate thread.

With servlets that implement SingleThreadedModel, on the other hand, a new instance is created for each request. At the end of that request, the instance is destroyed. This creates a lot of overhead and slows down the request/response cycle. To alleviate(make easier) this problem the makers of many servlet engines decided to pool(combine, add together) and recycle a number of instances, much in the same way that database connection pools do with database connections.

Since the SingleThreadedModel has been deprecated, it makes no sense to start using them now. They are still supported for for the sake of older apps that rely on them and developers should understand how they should work if they ever run into them while working on an existing application.

Monday, November 14, 2005

How to load a class when servlet starts up?

Check out this thread.

Thursday, November 10, 2005

Why can't we access resources using URL, inside the WEB-INF or META-INF folders. But we are able to access all resources that are outside this folder using URL.

Because these are stuffs that web client shouldn't access and accessing them is dangerous for web application. Assume there are some configuration files that client shouldn't be aware of. So these files go inside WEB-INF folder.

Besides those inside WEB-INF and META-INF, you need to protect those resources outside WEB-INF else the client browser will be displaying the contents of your webapp which in most cases will be your JSP pages. This will happen when the client types the url until the webapp name like http://localhost:8080/testapp. This can be protected by defining a welcome-file list for the web-app.

Does the manifest file in META-INF folder has any significance with respect to deployment ? I could not get where it is being used.

When WAR/EAR is created this would be automatically created by the build tool ?

Manifest is the link point between enterprise tiers, e.g. if your EAR is made up of 3 WAR and 2 JAR, then that dependency is written in Manifest. it is extremely critical while deployment.

Why we don't have attributes in config like context??

What would you use them for?
Remember, there is only one ServletContext object per web application (or per JVM in a cluster). So it makes sense for a servlet to be able to set attributes on the context object so they may be retrieved by other servlets.

However, there is one ServletConfig object for every servlet. If a servlet were able to set an attribute on the config object... the only servlet that could retrieve it would be the same servlet. There is simply no reason for it.

Wednesday, November 09, 2005

When init() method is called?

Options would be

(a) init method will be executed immediately after loading and instantiation of the servlet class takes place.

(b) Container differs the initialization till the first client asks for service.

Servlet Specification doesn't state exactly when init method should be called. But it will be called surely before servlet can serve to its first request.

From Servlet Spec

After the servlet object is instantiated, the container must initialize the servlet before it can handle requests from clients.

Instantiation ==> Calling the no-arg’s constructor of the servlet class.

Initialization ==> Calling the init() method.

Servlet initialization can also be done at server start-up by configuring in DD by setting positive integer value, to load the servlet at startup.

Hence it is wiser to answer as init() method will be execute when the servlet class is loaded by the container.

Friday, November 04, 2005

How to solve caching issues with FireFox?


C
aching is handled differently in different bowsers.

With Internet Explorer "no-cache" value of "Cache-Control" header is sufficient to disable

browsers from caching web pages.

response.setHeader("Cache-Control", "no-cache");

But it is not sufficient to prevent the FireFox browser from caching web pages. You need different value for the same header to prevent caching.

response.setHeader("Cache-Control", "no-store");

How to disable browsers from caching web pages.

Caching is a feature that’s provided by most of the modern and intelligent browsers. But the convenience of caching affects standard behavior. Here is the question: what would a user see if after submitting a form he clicks Back browser button? Did you say that he would see the same form he just submitted with the same values filled in? Why? Because the browser saved the page in the cache in case it would be needed again?

Well, forget smart browsers and caching. How this is for you: each window or page in an interactive application is a View representing an application Model. In order for the View to be correct and consistent with the Model it must be rendered anew each time it is presented to the user.

In plain English: caching must be prohibited for web applications. Online books, dictionaries, pictures can be cached. But please dear browser, do not save snapshots of a live program, because they may not represent actual Model state anymore. It is bad if the saved View is just looked at, but it is tenfold worse when a stale View is used to modify the Model.

Now I ask the same question again: what would a user see if he clicks Back button after submitting a form? You know the correct answer already: the user of a well-designed web application would see a View which represents current Model state.

To disable browsers from caching web pages use the following caching tags in your JSP Page

meta http-equiv="pragma" content="no-cache"

meta http-equiv="cache-control" content="no-cache"

meta http-equiv="expires" content="0"

A page would be considered expired right after it loaded from the server.

If your network has a proxy server or firewall, the web pages will be cached on the proxy server. The browser cache-control would have no effect in the intermediate proxy server. And also browsers are not required to process cache control tags on the web pages, but they usually obey HTTP response header fields.

Hence if your JSP page with caching tags doesn’t work out you got to use HTTP response header fields. It is always advisable to use HTTP header fields to prevent caching.

response.setHeader("Pragma", "no-cache");

response.setHeader("Cache-Control", "no-cache");

response.setHeader("Expires", "0");

response.setDateHeader("Expires", 0);

One more important point would be these header fields should always be added at the beginning of the JSP page before any processing happens.

Also take a look at this Link to learn more about META tags.

Explain Browser History and Caching and their difference. Is there a way to modify browser history.

Cache and browser history are not the same thing. Cache means that the browser saves the contents of the page on the client's machine so it can be displayed quickly without going to the server to pull down the content again. Browser history is just an entry in a list somewhere that the browser keeps saying that you visited the page (so that you can easily find something you were looking at the other day but didn't bookmark, or so you can prove that your significant other or children are secretly visiting "naughty" sites) The contents of the page are not saved in browser history, and there's really no way I know of affecting browser history from the server side. There might be some way to do it in JavaScript, though, since it runs on the client side.