JSF Best Practices
May 20, 2008 53 Comments
Here I am documenting some best practices can be followed during JSF project development.
Open Source Components
- Use myfaces or Sun RI. It doesn’t matter which one you use because both comes from Sun. Sun offers myfaces through open-source community.
- Use richfaces to get rich look quicker. Click here to go to demo site.
- Use facelets to avoid compilation time and better code readability.
IDE
- Use eclipse latest version
- Use richfaces eclipse plugin. It offers Visual Page Editor for Richfaces, JSF, and HTML / CSS.
- Use Tomcat instead of JBoss to avoid server restart for each changes.
Naming Convention
- Keep resource bundle name and xhtml name as same. Example SearchUsers.xhtml and SearchUsers.properties
- Suffix all the managed bean with “Bean” word, like SearchUsersBean.java
- Keep all the folder names in lower case.
Techniques
- For bigger project it is better to extend all the default components, that gives flexibility and extensibility to add new features in future.
- Use components effectively like oops concept to minimize the coding and maximize the usage.
- To keep your application scalable, minimize creating managed beans in session scope. Many of them recommending session scope for managed beans to solve the JSF component state problem but it is a serious issue if you want to host your application in clustered environment.
- Use Map object to capture values for components created inside <c:foreach> loop.
- Write a custom datetime converter and register with java.util.Date type to keep control of TimeZone and default date format. See here for more information.
- Customize default JSF error messages. See here.
- Use facelets layout feature to simulate Struts Tiles kind of behavior.
- Always use Wrapper classes instead of primitive types. If you use primitive data type passing empty values from the field will through exception.
- Use <h:outputLink> for simple page navigation, use <h:commandLink> to submit form and does validation too.
- Don’t hesitate to use simple HTML input controls where JSF doesn’t provide good solution. For example displaying radio button in datatable has issues when you fetch data from database. For these scenarios I prefer to use simple HTML controls.
- Use <c:if> instead of rendered attribute for <h:commandLink> and <h:commandButton>. If you use rendered attribute sometime action may not be fired if the bean by default returns false.
- If you are using JSF1.2, use <f:view beforePhase=”#{method-binding}”> to execute all your page initialization stuffs like fetching data from database, creating error messages to be displayed.
- If you are using JSF1.2, use field specific custom error message wherever is required. Example:
<h:inputText value=”#{bean.value}” requiredMessage=”#{bundle.requiredMessage}” converterMessage=”#{bundle.converterMessage}” validatorMessage=”#{bundle.requiredMessage}”>
More information can be found here. - Don’t use <c:if> inside iterative tags like <h:datatable> and <ui:repeat>. see here to know the reason.
Work around for some common issues
- Add immediate=”true” for Cancel and Reset types of buttons to bypass validations. See here.
- One of the major missing feature in JSF is calling an action before page invocation. Here is the workaround.
- Here an work around solution explained to invoke an action from url.
- This link explains the difference between <c:forEach> and <ui:repeat>
http://www.ilikespam.com/blog/c:foreach-vs-ui:repeat-in-facelets - If you need to redirect from navigation-case to URL with param which is a property of a managed bean. Here is the work around.
- EL expressions in JSF are executed multiple times for datatable and other iteration tags hence get method in managed bean might call multiple times. Either initialize your variables in action method or @PostConstruct method or follow lazy initialization. Read here for more explanation.
- With JSF implementation submitting form with enter key will not invoke action method. Here is a custom component which will solve this problem.
::
::
::
::
::
::
::
::
::
::
::
HI Venkat,
Let me introduce me – I am Rajiv gogri, working as java developer in TCS.
Encourge your effort to share ur experiences.
Here comes some of questions:
IDE:
point 2 – Use Rich faces plug in – What is end result of this plug – in?
Any good plug in to develop JSPs. How abt Workshop for weblogic10 ( with jsp plug in ).
point3 – If V wanna avoid Restarting with every change – as it happens in weblogic servers too – one can easily disable the option – Republish Automatically and always publish it manually.
Richafces plugin offers Visual Page Editor for Richfaces, JSF, and HTML / CSS. Also it offers Facelet support. I haven’t worked on weblogic IDE, so I can’t comment on that. On the open source front, I feel Eclipse with Richfaces plugin is good option for JSF development
Again I haven’t used weblogic server. Tomcat provide a feature called “Serve modules without publishing”, this feature enable tomcat to use workspace code instead of publishing. if any changes in .jsp and .xhtml, no publishing or restarting is required. And among the J2EE web container tomcat is one of the fastest server to start quickly.
I have a doubt. I just want to know the difference
between an abstract class and interface.
Please don’t tell me that in abstract class i can
define functions and in interface i can only declare
functions.
The doubt i have is that both represents nearly the
same and why the hell java supports both. It seems
like ambiguity to me.
For example i can have only abstract class and do all
the things that can be done with interface. then why
this ambiguity.
Thanks
Selvakumar(Mahendra Engg)
Abstract class is should be used for inheritance in meaning of like abstract Animal and concrete Tiger. Interface is sayin that class has some behaviour typically like Sortable. Java allows extends only from one class at the time but you can implement more interfaces.
TO Article:
for initialization is nice to use init method annotated @PostConstruct which runs before anything else does.
For JSF is must have some framework for support Seam or Shale or Spring. I like Seam helps in lot of cases.
As IDE i use Netbeans with facelets plugin and i am happy with it.
I don’t see need for Bundle file for every page.
I would add be careful with multiple forms on page as it adds a hidden param with serialized tree view.
I am using Netbeans 6.1 with myfaces and trinidad, i think it is probably the most feature rich combination. Trinidad also supports ajax, partial triggers and submits. which gives the application a good look and modern web 2.0 kind of a feel.
@Selvakumar: try inheriting from more than one abstract class
Just wanted to correct a point in your entry. Sun does not contribute to MyFaces. Mojarra (also known as the RI) is developed here: https://javaserverfaces.dev.java.net.
how can i prevent direct access to my pages in jsf
as i have used JAASActionListener for Authentication and
authorization. i want to redirect him to login page if he comes
using url for xyx.jsp in my application how to check him.
do i need to add onload call actionListener–> (i have not found it)
Ravi, there are two ways you can do page authorization in JSF.
a) Traditional way of writing a Servlet Filter which does the necessary authorization check before the request is sent to JSF servlet.
b) Write a phase listener which listens to restore view and render response phase. Perform authorization, if authorization fails change the ViewRoot to your login page.
FacesContext fc = event.getFacesContext();
NavigationHandler nh;
nh = fc.getApplication().getNavigationHandler();
String fail = “authorizationFailed”;
nh.handleNavigation(fc, null, fail);
thanks Venkat
but my reqirement is when user visits my site and from login page
he is authenticated and navigates to home.jsp if he captures the url
and types it in the browser my application is allowing him to visit home.jsp
that i want to restrict as i told u that i am using actionlistener for it from sun
example.In that if he clicks on command link or button my process action is called,to prevent him direct acces i want to call process action when page gets loaded.
help me.
Ravi, I haven’t used phase listener for authorization, however I have use servlet filter.
Here the code snippet you can try out:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String requestURI = httpRequest.getRequestURI();
// check authentication for other than login page
if (!requestURI.endsWith("/login.faces")) {
if (do you session validation here) {
// invoke chain if the session is valid
super.doFilter(request, response, chain);
} else {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.sendRedirect(httpRequest.getContextPath() + "/system/login.faces");
// request.getRequestDispatcher("/system/login.faces").forward(request, response);
return;
}
}
}
You can find a lot of information about servlet filter in google search.
hello Venkat,
how to refresh data table for every x intervals in jsf.
Ravi, That is not related to JSF, you have to write JavaScript code.
http://www.w3schools.com/js/js_timing.asp
You can post your questions to the JavaRanch forum.
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=forum&f=82
I have problem n using ajax4jsf poll
My requirement is after loading the page i have to render the datatable for every x minutes.it should fetch the latest records from database.
Hi sadasivan,
i am working on jsf,ejb3.0 .my requirement is to select the multiple rows usng checkboxes from jsf datatable. i am workng on this for last two days. early response is appreciated.please hel me.
Thanks
ravi
HI
Iam new to JSF development.
i downloaded the following plugin
tk.eclipse.plugin.jsf_2.0.6.jar …but iam unable to see it in eclipse…
iam using eclipse 3.4 version
Please let me know the best way of developing a JSF application.
can we use exadel for JSF development..
Thanks in advance
Sridhar Dasari
As I mentioned in the article, you can use richfaces eclipse plugin.
http://downloads.sourceforge.net/jboss/RichFaces-VPE-win32-2.1.1.GA.zip
Major problem in JSF is in showing 20 columns with 100 rows per page when database table size is in 100s of gigabytes or even megabytes. The results are brought with multiple joins and unions of 10 tables. The Results and other components too load too slow after endering a new page for some user inputs. No solution in Web too.
Hello, Venkat.
I’m using Facelets together with JSF RI in Eclipse. The thing is Eclipse reloads Tomcat context each time the .xhtml file has changed – the developing process becomes very long and inconvenient. I tried to move files from .xhtml to .jspx (hoping that Eclipse will publish static conent to Tomcat without full reloading of context – as if simple .jsp files) but hadn’t give any results… Have you solved the problem of Eclipse republishing?
Thanks!
Anton, you have to configure facelets.REFRESH_PERIOD in web.xml. Refer the below ur for details.
https://facelets.dev.java.net/nonav/docs/dev/docbook.html#config-webapp-init
Hi Venki ,
In jsf , i am having one command button, and corresponding action method for that ,
After once i clicked the button ,
wnever the page refreshes , the action method calls ,
how top avoid this .?
ASAP
I assume you are refreshing page by clicking F5 button. This is a common issue in web programming as browser re-sends the last submitted data when refreshing. Added the following meta-data to clear the browser cache so that browser cannot re-send the data.
Hi Venkat,
I am new to JSF.. and some how.. started to develop JSF components using ICEFaces..custom components.. I have a scenario where in i want to select a value for INput text field from a popup window.. when click a option link in popup window i need to refresh it in the corresponding Input text field.. but its not happening.. but able to get the value using output text..
kindly give your valuable advice..
Vijay Kumar, Sorry I haven’t used ICEFaces.
Hi Venkat,
Can you guide us in doing the same with JSF components, may be we can replace the ICEFaces with JSF components.. if possible.
Hi,
I am trying to implement Servlet filter for authorization and authentication in my JSF app. I am able to check if not login page, go to login and on success go to target page.
I am storing my visit state in a hidden input to maintain request scope, but when I click on any link to navigate into another page in the doFilter() the request parameter / attributes are empty.
Can you guys help me understand why the request attributes are empty and how can I retrieve the value from the hidden variable in the doFilter() as I don’t have access to FacesContext?
Thanks in advance.
hc
Store your visit state in a cookie. When clicking link it is GET request, hidden fields will not be submitted to server.
Hi Venkat,
The links I am clicking are h:commandLink this submits the form. Do you think is there any other way instead of cookies?
-Hari
Yes, h:commandLink will submit form in that you have to ensure all the forms in your application has the hidden field. But the hidden field name will change between different forms. The fields names are formid:componentid. Other than cookie you can think of keeping in your Session object. But cookie is simple and better solution for request scope data through your session.
Hi venkat, This is raghu, working in oracle, b’lore. in our project we are using jboss richfaces. we are facing a small issue. in our jsp page there are two dropdowns (select one menu) , depends on the first dropdown selection second dropdown should populate. so i’m firing onchange event to load the data for the second drop down. it is db call. so it is taking more time… in the middle(befor this call completes and formating SelectItems for second dropdown), we are trying to access the second dropdown, as it is going to change.. exception occurs and resulting a blank screen. how to solve this problme? is there any way that we can maintain a request queue?? or any known work around?? plz help me out. its very urgnet. Thnx in advance.
My suggestion is keep the second dropdown disabled till browser gets response from ajax request. Also when you are using AJAX make sure your server response time is faster enough (if not consider caching) otherwise it will annoy users.
The response time will be faster.
hi Venkat,
i’m using MyFaces 1.1.6, facelet and Richfaces 3.1.6
I’d like to know how to add a new row to rich:datatable for data input using javascript. After user input several rows, save the input in one server request. Did some searching on google/jboss forum, still got the same solution to add a new item in the List of the backing bean and re-render the table. It works, but not “dynamic” enough i think. Any hints?
Alan
venkat, thanks for you quick replay. but our problem is, evnthough we disabled the second dropdown till the first one is selected, there is chance of changing the first dropdown item, ( when our first dd is got changed , second one shud populate according ..) so still the same issue. in our loact development inveronment it is working fine. when we are doing a performence test with low band width, then it is giving error. we have to deploy this application in south africa, which is known for low bad width, i guess there will be serious problems in production. could you please help me out in this issue
venkat, thanks for you quick replay. but our problem is, evnthough we disabled the second dropdown till the first one is selected, there is chance of changing the first dropdown item, ( when our first dd is got changed , second one shud populate according ..) so still the same issue. in our loact development inveronment it is working fine. when we are doing a performence test with low band width, then it is giving error. we have to deploy this application in south africa, which is known for low bad width, i guess there will be serious problems in production. could you please help me out in this issue
Hi Ravi,
Let me introduce myself –I have been working in JSF with ICEfaces from last 3+ year.
Ravi here is the complete exaple to restirct the user to access unuthorized URL using phaseListener.
Code:
public class LoggedInCheck implements PhaseListener {
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
public void beforePhase(PhaseEvent event) {
}
public void afterPhase(PhaseEvent event) {
BridgeFacesContext fc = (BridgeFacesContext)event.getFacesContext();
// Check to see if they are on the login page.
boolean loginPage = fc.getViewRoot().getViewId().lastIndexOf(“loginCore”) > -1 ? true : false;
if (!(loginPage) && SessionHelper.getLoggedInUser() == null){
NavigationHandler nh = fc.getApplication().getNavigationHandler();
nh.handleNavigation(fc, null, “redirect_to_login”);
}
}
}
Before this you have to register this phage Listner class into faces-conif.xml, as below
LoggedInCheck
*
redirect_to_login
/login/loginCore.iface
Hi I am sheetal currently working on jsf.can anybody tell me how to give error message on onChange event of textbox using .in java server faces
You have written “Use Tomcat instead of JBoss to avoid server restart for each changes.” but there is no need to restart server for any changes. You can use JRebel http://www.zeroturnaround.com/jrebel for hot deployment.
Best practice would be to use PrimeFaces :)
http://primefaces.prime.com.tr/en/
Pingback: JSF Best Practices « Yigit Darcin's Blog
myFaces actually are an apache implementation of JSF specification
Hi Venkat,
I am new to JSF. which server faces is best for project. what are the faces there?. what are the open faces?.
this information will be useful for me.
Pingback: JSF – Buenas prácticas « cerITdumbre
JSF Gurus,
I am facing one issue with trinidad inputHidden tag. I need to pass updated value to other functionality on click of a command button(partial trigger present on this button). So I have added one partial trigger on input hidden. But its not working. So I have added inputText with style hidden. Its working fine. But Later i have to have so many inputHidden. So i cannot have all the inputText with style hidden. It’ll slow the rendering of page. So please guide me what would be the alternate option for having inputText with style hidden.
How to have updated bean values in JSF on click of partial trigger button.
Thanks,
DOM
Hi there! I’m at work surfing around your blog from my new iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the outstanding work!
How to reset input text fields inside datatable.I am using webui and jsf 1.1
No one routes for the evil villan who’s run off with the
hero’s beau, same applies to a site that’s been stuck in Google’s
naughty corner. 20 percent of customers have the potential to
spend five times as much as they do currently A relatively small amount
of marketing effort creates the majority of output.
* Page SEO: Your page is optimized by various means which include,
choosing the right keywords, placing them right, adding anchor text linking, adding call to action in various places on the
page.
In filing the case, in United States District Court, lawyers
for the plaintiffs argued that the corporation had been unfair and deceptive in deploying
users’ names and photos in marketing without the need of consent.
In its defense, Facebook took a press-freedom strategy, saying it did not need
to have consent since sponsored stories had been basically “news,” since all Facebook customers had been public
figures to their pals. Details of the tentative settlement had been not disclosed.
facebook likes free online (www.412gether.com)
Howdy! we all could have sworn I’ve included this website before buto after browsing through malos angeles of the articleyour account details I expected it’s capabilities to me: d Regardless, i truly do’m certainly never delighted we suppose found it while you I’ll be borisk free-marking it and checking for you personally often; )
Sweet blog! I found it while surfing around on Yahoo News.
Do you have any suggestions on how to get listed in Yahoo News?
I’ve been trying for a while but I never seem to get there!
Appreciate it
where to buy roche valium 5 mg of valium – valium high description
Estoy ilusionado por poder escribir en la web. Me gustaría
contar más pero no tengo tiempo debido a mi web webmoli.com.
Yo espero que le gusten estas palabras. Porque a mi me encanta la
tecnología
Nombre: Lorrine Noyes
Mi edad: 21
Found a copy of your article here: http://www.javabeat.net/jsf-best-practices/