dotkam.com stats

What is The Best Java Web Framework?

What is the best Java web framework

No, really, what is it? Are you one of those people who ever wondered why there is actually more than one? Or you work with Struts for 5 years in a row, and think it is the best, just because you know all the nasty hooks you have to implement to make it do what you actually need?

Are you one of those die hard Rails fans, who (as most of Rails developers) does not really know Java, but already has a lot to say how bad it is?

Do you work in C++, and feel absolutely confident, that the framework, your company had developed for the last 25 years, that build web pages via socket programming is the best, and the most efficient one out there?

Is your company big enough, so it has a mature team of software (what they call themselves) architects, that take open source frameworks, and write their own single wrapper framework around it that, as they think (since they wrote it), is the 8th wonder of the (ancient) world?

You, see, I am a consultant – I know many of you, since I met “you” before :)

This one will be a very short article about my experiences with several Java Web Frameworks out there. Here we go:

Spring MVC Would be a good choice for the most of your needs

(I’ll give a short controller example below)

Wicket Interesting to look at – no XML, no JSP (JSTL), just Java and HTML. Can mimic a flow in a WebPage object. Better separation of concerns than, for example, in GWT (e.g. no Javish CSS, etc.). Good Community

The only thing that is off is your dynamic HTML elements are done in Java

Spring Webflow Yes – it is a separate beast. It mostly is good, and makes sense, however, in practice, once you need to do something a bit more complex that a shopping cart or a hotel booking app (hint, hint), you can run into problems. “Back button” and “Double click” are not very well handled by the framework, may get an exception while bookmarking (there is a magic recipe, but far from being simple, and intuitive), sharing data across the flow, last resort error handling are not simple, etc.
Stripes Good / simple (no XML – conventions), but not very actively maintained – hence not as mature. (good community though) Worth to look at for simple projects.
Struts Just architected wrong from the very beginning: Validation (XML – why? What about minimum search criteria, what about several, what about nested OO validators!?) / 0 for NULLs / Multi Action Forms / Testing (without StrutsTestcase) / etc. ) Improved a bit since WebWork merging, but still lots of “code smells”.
JSF Quite hard to keep up with all these JSF based JSP tags + integration with security is not simple + full JSF solutions are usually Frankensteins with many pieces from different vendors.
Tapestry Not bad, actually make sense, when you get it. But have you ever looked and tried to follow the Tapestry code? – Very complex implementation, if ever need to look inside the code + Tapestry does take time to learn, so forget about a new off-shore team, or fresh out of college not so geeky grads, taking it on.

And here is why I like Spring MVC:

  • Binding / Validation is done just right – clean, testable, reusable
  • Multiple View options ( PDF, XML, Excel, Atom, etc… ) done easy [AbstractExcelView, AbstractFeedView, AbstractJExcelView, AbstractPdfView, AbstractUrlBasedView, AbstractXsltView ]
  • Annotation based – no XML madness, and very clear when looking at the code – check the Pet Clinic in Spring 3.0 M3
  • Integrates with Spring JS very nicely ( in case needed )
  • Handing requests and parameters with ( Spring ) expression language – quite flexible
  • In Sping 3, MVC is actually REST aware (GET, POST, PUT, DELETE)

You can download Spring STS, import sample projects, and see many examples on how to use it, but here is a very simple controller example from Spring’s Pet Clinic:

@Controller                                                 // it’s a controller
public class ClinicController {
 
      @RequestMapping("/welcome.do")           // that all there is to mapping
      public void welcomeHandler() {
      }
 
      /** @return a ModelMap with the model attributes for the view
                                 uses org.springframework.core.Conventions */
      @RequestMapping("/vets.do")
      public ModelMap vetsHandler() {
            return new ModelMap(this.clinic.getVets());
      }
 
      @RequestMapping("/owner.do")
      public ModelMap ownerHandler(@RequestParam("ownerId") int ownerId) {  // parameters are passed in easily
            return new ModelMap(this.clinic.loadOwner(ownerId));
      }
}

It all depends on project’s requirements / timeline / resources / requirements / technologies already in place / etc… But having a choice, I do choose Spring MVC – it just makes sense: easy implementaion with Spring Roo / integration with Spring’s back end / support / community / releases / etc… I also like where Wicket is going, but it feels like “it is still going…”

In any case – good luck, and remember – if it does not have to be Java, but you still like to “stay close”, I would definitely give Grails a shot.

