Sunday, October 30, 2005

How to use cookies to enable cross-context communication.


To make the cookies available to other apps you need to set setPath() method to the root path by using cooki.setPath("/");

Servlet Code:

Cookie cooki = new Cookie("session","visu");

System.out.print("Cookie setting for first time");

cooki.setPath("/");

cooki.setMaxAge(10); //48*60*60

response.addCookie(cooki);

response.sendRedirect("/SessionExample/MyJsp.jsp");

JSP Code:

Cross-Context using cookies:

<%

Cookie[] cookieArr = request.getCookies();

int i = 0;

while( cookieArr!=null && i <>

Cookie cookie = cookieArr[i];

System.out.println( cookie.getName()+" = " + cookie.getValue() );

out.print(cookie.getName()+" = " + cookie.getValue() );

i++;

}

%>

Advantages of cookies:

You can tell a cookie to stay alive even AFTER the browser restarted (or) the user hasn’t been on the site for a week. This can be achieved using cooki.setMaxAge(10); (//48*60*60) method.


Explain filters and especially compression filters briefly.

A very good article explaining everything about Filters and Compression Filters is Here

Here is another link from SUN Developers Network The Essentials of Filters


How to upload files using Server-Side Programming.?

Check out Page 72(42 of 78) to learn how the Servlet API handles file uploads.
You can also find a good, free, open source file upload API is the Jakarta Commons File Upload API at page 85(55 of 78).

File Uploading using Server Side Programming

I am having problems with sending the POST data to the server. If user submits the data twice accidentally then it is causing undesirables effect in the server. How to solve this issue ?

A very good article explaining ways to get rid of this Double Submit Problem is Here

Notes

Will there be a change in the url if I use sendRedirect to transfer the control within the same application(context) from one resource to another resource(E.g. from servlet to jsp)?

Yes. Definitely there will be change in the URL of the browser even if the transfer happens within the same application(or)Context.

If I block the session in the page directive like session=”false” then does the custom cookie will also be blocked.

No. Only session tracking cookie JSESSIONID will be blocked. Custom cookie will be enabled.

Thursday, October 27, 2005

What’s the difference between ServletContext.getRequestDispatcher("/ResourceName") and ServletRequest.getRequestDispatcher("/ResourceName").

Explain relative path and absolute path.

With ServletRequest.getRequestDispatcher("/ResourceName") you can specify a relative path.

Relative path means it starts from the root of that particular web application

RequestDispatchers work relative to the context root

for example in Tomcat:

your application directory tomcat/webapps/my-app
your jsp page webapps/my-app/example.jsp
Relative path
/example.jsp means my-app/example.jsp

Code:

ServletRequest.getRequestDispatcher("example.jsp");

You don’t need to include the forward slash in ServletRequest whereas you need to include a forward slash in ServletContext. You cannot specify a path relative to current resource in ServletContext.

ServletContext.getRequestDispatcher("/example.jsp");

Excerpt from Context.getRequestDispatcher() method.

The pathname must begin with a "/" and is interpreted as relative to the current context root.

Excerpt from Request.getRequestDispatcher() method.

The pathname specified may be relative, although it cannot extend outside the current servlet context.

ServletRequest.getRequestDispathcher() takes relative path.

ServletContext.getRequestDispathcher() and

HttpServletResponse.sendRedirect() takes absolute paths i.e. paths starting with "/" which is taken as relative to context root of the current web-app.


If there is no initial forward slash then it is a relative path.
ServletRequest.getRequestDispatcher("example.jsp");

If a slash is present then it is considered relative to the current context root.
ServletContext.getRequestDispatcher("/example.jsp");

Absolute path:

The complete URL location needed to locate the page/file

response.sendredirect(http://myServer.com/development/jsp/homepage.jsp);

response.sendRedirect("http://localhost:8080/SessionExample/MyJsp.jsp");

ServletConfig: A servlet configuration object is used by a servlet container to pass information to a servlet during initialization. Using config object you can access init parameters declared in deployment descriptor and get context object.

ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

There is only one context per "web application" per Java Virtual Machine.

The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

Wednesday, October 26, 2005

If we try to forward a request with the help of RequestDispatcher after the response is committed(flush() method called) then we will get an IllegalStateException. This is fine because the response is already sent to the client and the request is a history.

This link has got good mention about forward and commit techniques.

But what will happen if I write something to the response output like

out.println("##");
RequestDispatcher dispatcher =
req.getRequestDispatcher("/servlet/aView");
dispatcher.forward(req, res);
out.println("!!");

and call RequestDispatcher before committing the response?

out.println("##");

"##" is stored in the output buffer (but not yet sent to the browser).

RequestDispatcher dispatcher =
req.getRequestDispatcher("/servlet/aView");
dispatcher.forward(req, res);

The output buffer is cleared, removing "##". Uncommitted output in the response buffer is automatically cleared before the forward.

Then "/servlet/aView" is called, its response is committed and the output stream is closed.

out.println("!!");

An IOException is thrown because "out" is closed.

The reason why you are not getting an IOException message or the output "!!" is because
after the request and response has been forwarded to the said url, the output stream will be closed there and nothing will be sent to the client anymore (Any exceptions thrown will be effectively invisible).

Thats why it is considered Best Practice to use return keyword after a request has been forwarded, using requestdispatcher.

RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/ABC.jsp");
rd.forward(request, response);
return;

Check this thread for details.



Explain why contentType has to be set BEFORE accessing the PrintWriter object.

Servlet container may commit the response output to the client when the response buffer is filled. But the servlet container providers may choose not to implement buffering at all. See the following quote from Servlet Spec 2.4 Section SRV.5.1 page 43.

From Spec


A servlet container is allowed, but not required, to buffer output going to the client for efficiency purposes. Typically servers that do buffering make it the default, but allow servlets to specify buffering parameters.

So, if as a servlet developer you are not setting the content type before writing to your output stream the container may commit the response and subsequently your call for setting the content-type will be ignored by the container as the response has already been committed.

Tuesday, October 25, 2005

Suppose we have a XYZ site, where it sets the cookie with the name as "username" we have another site say ABC where it sets the cookie with the same name i.e. "username". Now when the cookies are collected in the array and when cookie.getName() checks for username, it can display the wrong name in the server. How does the server handles this problem.

The browser will send only those cookies that were set by this server with every request to the server. So, a cookie with name "username" set by javaranch will be sent to javaranch and a cookie with name "username" set by yahoo.com, will be sent to yahoo.com. A particular site can only retrieve the cookies that it set.

Cookie.setPath() method

The cookie.setPath(String uri) method sets the return path to where the cookie should come back along with the request from the browser.

If we do not set the return path, does the cookie comes back to the same server path?

If you do not call the setPath method on a cookie, the browser returns the cookie only to URLs in or below the directory containing the page that sent the cookie.


Also take a look at the article "Cross Domain Cookie Provider" Here

Why do we need Attributes? What’s it’s purpose?

Explain

context.setAttribute(....)
session.setAttribute(....)
request.setAttribute(....)

An attribute is an object usually bound into one of the three servlet API object’s. ServletContext, HttpServletRequest(ServletRequest), HttpSession. You can think of it as simply a name/value pair( where name is a String and value is an Object). All we care about when looking at attributes is about the scope in which attributes exists.

context.setAttribute(....)

These attributes are accessible for all requests within the current application and usable throughout the life of the web application. Scope of these attributes are lifetime of deployed application. If server or application goes down, the context is destroyed.

Context attribute are accessible to all the request from any client, as context attributes are common to all the components in the web application.

session.setAttribute(....)

These attributes are stored and retrieved across multiple requests from the same client and accessible throughout the life of this user's session .
They are isolated from other sessions (i.e. one user's session is completely separated from another’s). Scope of session attributes are life of the session. A session can be destroyed programatically or can simply time-out.

Session attribute are accessible to all the request from same client, as all the request from the same client will use a single session object on the server side.


request.setAttribute(....)

These attributes are only valid and usable for the duration of one request (i.e. from the user requests some resource, until the server has finished responding), but allows different components within this request (look up: MVC or requestDispatcher) access to objects bound to it. Scope of request attributes are life of the request. In other words, for the life of the thread handling this request.

Request attribute are accessible only to those component(JSP/Servlet) to which request object has been forwarded. These attributes are valid and usable only for the duration of one request because http is a stateless protocol.


Monday, October 24, 2005

Explain the difference between init(ServletConfig config) method and init() method. API says simply override no arg init() method which will be called by init(ServletConfig config) method? What does this imply?


Code decompiled from GenericServlet in javax.servlet package.

----------------------------------------------------------------------------

public void init(ServletConfig config) throws ServletException {

this.config = config;

init();

}

public void init() throws ServletException {

}

private transient ServletConfig config;

-----------------------------------------------------

If we look at the above code we can understand that the init() method with no args is called from within the init(ServletConfig config) method.

If we override the init(ServletConfig config) method that takes a ServletConfig then

super.init(config) should be the first statement inside that overriden method.

Because the container creates a ServletConfig instance and passes that instance to the init method of the GenericServlet where that config instance is assigned to the local private copy of that class. (private transient ServletConfig config;)

Code decompiled from GenericServlet in javax.servlet package.

----------------------------------------------------

public ServletConfig getServletConfig() {

return config;

}

----------------------------------------------------

If we override the init(ServletConfig config) method that takes a ServletConfig and didn't specify the super.init(config) then the local copy of the ServletConfig instance will not be initialized and when you try to use the getInitParameter(String str) of the ServletConfig interface (which is not been initialized to some value in the GenericServlet class) NullPointerException will be the result.
This is a very good example of Encapsulation as the instance variable [
private transient ServletConfig config;] is kept private and the getter methods are used to get that particular instance.


Tuesday, October 18, 2005

If a client is using multiple Internet Explorer, then are they going to use the same session object or not ???

If the client uses multiple Internet Explorer, they will be getting different session provided the browser is not opened using ctrl+n or File>> New >> window.

With Opera and FireFox the same session is continued with both in a new tab (and) a new browser process(or) instance(or)window.
Only in IE with each new browser process(or) instance a new session is created.

How to set IE to run all windows using single browser process ?

There used to be a setting in the Advanced options area called "Launch Browser Window in a separate process" which, if enabled, would force a new session with each new window. If disabled, all windows would share the same session. However, as of IE 5.01, > this is no longer an option.

quote:


If the computer has less than 32 megabytes (MBs) of RAM installed, this setting is disabled and all instances of Internet Explorer share the same process. If there is 32 MBs of RAM or more installed on the computer, the setting is enabled, which causes new instances of Internet Explorer to create new processes.


You cannot guarantee session state to be maintained over multiple windows. If you need to maintain data over multiple windows, use a key in the query that is tied to a cookie or a bean.


A very good example to explain sessions would be your yahoo inbox

Start a new Firefox instance, open two TABS, type the user-name/password and login in to your yahoo account in one of the tabs. Now without logging out just close the browser tab leaving the second tab untouched. Now again open a new FireFox instance. Type the following URL
mail.yahoo.com. Now you will NOT be asked to enter your user-name and password again, because the session with which you had logged in is existing and has not expired(Timed-out).

But the above scenario is not possible in IE because every single instance of IE is considered as a new browser PROCESS no matter whether a previously opened IE instance exists or not and with every new IE you will be asked to enter the username/password.


How Sessions are treated with respected to different browsers and windows ?

In context of multiple windows here is the quote from the servlet spec. How the session is treated depends on the browser processes.

From Spec:

Client Semantics

Due to the fact that cookies or SSL certificates are typically controlled by the Web browser process and are not associated with any particular window of the browser, requests from all windows of a client application to a servlet container might be part of the same session. For maximum portability, the Developer should always assumethat all windows of a client are participating in the same session.

What is the default life time of Session (or) JSESSIONID Cookies?

1800 seconds (or) 30 minutes

From Spec:

The default timeout period for sessions is defined by the servlet container and can be obtained via the getMaxInactiveInterval method of the HttpSession interface.

Example Code:

HttpSession session = request.getSession();

System.out.println("default timeout period for sessions : " + session.getMaxInactiveInterval());

Note:
Be careful not to assume that sessions expire as soon as they reach their expirey time, sometimes they only get closed by a very low level thread some time after they have timed out.


Monday, October 17, 2005

What in fact is the main difference between applets - servlets and JSP's?

An applet is a program written in the JavaTM programming language that can be included in an HTML page, much in the same way an image is included. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM).

This process becomes time consuming when the size of the applet is large. Servlets and JSP are executed on the Web Server. Applets are 'rich clients' and require java to be installed in the browser on the client. They also have some cross platform problems that effect their use.

Servlets do not require the browser to be java enabled unlike applets because they execute on the web server. Web applications are thin clients which (in general) only need the browser to support HTTP and HTML.

For more details take a look at this Thread

Tuesday, October 11, 2005

Difference between JSP and Servlets


The JSP engine(Jasper) essentially parses the JSP file to create a Java program (servlet), and compiles and runs it just like any other servlet. So the way servlet and jsp work is almost similar.

JSP's and servlets, should always coexist. JSP's to render the presentation and servlets to control flow. It is always better to have Business Logic in separate Java class(POJO’s) (or) EJB’s (or) Java Beans and use Servlets as controller between the Model and View. In a well designed J2EE web application, you should find little or no HTML in the servlets, and little or no Java in the JSP's.

Coming to when to use servlet or jsp. when your purpose is to render page at user end go for jsp, else if your purpose is to do some server side stuff such has database updatation, interacting with model and retrieving some data to pass it to JSP etc. go for servlet.

JSP has access to things like Tag libraries and JSTL which are not available in Servlets. Some of these features can be accomplished in other ways in Servlets, but not all.

Performance

The JSP will require to be translated and compiled into a servlet -- so on the first request the JSP will definitely be slower. But after that they should perform similarly (both are servlets).


Explain me the difference between Application server and Web server.

An Application server is more sophisticated and intelligent server when compared to a webserver. A webserver works on a request-response model. You make a request and it gives you the response. An application server does a lot more than that. It takes care of performance related features like Database connection pooling, bean instance pooling, transaction management, security etc. Application servers come into picture (as you rightly said)in n-tier architectures (where n is normally > 2)when you are using business components(like EJB) in a distributed architecture.

1)What is the role of application server in a n-tier architecture?

The role of an application server is to assist the business components with various things like transaction management, Instance pooling, Security and a host of other system level plumbing features, which are vital for an enterprise application. A web-server cannot provide these facilities.

2)Is the business logic stored only in the application server or in any other server too? What technologies are used to write the business logic?

