Tutorial: Developing Your First Spring Web Application

Discussions

News: Tutorial: Developing Your First Spring Web Application

  1. Check out these updated Tutorials for Spring 3 and Hibernate 3.x
    Spring 3 Tutorial I: Setting up a Spring 3 Environment, from TheServerSide.com
    Spring 3 Tutorial II: Spring without XML; IoC with Spring Annotations

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

    TSS has excerpted a chapter from the 'Spring Live' book, by Matt Raible, that shows you how to write a simple Spring web application using the Struts MVC framework for the front end, Spring for the middle-tier glue, and Hibernate for the back end.

    Read Spring Quick Start Tutorial: Developing Your First Spring Web Application

    Recommended Books for Learning Spring

    Spring in Action  ~ Craig Walls
    Spring Recipes: A Problem-Solution Approach  ~ Gary Mak
    Professional Java Development with the Spring Framework ~ Rod Johnson PhD
    Pro Java EE Spring Patterns: Best Practices and Design Strategies ~ Dhrubojyoti Kayal

    Threaded Messages (37)

  2. Business Delegate?[ Go to top ]

    Matt,
    Dont know if its a matter of naming, however traditionally "Business Delegate" is used to front Session Facades, etc. to hide the complexities of EJBs, JNDI, RMI, etc. ? (not applicable in this case)

    Spring also does provide support for the idea of a "codeless business delegate", so the use of the term may seem a little off.

    I have personally like the idea of a POJO business service layer ala:
    http://martinfowler.com/eaaCatalog/serviceLayer.html

    Just thought it a little odd seeing the use of Business Delegates and Spring in the same article/book.
  3. RE: Business Delegate?[ Go to top ]

    Mark,

    It is probably just a matter of naming since the *Manager classes are just the service layer. However, AFAIK the business delegate pattern is the closest "pattern" that describes the services layer.

    I'm simply trying to describe the classes that hide the persistence layer - if you'd prefer, I can certainly remove the reference to "Business Delegate". But I do thinks its an accurate way to describe hiding the business logic and persistence details from the client (a Struts Action in this case).

    Thanks for the feedback,

    Matt
  4. RE: Business Delegate?[ Go to top ]

    Matt,

    I would also recommend not going with BusinessDelegate here; Facade or "ServiceFacade" or "SessionFacade" feels more natural for what you're describing. I generally look at BusinessDelegates as client-side proxies, masking client/server remoting details around a business interface. Thankfully, with Spring AOP, we don't have to code them anymore.
  5. I downloaded the accompanying source code for this chapter from here http://www.sourcebeat.com/downloads/myusers-ch2.tar.gz and have had not a lot of fun trying to get it working in WSAD.

    e.g.

    the JSTL tld files aren't in the WEB-INF directory
    the tld references in the JSPs have typos in them
    there are missing tags in some of the JSPs (e.g. </TR> and no <TR>
    the JSP's reference missing stylesheet classes (e.g. <tr class="even"> and no reference to stylesheets in the JSP)

    I'm sure Spring and Hibernate is great but so far all I've learnt about is JSLT, and I'm still gettting a page up that says

    User Id First Name Last Name
    ${user.id} ${user.firstName} ${user.lastName}
  6. I downloaded the accompanying source code for this chapter from here http://www.sourcebeat.com/downloads/myusers-ch2.tar.gz and have had not a lot of fun trying to get it working in WSAD
    Your problem is most likely that you're using WSAD. ;-) What version are you using? This app works fine on Tomcat 5.0.x. It also requires a Servlet 2.4 container.
    .e.g. the JSTL tld files aren't in the WEB-INF directorythe tld references in the JSPs have typos in themthere are missing tags in some of the JSPs
    This is because Servlet 2.3+ containers can dynamically load .tld files directly from the WEB-INF/lib directory. All you need to do is use the URIs in your taglib declaration - rather than the URI you might normally specify in web.xml.

    As far as missing <tr>'s - please let me know where they are and I'll fix it. Feel free to post a URL from the demo.

    The stylesheet you're looking for is provided by SiteMesh's decorator. There's a tr.even class defined in the global.css file.

    table.list tr.even {
        background: #eee;
        border-top: 1px solid silver;
    }

    I'm sorry this app isn't working for you so far, please contact me at mattr at sourcebeat dot com if you'd like more help.
  7. This is because Servlet 2.3+ containers can dynamically load .tld files directly from the WEB-INF/lib directory. All you need to do is use the URIs in your taglib declaration - rather than the URI you might normally specify in web.xml.
    Sorry, I meant to say "containers can dynamically load .tld files from the JARs in WEB-INF/lib. The JSTL JARs have .tld files in their META-INF directory with their URIs in them.

    Where's the "preview" button on this thing?
  8. Hi

    I'll persevere with the example and then email you back with specifics.

    As far as WSAD goes, I'm using the very latest version, 5.1.2 on Linux.

    I was trying the demo using the Websphere 5.1 test environment built into WSAD. I'll try the Tomcat one instead.

    I guess a lot of commercial developers will be using WSAD and Websphere (WSAD is an awesome product, its capabilities are mind boggling). This being the case, I think it would have been better if the front end code adhered to the keep it simple stupid philosophy too.

    As an experienced WSAD developer, used to Struts and EJBs, I was hoping to see how I could swap out our hand coded middle layer with Spring and our backend persistence stuff with Hibernate, but so far the problems have been sorting out getting the front end up - I've had to find out about jstl, and no will have to get tomcat and work out how WSAD deploys to that etc.

    I guess my point is, if the front end had been a simple servlet 2.3 / struts application, then you would get a much wider audience.

    Anyway, I will either persevere with trying to get jstl to work, or otherwise just wing it with scriplets or struts tags. Once its all working I can send you a WSAD 5.1.2 generated EAR file, for others to use.
  9. I've had to find out about jstl
    If you're using JSP, it's well worth your while to find out about JSTL, so that time will have been well spent, anyway.
  10. I've had to find out about jstl
    If you're using JSP, it's well worth your while to find out about JSTL, so that time will have been well spent, anyway.
    In WSAD 5.1.1, you can do Project -> Properties -> Web Project Features -> JSP Standard Tag Library (checkbox), then click Apply. This will put everything you need into WEB-INF/lib.

    Doing this didn't get me any TLDs, so I obtained them from http://apache.mirrors.versehost.com/jakarta/taglibs/standard/jakarta-taglibs-standard-current.zip or you could use the tarball.

    Hope this works with WSAD 5.1.2!
  11. Grab it from here.
  12. Yep, I'd already done what you said, ditto grabbing the TLD's, and it still printed out $'s in my pages rather than variable values, so my EAR file has stripped out JSTL code in the JSP's altogether (to be honest doing it all in struts means one less load of technology to think about).
  13. OT: WSAD and JSTL[ Go to top ]

    I had no problem running the examples from the command line using Tomcat, and I set it up in regular Eclipse with no problems (once I worked around the irritation of Eclipse trying to validate every little piece of xml and not being able to do so because of the firewall), but in WSAD I'm having the same problems with the JSTL that Paul had. I've configured WSAD so it knows where to go to get the tlds. But if I run something like this:

      <c:forEach var="num" items="1,2,3,4" >
        <c:out value='${num}' />
      </c:forEach>

    or this:

      <c:forEach var="num" items="1,2,3,4" >
        ${num}
      </c:forEach>

    I get this:

     ${num} ${num} ${num} ${num}

    Obviously Websphere is finding the taglibs and the associated classes, because I get the right number of iterations. But something is messed up, because the variable doesn't resolve. Has anyone else had this problem? Did you solve it?
  14. Thanks for posting this Paul - I'm sure WSAD users will appreciate it.
  15. The following is an optimized IBM WSAD 5.1.1 workspace containing the equinox (Appfuse) application. The app is running on a WAS 5.1 Server. The view layer is Struts. The DAO layer is Hibernate (w/ MySQL database). The workspace contains a minimal amount of libraries to make the application run. You can download the complete workspace and be up and running within a couple of minutes!

    https://appfuse.dev.java.net/servlets/ProjectForumMessageView?messageID=10546&forumID=566

    Happy Appfusing,
    Joel Cohen
  16. The following is an optimized WSAD 5.1.1 workspace
    containing the full Appfuse application (including
    security). The app is running on a WAS 5.1 Server. The
    view layer is Struts. The DAO layer is Hibernate (w/
    MySQL). The workspace contains the minimal amount of
    libraries to make the application run. You can download the
    complete WSAD workspace and be up and running within a
    couple of minutes!

    Note: I had to remove the .metadata folder to meet the upload requirements.

    https://appfuse.dev.java.net/servlets/ProjectForumMessageView?messageID=10575&forumID=566

    Happy Appfusing,
    Joel Cohen
  17. Struts Hibernate and Spring Tutorial[ Go to top ]

    HI, Visit: http://www.roseindia.net/struts/hibernate-spring/index.shtml. This tutorial shows how to develop User Registration and Login Application using these technologies. Regards Deepak Kumar
  18. http://www.techfaq360.com/tutorial/spring/springwebapp.jsp
  19. Developing Your First Spring Web Application .. code is there just download and deploy into tomcat to test it... http://www.techfaq360.com/tutorial/spring/springwebapp.jsp
  20. Its a nice article.
  21. The TLDs should be contained in the META-INF directory inside the jar. As Matt mentioned earlier, since the 2.3 spec containers will search inside the META-INF within the jar for TLDs so you only need to drop the jar file into WEB-INF/lib. Finally, you use the URI in the TLD file at the top of your pages.

    HTH

    Graham O'Regan
    Ellison Brookes
  22. To Matt's defense... I have seen the code structure and it is quite standard. I have also worked with WSAD a bit. My experience is that if you don't start with its code directory structure, you will have real problems. WSAD has its own view on the world of Java dev, and I am not surprised that a standard build script driven project will not deploy correctly out of the box.

    I think if you evaluate it with Eclipse and simpler container (Tomcat, Resin), you will be happier, and you may get spoiled. It is alot easier that WSAD, IMO.

    On another note, please let us know if you do get this working in WSAD. Many corporate developers are required to use it, and it would be great for them to know how to leverage a set of tools that AppFuse packages together.

    Have fun!
  23. I have imported the example source code for this chapter into WSAD 5.1.2, and done the following changes to get it to work under Websphere 5.1:

    Removed references to any JSTL code and replaced it with standard Struts tags

    Removed reliance on having to run the demo in a servlet 2.4 container (imported various TLDs into WEB-INF and updated web.xml)

    Removed any reliance on decorators / stylesheets - it looks ugly but it works.

    Made the project a WSAD Web project which in turn is a module in a WSAD J2EE application.

    The purpose of all this was to get the project up and running under WSAD/WAS, so that people can focus on the Spring and Hibernate parts of the application, rather than spend time getting the front end to work under WSAD.

    If people are interested the EAR file is about 1.5 megs (tgz) - I'll post it somewhere.
  24. If people are interested the EAR file is about 1.5 megs (tgz) - I'll post it somewhere.
    I would love to have access to the .EAR file. Please post it somewhere ! Thanks
  25. I couldn't find the EAR code .I want to grab the EAR module at the earliest.Please post it somewhere.
  26. I'd skip this book in favor of Professional Java Development with the Spring Framework, as I recall to be released somewhere this year

    I've browsed thru it and IMHO There isn't any compelling reason to buy it, Most of the information in it is just as well described in the project documentation. The book doesn't really offer any additional insight

    Posts like this on the author’s blog don't inspire a lot of confidence in the author either as he seems to be winging it as he goes along

    The writing feels somewhat amateurish, and there is a general lack of consistency
     
    The demo’s simple as they may be, aren’t working properly even on his demo page and contain multiple security related flaws which the author doesn’t care to fix

    To its defense, it’s still an early draft but by the time the book is worth reading, the other book will be out and will be better
  27. I followed step by step from Spring Quick Start and got this exception very early. I am using:

    ant 1.6.1
    tomcat 5.0
    jdk 1.4.2_3

    Here is the exception when trying to create the User table:

    NFO - Binder.bindRootClass(229) | Mapping class: org.appfuse.model.User -> app_user
    DEBUG - Binder.bindProperty(475) | Mapped property: id -> id, type: long
    DEBUG - Binder.bindProperty(475) | Mapped property: firstName -> first_name, type: string
    DEBUG - Binder.bindProperty(475) | Mapped property: lastName -> last_name, type: string
    INFO - LocalSessionFactoryBean.afterPropertiesSet(372) | Building new Hibernate SessionFactory
    INFO - Configuration.secondPassCompile(613) | processing one-to-many association mappings
    INFO - Configuration.secondPassCompile(622) | processing one-to-one association property references
    INFO - Configuration.secondPassCompile(647) | processing foreign key constraints
    INFO - Dialect.<init>(82) | Using dialect: net.sf.hibernate.dialect.HSQLDialect
    INFO - SettingsFactory.buildSettings(62) | Use outer join fetching: false
    INFO - ConnectionProviderFactory.newConnectionProvider(53) | Initializing connection provider: org.springframework.orm.hibernate.LocalDataSourceConnectionProvider
    INFO - TransactionManagerLookupFactory.getTransactionManagerLookup(33) | No TransactionManagerLookup configured (in JTA environment, use of process level read-write cache is not recommended)
    INFO - DriverManagerDataSource.getConnectionFromDriverManager(152) | Creating new JDBC connection to [jdbc:hsqldb:db/appfuse]
    DEBUG - JDBCExceptionReporter.logExceptions(36) | SQL Exception
    java.sql.SQLException: Access is denied
    at org.hsqldb.Trace.getError(Unknown Source)
    at org.hsqldb.Trace.check(Unknown Source)
    at org.hsqldb.Trace.check(Unknown Source)
    at org.hsqldb.User.checkPassword(Unknown Source)
    at org.hsqldb.UserManager.getUser(Unknown Source)
    at org.hsqldb.Database.connect(Unknown Source)
    at org.hsqldb.jdbcConnection.openStandalone(Unknown Source)
    at org.hsqldb.jdbcConnection.<init>(Unknown Source)
    at org.hsqldb.jdbcDriver.connect(Unknown Source)
    at java.sql.DriverManager.getConnection(DriverManager.java:512)
  28. My guess is you're on a *nix machine b/c of the "Access is denied" error. One of the things I tried to do w/ this sample app is make it very easy to build and deploy. I didn't want to force users to install and start a database - so I chose HSQLDB and it's in-memory database feature. If this doesn't work for you, you can easily change web/WEB-INF/applicationContext.xml to use a "url" property that points to a running instance - and start it manually before you start Tomcat.
  29. Running on Windows 2000. I had no problem with HSQL when I tried it with JBOSS before!.
    I guess I should switch to MySql for continuing the Quick Start.
  30. I agree[ Go to top ]

    I agree that the demo is simple - but this is often the easiest way to learn a new technology IMO. CRUD seems to be 80% of the web apps I develop - and showing users (especially beginners) how to do that simply seems important to me. If you want to see something more advanced - let me know and I'll add it.

    I agree that Professional Java Development with the Spring Framework is going to be a good book (esp. b/c of the geniuses behind it) - I hope to learn stuff from it myself.

    As for security holes - I agree that users can upload files and hack my server - but I'm not trying to show you what to do with files after you upload them. I'm simply showing you how to upload them. Are there other security issues you believe I should fix? If so, please let me know.

    I think it's important to re-iterate the goal of this book: <em>It is aimed at users that are familiar with Java development, but have never used Spring.</em> I believe KISS is important, but I'm also interested to hear how you think I can make it better.
  31. Matt is doing a great job![ Go to top ]

    I just became a ERP Subscriber to this book yesterday. I downloaded the sample chapter, but I'm not much of a fan of Struts (my own personal reasons).

    I was very *very* curious as to how Mark refactored the quickstart tutorial into SpringMVC. SO I subscribed. I couldn't wait!

    Matt, you're doing a fantastic job! This book is great for a newcomer like me. I do not have any real world experience in Java, and the 2 days of reading this type of book helped me tremendously!

    The book is geared in a tutorial manner for beginners like me.

    I believe to get the most out of this book, you would want to have a 'few' reference books along with it. For example, 'Expert One-On-One' or possible the Pro Java book coming out later this summer.

    I can't wait to see the iBatis coverage!

    Great Job Matt!
  32. I agree[ Go to top ]

    Matt,
    if CRUD is 80% of what you do, then why not have middlgen as part of appfuse? Appfuse is decent BTW, good job on it...
    as far as your spring book, is that an online book only? are there print copies?

    -jp
  33. RE: Middlegen[ Go to top ]

    The main reason I don't use Middlegen is because I tend to like developing my POJOs first, and then creating the schema from those. On projects where I have control of the database - this solution works well. For those projects that have an existing database, I've often found it easier to use iBATIS.

    As far as Spring Live goes - it's only available in PDF. The main reason for this is because we're updating it so often, it'd be tough to keep up with a print version. I have talked with folks that have printed it out w/o any problems. I've heard I need to change some of the code color to make it more print-friendly though.
  34. Nicely done[ Go to top ]

    Very well done Matt - there's no question that I learned more about Spring from your Chapter #2 than the other intros I've read combined. You book is clearly targeted at me - someone with lots of Struts web app experience, but weak on decoupling the business and DAO layers, IoC, AOP and transaction management (to name a few). Again, good job!
  35. I'd skip this book in favor of Professional Java Development with the Spring Framework
    While I certainly believe that Pro Spring will a good book (being one of the authors), I personally do not see it as direct alternative to Spring Live.

    Pro Spring aims to cover Spring in its entirety, of course from a user perspective but also illustrating concepts that help to understand the internal workings. While it will be able to serve as introduction too, one of its goals is to also give signifant value to people who are already Spring users.

    Spring Live, on the other hand, has a different mission: It is a tutorial-style introduction for people who have had none or hardly any exposure to Spring before. A strong focus is on web applications, particularly on Struts/Spring integration, and on local middle tiers for such web applications.

    From my point of view, the primary audience for Spring Live are Java web application developers who are interested in Spring, particularly people who are working with Struts. Matt does a good job in picking up that audience where it is, showing those people ways to improve their architectures with Spring.

    So keep up the good work, Matt, both on the book and on your blog!

    Juergen
  36. Books[ Go to top ]

    How many Struts books are out there? :) Same idea, some are quickstarts, others are the definitive guide.
    Plus it is beneficial to have more books authored by people other than the Spring developers.
    I think its a good idea, plus Matt is open to feedback.
    Good work.
  37. FYI - There seem to be some pages missing from the online version (19, 23, 28, 29, 31, 34, 36, 37, 39, 40, 42, 43, 46, 49, 52, 54, and 55) at http://theserverside.com/articles/content/SpringLive_Chapter/chapter2.pdf
  38. RE: Missing pages[ Go to top ]

    FYI - There seem to be some pages missing from the online version (19, 23, 28, 29, 31, 34, 36, 37, 39, 40, 42, 43, 46, 49, 52, 54, and 55) at http://theserverside.com/articles/content/SpringLive_Chapter/chapter2.pdf
    I just downloaded it and they appear fine for me. I'm using the "Preview" program on OS X. You might try saving it your hard drive before viewing.