38 comments

  1. Did u had any views on zk, aribaweb, richfaces and icefaces. I am feeling very good about zk rich widgets and pure java approach for handling of events.

  2. We will appreciate knowing your opinion on HybridJava as well. Specially designed to eliminate “architects”.

    Warning – take some time to understand it first impression may be false.

  3. @Raja,

    I. ZK

    Things I liked:

    1. It is simple and very feature rich
    2. Binding and validation
    3. It allows you to choose between XML or code.

    Things I did not like:

    1. It is not free unless the project is open source, so it requires me to sell it to the client before using it on a project.
    2. It generates HTML and Javascript, so on case there is any modification needed for certain browsers, framework needs to be hacked by developers. I only used it for my pet projects (never on a client site), however I remember having some rendering problems (JS – spacing, funny looking page before “ZK” completes the page load, etc.), I take it as a temporary issue, since the framework is improving.

    (Again, I am not a ZK expert)

    II. Heard about “aribaweb” – never used it.

    III. As to anyFaces (iceFaces, richFaces, etc..) I personally never had a smooth experience with them. They extend JSF to some extent, and provide some proprietary tags, but figuring out some simple things as “how to pass parameters to so and so action” may take some time. For me xyzFaces are code smells. I have not had a chance to look at Spring Faces, so may be Spring made JSF a bit better.

    /Toly

  4. @Alex (Саша? :) ),

    You’re right, I would need “some time to understand HybridJava first”, since I’ve never used it. From what I read from the main page, one point that I found awkward is “Unlike some other technologies View, Controller and session-persistent data belong to one and the same class instance which is good for performance”, but again, maybe I need to read more about the overall HybridJava philosophy to understand the benefit of coupling V and C (and M?) together.

    It would really help if you guys put some design effort on http://www.hybridserverpages.com/, to make it a bit easier for the eyes to get. + although I think “HybridJava.doc” is great (still reading it) – cmmon, a DOC file with code? Basically what I am saying is – run this DOC file though some wiki generator, and have your self a wiki – that would help other comers to hybridserverpages.com.

    Thanks for the introduction though :)
    /Toly

  5. Hi Toly (Анатолий?)
    … Controller and session-persistent data belong to one and the same class instance …
    — In fact the same could be also explained as “HybridJava does not use JavaBeans”. So the presentation data does not travel from one instance to another in a cycle. It was not a special aim or design solution to couple V and C together. C and V just happened to be in one instance after a somewhat deeper philosophy was applied – that is Occama’s Rasor – not to do (or use) anything unless it is absolutely inevitable.

  6. Hi Toly!

    С вашей подачи мы несколько поработали над содержанием сайта http://www.hybridserverpages.com/. Спасибо за прежние советы и надеемся на новые.

  7. С днём программиста!

  8. @Алексей,

    Можно на ты. Спасибо – Hybrid Server Pages туда же! :)

    Сайт выглядит значительно лучше. Красного многовато, но эт вкусовое… Рекламка сверху не помогает, но если чё приносит, то почему бы и нет. Вижу, что с микрухой (M$) вы близки так как просто экспорнули doc через Microsoft FrontPage 5.0 :)

    Насчёт бизнес модели я не совсем понимаю. Помоему лучше открыться и залить HJ на github, чтобы работали все кому интересно на проектом. Если пойдёт, лайсенс можно апдэйтнуть и продавать энтерпрайзам. Потому как идея есть – но альтернативы в сети up the wazoo.

    В любом случае удачи!

  9. Привет!

    Никто не обидится что по-русски чешем?
    Рекламка если и помогает, то не нам, а GoDaddy. Разведка донесла что и ты с оным дядей знаком.

    У одного писателя стоит frontpage, а другой его с собой забыл взять оказалось. Расстояние – где-то 10 000 км. так что делаем чем придётся.

    Заливать не хочется. Прежде всего потому над этими сорсами никто всё-равно никто работать не сможет. Сложновато и по необходимости запутано. Потом там есть действительно нетривиальные алгоритмы, делиться неохота. Пусть попрыгают. Наконец – если говорить о языке, трансляторе и фреймворке, то увы, есть такое впечатление что всё уже сделано. Так что делиться в смысле работы просто нечем. Есть некоторые идеи, но они теперешнего кода коснуться мало. Кажется первоочередным будет разработа плугина к Ecipse. Жаль что у нас нет такого специалиста around.

    Up the wazoo мне перевести не удалось, но смысл кажется я понял. Их много, эти фреймворков, да. До 100. Приходится с ними знакомиться в порядке похвальбы (их собственной). Пока что такое впечатление что мы ВСЕХ их поимели. Кроме всего прочего у меня на домашнем линуксе время отрисовки страниц (после разгона) часто показывает 1 ms. Даже глазам своим не верю.

    Касательно лицензии – о ней можно узнать только сгрузив зип файл. Она там внутри отдельным файлом.

    Кстати – а ты откуда бьёшь по клавишам?

  10. @Alexey,

    Даров! А чем русский не язык!? Можно и по китайски, ток я пока не умею :)

    Бью из лучших домов Филадельфии (прим. ред. – Остап Бендер)

    Да, когда “своё”, ощущение ‘всех поимели’ частенько аккомпанирует – эт нормально.

    Насчёт сайта есть идея для тебя: переделай этот сайт на “HJ” вместо Front Page, так чтоб не только ты на домашнем пингвине, а все смогли ‘почувствовать разницу’.

    А есть ваще реальные клиенты (энтэрпрайз/open source)? Если есть, приведи пример на сайте, эт обычно помогает, создаёт некую видимость выхода из инкубатора.

    А ты с “писателем” откуда?

  11. Ну я подумал что ты дорожишь англоязычными посетителями.

    А на чём получится разница? Пока все заходили по-одному, а трафик на подходе к дяде наверное больше чем на подступах к моему dsl. Чтобы заметить разницу надо лог смотреть. В Sample Application у меня вписан тайминг.

    Кроме того дядя не даёт сервлетного контейнера. Мы тоже думаем в направлении другого хостинга, но всё было не до этого – продукт только-только дописался, пару месяцев тока. А ещё при дяде неплохая статистика. Может чего посоветуешь?

    Питер – Силликоновка.

  12. Это ж благ (или как бритиши говорят ‘блог’), я тут мыслями дорожу, а посетители ими делятся и читают мои, так что англо / латыно / словако.. эт совсем не важно

    Дядям и тётям я даю отдыхать, и хостаю сам, хотя хотелось бы ужо перекинуть на кого-нить за $3/4 в месяц. А то када comcast шалит, надо IP перенастраивать вручную

    Статистика для продукта – эт врядли количество поситителей сайта, а скорее количество применений самого продукта… Возьми да и примени HJ у себя на работе или продай идею (в смысле ‘убеди’) кого-нить из компаний создать чё-нить клёвое / полезное на HJ

    Кстати, http://siliconovka.spb.ru/ очень порадовала :)

    DHH (папа Rails) сегодня оставил интересный комментарий: “Good reminder to be careful with your advice. Seems that the “skinny controller” idea was taken as “eliminate all code/flow”. Not so.“. Это не насчёт HJ, но близко к теме

    Насчёт хостинга, попробуй 1&1. дядя тож ничё, но интерфэйс у них ужас, плюс эти флэшные рекламы – ноу гут

  13. There’s something changed in ZK 5.

    1. Although ZK 3.6 is under GPL Dual license( which means you do need to pay for a commercial use), ZK 5 has Community version which is under LGPL.

    2. If you want to do something that is Browser specific, you can use ZK Native namespace to output pure XHTML + Javascript code, and if in your javascript you want to cooperate with ZK Widgets, you don’t have to “Hack” anymore. ZK5 rebuilt it’s client-side js with a complete OO architecture, which makes the cross-operation between your js code and ZK js widgets become an “official-support operation”.

  14. Are your comments on Tapestry based on version 4 or 5? I’ve heard 5 is substantially different than 4 and below.

  15. ZK did recently change to LGPL.

    What about Vaadin (previously IT MILL)?

    Or Play framework?

    tribui

  16. i like your view on Struts. it made me ROFL :D

  17. Let’s say your company does have something truly amazing for java. Like rails, but faster to develop with. But, you don’t have the resources spare to open source it & turn it into a generic framework not tied to your companies projects and standards.

    What would you suggest?

  18. I was Java web developer for couple of years. I used Struts, JSP, tried JSF. I was also working with own-build framework based on XML to HTML transformations by XSLT.

    I was working with Hibernate and OJB.

    Before Java I was using PHP for couple of years, and I was pretty satisfied with it. I think it was great solution at the times, and well I think it is still pretty good.

    I always felt that all that Java stuff is little to heavy for building web apps. Sometimes I felt as I would have ball at my feet. And as I was switching to more advanced technology I felt this ball gets bigger (JSF).

    I sometimes felt that I miss my old, good, simple PHP. But on the other side I knew that Java provide lots of better designed, more object oriented and fresh solutions (Hibernate etc).

    Now I switched to Python and Django. And I have to say that the ball is gone. I have all the good stuff that well designed, object oriented language can provide me. I have simplicity, speed of development, well designed ORM. I have separated, non-bloated template engine, etc.

    I hope I will stick to Django/Python for some longer time :)

  19. Tapestry 5:
    - it is a project of one person, not really community-driven; as I saw the core of Tapestry 5 was developed by this single person without collecting the requirements of the users
    - the Tapestry developers left Tapestry 4 users without migration path to the new Tapestry 5 version, so I would not trust them anymore; I will never use Tapestry again (I have some Tapestry 4 websites still around, but for new projects I switched to Wicket instead of Tapestry 5)
    - just an example blog: http://ptrthomas.wordpress.com/2009/09/14/perfbench-update-tapestry-5-and-grails/

  20. Give a try to ItsNat. In some way ItsNat is similar to Wicket but Single Page Interface oriented.

    http://www.itsnat.org

    My proposal:

    Read this tutorial (very short really):
    http://itsnat.sourceforge.net/index.php?_page=support.tutorial.core

    See it running online:
    http://www.innowhere.com:8080/itsnat/servlet?itsnat_doc_name=manual.core.example

    Now try to do this very simple example with any of previously listed frameworks.

    Yeah, I suppose is possible…
    in the same time?
    with similar amount of code?
    with the same freedom?
    with the same flexibility?
    in a single page?
    with the same learning curve?
    with the same platform requisites?
    running on Google App Engine?

  21. Thanks for the great overview.
    My favorite is missing and I just want to mention it: Seam. It’s like JSF2 on steroids ;-)

  22. Stripes is awesome but I dont think that the “maturity” is the problem maybe the only problems is that it is not an apache project. :(

  23. In my experience it is hard to beat GWT in productivity and results.
    At my current project there are 3 web frameworks in use, Spring MVC, Wicket and GWT.
    The GWT apps are built and maintained a factor 3-4 faster than the other two.
    I think it is because of the low complexity and Swing-like development.
    GWT also has the lowest amount of bugs (Wicket the highest – what a buggy framework :( )

  24. I was searching for the “right” web framework for a long time now. Spring MVC was one of the frameworks I tried. It is not bad, but it would be hard to use it without the rest of Spring. But the main disadvantage for GUI applications is the bad modularisation. Imagine a page with several tabbed panes. With Spring MVC you have to encode the state of oll tabbed panes in the URI (or use JavaScript). This means that every GUI element needs to know of the other GUI elements to be able to encode their state to the links.

    Wicket offers a better programming model with highly reusable and easy to develop components. It feels natural to build flows with Wicket.

  25. Could you say something about Seam and Grails?

  26. For my taste Wicket is the one – it is so straigthforward and pleasent simple.
    And you can get a welldone Documentation
    Even integration with Scala works like a charm …

  27. JSF has gotten MUCH easier to use since version 2 was released… no more massive configuration – it just works. And even better, when running on a JEE 6 server, you don’t even need to configure dependency injection – it just works.

    JSF2 and JEE6 are leading the pack in my opinion.

    Check it out on http://www.javaserverfaces.org !

    –Lincoln

  28. And yes, there are many extensions to JSF, but they should be thought of more like plug-ins from Grails or other frameworks.

    PrettyFaces ( http://ocpsoft.com/prettyfaces/ ) for example, provides URL rewriting, pretty URLs, parameter management, and dynamic navigation for JSF :)

  29. Two others you should include are Apache Click and Play, haven’t used either in a larger project but both look promising in terms of the future of a Web framework. You should include grails as an alternative, because you can use all java code realistically but why would you .

  30. Word ahead: being the developer of the opensource project JPublish, I am biased in my comment. So, my 2cents here are: again and again, Java developers analyzing web frameworks without considering (too much) the rest of the team (if any). What about the roles dedicated solely to the web design aspects?! Teammates experts in CSS/JS/HTML, but with no time for learning Java/annotations and so on? Do they count? They sure do, unless we (Java devs) claim their part of the work as well?! How will the list above look like if your team will have 3 designers to 1 Java dev ratio?! What if they need to start writing/mocking the pages while you are away?? @RequestMapping?? Or writing a java class/method for every page they need to build and possibly throw away, as required by other frameworks? Don’t misunderstand me, all the frameworks enumerated by this article are great, and I have a great admiration for most of them, but let’s try to step back a bit and try to find the most Designer friendly Java web frameworks. Can we try that? Thank you for your writing.

  31. You are missing vaadin (www.vaadin.com). It is not mainstream but it simply rocks!

  32. Hy Toly!

    Most important news about HybridJava
    1) Version 0.99 available
    2) Expression Language added on many requests. Naturally that is about pure Java expressions.
    3) One more effort taken to explain whet it is. In particular – I have elaborated eight principles of good web framework component model. Naturally – my framework implements them all. Please see this at http://www.hybridserverpages.com/framework.html. I am also bold enough to claim that of all currently popular frameworks NONE fits all the criteria list. Well, I may be wrong of course, but let someone else tell that.
    4) The Sponsor has agreed to a promotion in a form of FREE commercial license:
    Any commercial company is eligible for one free life-time license
    (“license” is defined in file LICENSE.txt) of the Software.

    Limitation: the Web-applications developed using the Software
    may be run only on one physical computer per company.
    To get this promotional license please send an email with the name
    and the legal address of your company to promotion_2010@HybridServerPages.com.
    You will be sent your license number in reply.

    This offer expires after December 31st 2010.

    Will be happy to hear what you think.

  33. florin: Teammates experts in CSS/JS/HTML, but with no time for learning Java/annotations and so on? Do they count?

    You are right, but some frameworks like Wicket and ItsNat try to keep HTML code of templates as clean as possible, in case of ItsNat, templates are absolute pure HTML/SVG/XUL markup (view logic is Java W3C DOM code).

  34. Here is a Java Web Framework that I like:

    Hamlets (previously known as IBM Servlet-based Content Creation Framework) is an open source system for generating dynamic web-pages developed by René Pawlitzek at IBM. A Hamlet is a servlet extension that reads XHTML template files containing presentation using SAX (the Simple API for XML) and dynamically adds content on the fly to those places in the template which are marked with special tags and IDs using a small set of callback functions. A template compiler can be used to accelerate Hamlets.

    Hamlets provide an easy-to-use, easy-to-understand, lightweight, small-footprint, servlet-based content creation framework that facilitates the development of Web-based applications. The Hamlets framework not only supports but also enforces the complete separation of content and presentation. It is the result of a radical software simplification effort.

  35. @ben,

    If there is a desire, there is time. Turn it to open source.
    If there is no desire to do that, donate your core ideas, it is as simple as posting back in comments, or create your own web page with your ideas, or contact whoever you like: DH, Rod Johnson, or any other relevant open source spiritual leader
    Again, it is all about desire/passion, if you have it, time is never an issue

    @Naos,

    Good for you, I admire Python crowd, they are solid, they give no excuses, they are not as arrogant as Railsists, and get the job done. The only problem I see with none JVM based solutions is selling them to various clients, as “big brother”s are afraid of something they do not understand. Hence it is much easier to say: “Yes, if we go Grails / Lift we will be able to _leverage_ you beloved websphere contract with IBM”…

    @Dennis,

    Your favorite, Seam, is not missing, I just did not have a chance to work with Seam, but “JSF2 on steroids” does not sound all that appealing. Again Seam maybe great, I just have not had a chance to use it.

    @Leon,

    Interesting, can you point out any Wicket bugs that you encountered? As to GWT, I like it, but it is too much “view logic” in Java, with HTML5 it just does not seem like a right direction..

    @Christian,

    It seems like you can benefit from Spring Webflow, which is based on Spring MVC, but understands a “flow scope” where you can manage your states through e.g. multiple tabs.

    @Lincoln,

    I just don’t know where to start on JSF2,3,4,5.. JSF has such a bad and convoluted internal design that I would use any of the frameworks I listed + any I have not tried yet (Seam, maybe?) instead of JSF. Unfortunately, I currently use Richfaces / JSF2 via Spring Faces.. definitely don’t recommend.

    @florin,

    I do agree designers are extremely important, but I could not really see what you propose. Did you have anything in mind that is not in the list? And again, I only listed frameworks that I worked with previously. Yes, Florin, @RequestMapping is not a rocket science, and you know what? If there is a designer who knows CSS, but has no idea about anything else, I’ll have s/he do just that CSS: has nothing to do with @RequestMapping. But again, do you have a designer friendly web framework in Java that you have in mind? Do you? What is it? Let’s have a dialogue.

    @Ivan,

    Vaadin is great, I like it. Have not used it for projects, but as a Grails plugin, and it is cool, but I would not say it is a full blown Java web framework. That does not mean it has to be, but the title was “The Best Java Framework” :)

    /Toly

  36. Hi Toly!

    Good news from HybridJava!

    We have reached release of version 1.00. The new feature we added is a very lightweight support for validation. It looks like there will be no new features for at least some time.

    What may be more important we\\\’ve worked quite a bit on the text of our website and the current text must be much more readable than the previous variant.

    Will be happy to hear your comments.

  37. HybridJava version 1.01 available

  38. На сайте hybridserverpages.com добавлены старницы на русском языке.

tell me something...
  1. (required)
  2. (valid email - optional)
  3. Captcha
  4. (required)