Normally yes. The business logic is stored in the application server in the form of business components.(It is part of the j2ee specification).But you can also load your web components in the application server which might have a little of business logic and a lot of presentation. The technologies mostly used in the industry today to create business components are EJB, DCOM and CORBA.

3)Is Apache Tomcat server a Web server or a Application server or both?

TOMCAT is a webserver.

4. I think an Application server can also have the functionality of the Web server, am I right?

All J2EE application servers (from all vendors, including the reference implementation from Sun) come in two parts:

(1) A Web Container that implements the Servlet and JSP specifications

(2) An EJB container that implements the EJB specification.

Tomcat from the Apache consortium IS the Reference implementation of the Servlet specification. Likewise Jasper (which is part of Tomcat) is the reference implementation of the JSP specification.

The sun J2EE reference implementation does include Tomcat. You can download whichever one you need, based upon whether you just need servlets or JSP's, or EJB's also.

Friday, October 07, 2005

Difference between response.sendRedirect and requestDispatcher.forward with respect to session?


When you forward the request with requestDispatcher.forward the target servlet/JSP share the same session. But with sendRedirect the session information is not preserved. ( target is not in scope of session)

A RequestDispatcher forward is a server side activity. So the request and its associated session are available to the forwarded resource.

If you use sendRedirect to redirect the user to a different context, i.e. a different application, of course the session information is not preserved. It would be meaningless because sessions are tied to a specific context. (for example, my session information from javaranch would have no meaning if I decided to go to yahoo)

