Thursday, March 6, 2008

Setting Default page in JSF

I am assuming you have a JSF application that runs in Tomcat, and that you are using MyEclipse as your IDE (though it isn't really that important. What I wanted to do was instead of a url that included the specific default page, I wanted the ability for users to assume a default page in the url. For example: Users could put in the browser: http://myhost:8080/MyJSFApp/MyJSFPage.faces What I want them to also be able to do that will get them to the same page as if they had typed the above url. http://myhost:8080/MyJSFApp or
http://myhost:8080/MyJSFApp/
To make this work, there is a little trickery that we need to do. Step 1: Create a new JSP page called index.jsp (it could be called anything) Step 2: The only thing you need in the index.jsp file is: <jsp:forward page="/MyJSFPage.faces"/> At this point you should be able to type the following into the browser and have it redirect (without the url changing) to the MyJSFPage.faces page. http://myhost:8080/MyJSFApp/index.jsp Step 3: Now all we have to do is edit the web.xml file. You will most likely have a welcome-file-list tag already in the file. Change it (or add it if it doesn't exist) to the following (or similar for your application).

<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> That's it. Side Notes This all assumes that JSF is using the .faces pattern to designate what a JSF page is. The whole reason we need the first two steps to create the index.jsp file is because the welcome-file tag must point to a file that actually exists in the file system. It can't be a .faces file, because it doesn't actually exist. Has anyone tried it such that JSF is setup to use a pattern like /faces/* instead of *.faces?. I have not tried it, but I think the same problem would exist because the faces directory directory doesn't exist either. Feedback is welcome on this issue. Instead of the JSP forward tag, you could use pageContext.forward("/MyJSFPage.faces") or requestDispatcher.forward("/MyJSFPage.faces") and the behavior would be the same. On the other hand if you want the url to change to the url of the new page in the browser, you could use response.sendRedirect("...") which can redirect to any page on any server (any url really). The difference is that this sends a response to the browser that sends back an immediate request to the url that you wanted to redirect to. This is slower, but may be the behavior that you need in some cases.

3 comments:

Anonymous said...

Thanks very much for your post. I'm new to JSF and this definitely helped.

Brent V said...

I agree for a newbie it can be difficult. Thanks for the feedback and I'm glad it helped.

Thx,

Brent

Anna said...

Great and Useful Article.

JSF Online Training

JSF Training

JSF Interview Questions

JSF Tutorials

Java Training Institutes in Chennai

Java Training in Chennai