However, using sendRedirect within the same context works perfectly.

You might have a scenario in which you want to redirect the request to a different URL, but still want to use a session. There is a special URL encoding method just for that:

response.encodeRedirectURL("/resourceName");

Remember to include the slash in the method.

What is URL Rewriting ?


Passing cookies back and forth is the simplest way to exchange session ID’s. The goal for the Client and the Container is to exchange session ID info. If the client won’t take cookies, you can use URL Rewriting as a backup. URL Rewriting takes the session ID that’s in the cookie and sticks it right onto the end of every URL that comes into this application.

We add the session ID to the end of all the URL’s in the HTML we send back in the response.

http://www.myserver.com/catalog/index.html;jsessionid=1234

URL Rewriting works ONLY if we tell the response to encode the URL. If we don’t explicitly encode the URL’s, and the client won’t accept cookies, you won’t get to use sessions.

If you do encode your URL’s the Container will first attempt to use cookies for Session Management, and fall back to URL Rewriting only if the cookie approach fails.

Response.encodeURL(“/resourceName”);

Difference between response.sendRedirect and requestDispatcher.forward?

A RequestDispatcher does the work on the server side. That’s the big difference between a redirect and a request dispatch - Redirect makes the client do the work, here client is the browser not the user. RequestDispatch makes something else on the server do the work. The something else is nothing but a resource in the Web Application which should be either a Servlet Or a JSP

A forward passes the current request along to a new resource within the same context. Request parameters and scoped variable are therefore preserved.

A redirect causes a new request to be issued by the browser. Hence request parameters and request scoped variables are not preserved. Context(or)Application and Session scoped variables are indeed preserved. As context attributes are accessible to all request and session attributes are accessible for any request from the same client. Redirect can be used to transfer the control to a different context.

A sendRedirect sends the mentioned url to the browser and the browser sends a new request to that url. Request parameters and scoped variables are therefore NOT preserved. sendRedirect is typically used to forward requests to a different context (Application Context).

Another difference would be if we use RequestDispatch there will be no URL change in the browser as the request is dispatched within the same Web App, whereas if we use sendRedirect the user sees the new URL in the browser. This is because the browser makes the new call on the user’s behalf after the originally requested servlet returns the requested resource URL. With sendRedirect the new URL is exposed to the user and the client has the ability to bookmark the page.

Also when switching protocols like from Http to Https, we use sendRedirect.

Remember:

Redirect = Client

RequestDispatch = Server

Learn more redirect Here