This has been asked in few times in this thread. But sometimes its hard to make it decouple. Let say Im dealing with session, cookie stuff how do I decouple or basically how do I move the existing code out from the JSP? UseBean will be a good alternative. But how to deal with business logic with lot of HTTPServletRequest and HTTPServerletResponse and its related objects used services?
Thank you
Developing web-applications in Java has evolved quite a lot over the past 10 or so years. PHP-style JSP pages may have been ok-ish in 1999 but not today. At very minimum, you should isolate your business-logic in a servlet and only have your rendering/view in the JSP. That is just the bare-minimum to pass some form of basic level of hygiene. If you are doing any sort of new development or even refactoring, you should look into a more refined MVC/MVP framework. Spring is a good candidate. Maybe not the "coolest" but definitely established and well-known. The tutorial Andrea mentioned is a good place to start. And don't get too nervous about things like "how does it make sure the right request and session is used" - that is what spring-mvc does, it's the core functionality. Go through the tutorials, try it out and then dig deeper to understand what is happening under the hood and how you can customize the behavior to fit your needs.
I suggest you to use a MVC patter to add the business logic to your web application on Java classes instead of add the logic into the JSP.
Take a look to that: http://static.springsource.org/docs/Spring-MVC-step-by-step/part3.html
Related
I have a simple CRUD website in development process, almost done. I was asked to refactor the code but this time use struts 2 and commons chain. I read a couple of sites like this but wasn't able to know exactly what will be the key roles done by these two (struts 2 and commons chain) in my project. I was also asked that don't worry about struts tags like in this tutorial as the code that i made earlier can be used.
Can anyone give me an insight. Thanks
Note: A day back I started to see about struts 2
Well any framework is designed (most of them) to provide some sort of ease of use. That should be the driver when you chose one.
In your case, I can comment on Struts2.
Using Struts2 provides and enforces a better design in terms of separation of your code responsibilities (model view controller). This way the over all application design is well formed.
On top of this, framework provides many interesting features like interceptors, out of box request parameter assignments, validation, ui tags etc etc which you can benefit from.
So if you are still in the starting phase, yes - go through various frameworks available and weigh them out in terms of what ease you are looking for.
If the website is almost done, I don't see any compelling reason to adapt Struts 2. In fact, the person who asked you all this is the best person to contact, in this case.
Regarding commons chain, yes it can help you implement Chain of Responsibility pattern if it can solve the cases in hand.
I liked using three layers (data/business logic|services/ui) in Java and wish to apply this to a web site in PHP. What advice, links, tutorials could you suggest in this respect?
P.S: I'm particularly interested in knowing how the domain/entity objects can be written and used.
You could go with some frameworks of PHP.
They already done three layer for you
ZendFramework
CakePHP
This could be interesting for you and help you to choose right framework.
PHPFrameworks
If you want a PHP framework that actually follows the Model View Controll (MVC) pattern then you will need to look at Agavi. Many other frameworks have attempted to implement it but have failed.
Correct me if I am wrong, but this is an MVC approach (Model->View->Controller)?
If so, checkout a framework like CakePHP, they have a pretty good learning zone for you.
You could look at the MVC pattern used in many frameworks for PHP.
You could use frameworks like Kohana, Zend, CakePHP, Yii, which all uses this pattern.
MVC stands for Model-View-Controller, where the model contains the business logic, the view contains the UI, and the controller handles the requests and ties things together.
Symfony (http://www.symfony-project.org/) gets good reviews from my PHP slinging mates
With reference to this post, I am considering starting a new web-based Java project. Since I don't know Spring/Hibernate I was concerned if it's a bad plan to start learning them while creating a new project, especially since it will slow down the early development.
One idea I had was to write a prototype using tech I do know, namely JSP/Servlets/JDBC, since I can get this running much quicker with my current knowledge. I could then throw the whole thing away and start over with Spring, etc, but I'd like to consider how easy it would be to refactor a smallish project from JSP/Servlets/JDB to SpringMVC/Hibernate? My DB could of course be re-used but what about other code... would I expect to save most of it plugged into an MVC framework, or is the paradigm shift big enough this would cause more trouble than it avoids?
Please use the other question for more general advice on choosing technologies
I would advise that you start with Spring and use its JDBC templates and leave Hibernate out of it until you have it working.
Spring will encourage you to use interfaces, which means you'll separate the implementation from the method signatures. You can get everything up and running with Spring and swap out the JDBC DAO for its Hibernate equivalent once you're ready for it.
I can only handle one thing that I'm ignorant of at a time. If you're like that too, follow my advice and start with Spring alone.
+1 to #duffymo's advice. Hibernate is really a whole other beast, and it is especially difficult for folks who are so used to code straight-up SQL to switch to an ORM tool. I mean it took me awhile to be comfortable with Hibernate to do all the work for me, because I just didn't trust it will do a better job than my 'awesome' SQL code. But, as time passes by, I learn to accept that Hibernate is doing a fine job PROVIDED you configured it properly. :)
So, #john, I'll start with JSP + Servlet + Spring first, just like what #duffymo mentioned. Convert your DAO classes to use Spring's JbcTemplate. This forces you to create interfaces for your existing DAO classes. Make sure your DAO classes are stateless, I mean, it should be though. With that, you can easily test the crap out of it in your testcases.
For your servlet to utilize these DAOs, you need to do something like this...
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
SomeDao dao = (SomeDao) ctx.getBean("someDao");
dao.doStuff(..);
The reason for that "tad ugly" code to get the DAO is because Spring cannot wire up the DAO directly into your servlet because Spring doesn't manage your servlet at this point.
Once you get all of this working, you should have some understanding on how Spring's IoC works. Now, you can swap out your servlet and replace it with Spring MVC. I suggest you use Spring MVC 3.x so that you can build your web part the restful way. Trust me, it's whole lot easier and cleaner than Spring MVC 2.x, in my honest opinion.
Okay, when you have JSP + Spring MVC + Spring + JdbcTemplate working, I think it will be a good time to swap your database module from JdbcTemplate to Hibernate. Since you code by interface, it will not cause ripple effects to other modules. PLUS, you can reuse the exact same testcases to test the crap out of your Hibernate DAO classes. Sweeet. :)
... and that's how you end up with JSP + Spring MVC + Spring + Hibernate. :)
Breaking this whole thing down into smaller chunk makes it whole lot easier to learn and digest. At least, when things start breaking in development, you won't indirectly improve your swearing vocabulary, trying to figure out the problems.
I would advice either not using Spring/Hibernate, or using it right away.
Hibernate, but also Spring, influence the modelling of the data and the flow quite a bit. Porting an application from JSP/JDBC to Spring/Hibernate might not always be that easy, especially if you start taking transaction boundaries into account.
My personal advice would be to get a decent Hibernate + Spring book, and start from there.
If you follow good programming practices it will be easy to do the conversion. A servlet could become a controller and a jsp could be re-used as is to become a view. Of course if you are doing things like having business logic in your JSPs it will be more difficult to do the conversion. It will be also good if you already have a data abstraction layer.
This will be an interesting experiment and will help you understand better the advantages of Hibernate and Spring. You may find out that many things these technologies offer, you are doing them already by yourself the hard way.
I'm wondering if anyone has any experience in "isolating" framework objects from each other (Spring, Hibernate, Struts). I'm beginning to see design "problems" where an object from one framework gets used in another object from a different framework. My fear is we're creating tightly coupled objects.
For instance, I have an application where we have a DynaActionForm with several attributes...one of which is a POJO generated by the Hibernate Tools. This POJO gets used everywhere...the JSP populates data to it, the Struts Action sends it down to a Service Layer, the DAO will persist it...ack!
Now, imagine that someone decides to do a little refactoring on that POJO...so that means the JSP, Action, Service, DAO all needs to be updated...which is kind of painful...There has got to be a better way?!
There's a book called Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition)...is this worth a look? I don't believe it touches on any specific frameworks, but it looks like it might give some insight on how to properly layer the application...
Thanks!
For instance, I have an application where we have a DynaActionForm with several attributes...one of which is a POJO generated by the Hibernate Tools. This POJO gets used everywhere...the JSP populates data to it, the Struts Action sends it down to a Service Layer, the DAO will persist it...ack!
To me, there is nothing wrong with having Domain Objects as a "transveral" layer in a web application (after all, you want their state to go from the database to the UI and I don't see the need to map them into intermediate structures):
Now, imagine that someone decides to do a little refactoring on that POJO...so that means the JSP, Action, Service, DAO all needs to be updated...which is kind of painful...There has got to be a better way?!
Sure, you could read "Beans" from the database at the DAO layer level, map them into "Domain Objects" at the service layer and map the Domain Objects into "Value Objects" for the presentation layer and you would have very low coupling. But then you'll realize that:
Adding a column in a database usually means adding some information on the view and vice-versa.
Duplication of objects and mappings are extremely painful to do and to maintain.
And you'll forget this idea.
There's a book called Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition)...is this worth a look? I don't believe it touches on any specific frameworks, but it looks like it might give some insight on how to properly layer the application...
This book was a "showcase" of how to implement (over engineered) applications using the whole J2EE stack (with EJB 2.x) and has somehow always been considered as too complicated (too much patterns). On top of that, it is today clearly outdated. So it is interesting but must be taken with a giant grain of salt.
In other words, I wouldn't recommend that book (at least certainly not as state of the art). Instead, have a look at Real World Java EE Patterns - Rethinking Best Practices (see Chapter 3 - Mapping of the Core J2EE patterns into Java EE) and/or the Spring literature if you are not using Java EE.
First, avoid Struts 1. Having to extend a framework class (like DynaActionForm) is one of the reasons this framework is no longer a good choice.
You don't use spring classes in the usual scenarios. Spring is non-invasive - it just wires your objects. You depend on it only if using some interfaces like ApplicationContextAware, or if you are using the hibernate or jdbc extensions. Using these extensions together with hibernate/jdbc completely fine and it is not an undesired coupling.
Update: If you are forced to work with Struts 1 (honestly, try negotiating for Struts 2, Struts 1 is obsolete!), the usual way to go was to create a copy of the Form class, that contained the exact same fields, but did not extend the framework class. There would be a factory method that takes the form class and returns the simple POJO. This is duplication of code, but I've seen it in practice and is not that bad (compared to the use of Struts 1 :) )
I think your problem is not so big as it seems.
Let's imagine, what can you really change in your POJO:
1) name of its class: any IDE with refactoring support will automatically make all necessary changes for you
2) add some field/method: it almost always means adding new functionality what is always should be done manually and carefully. It usually cause to some changes in your service layer, very seldom in DAO, and usually in your view (jsp).
3) change methods implementation: with good design this should cause any changes in other classes.
That's all, imho.
Make a decision about technology for implementing busyness-logic (EJB or Spring) and use its facilities of dependency injection. Using DI will make different parts of your program communicate to each other through interfaces. It should be enough for reaching necessary (small enough) level of coupling.
It's always nice to keep things clear if you can and separate the layers etc. But don't go overboard. I've seen systems where the developers were so intent on strictly adhering to their adopted patterns and practices that they ended up with a system worse than the imaginary one they were trying to avoid.
The art of good design is understanding the good practices and patterns, knowing when and how to apply them, but also knowing when it's appropriate to break or ignore them.
So take a good look at how you can achieve what you are after, read up on the patterns. Then do a trial on a separate proof of concept or a small part of your system to see your ideas in practice. My experience is that only once you actually put some code in place, do you really see the pros and cons of the idea. Once you have done that, you will be able to make an informed decision about what you will or will not introduce.
Finally, it's possible to build a system which does handle all the issues you are concerned about, but be pragmatic - is each goal you are attempting to reach worth the extra code and APIs you will have to introduce to reach it.
I'd say that Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition) addresses EJB 2.0 concerns, some of which would be considered anti-patterns today. Knowledge is never wasted, but I wouldn't make this my first choice.
The problem is that it's impossible to decouple all the layers. Refactoring the POJO means modifying the problem you're solving, so all the layers DO have to be modified. There's no way around that.
Pure decoupling of layers that have no knowledge of each other requires a lot of duplication, translation, and mapping to occur. Don't fall for the idea that loose coupling means this work goes away.
One thing you can do is have a service layer that's expressed in terms of XML requests and responses. It forces you to map the XML to objects on the service side, but it does decouple the UI from the rest.
I recently added Struts 1.3 to my application on Tomcat. Here are my observations,
MVC. Servlet/JSP does this fine for me, where JSP is the view and servlet is the controller. I don't see any benefit to get the mapping from an XML file since our mapping is very static.
Action Form. I can see some benefits of action form but not huge.
Tags. I already uses JSTL and don't see any advantage using Struts tags.
So I am thinking about removing Struts. Anyone can think of any other benefits I might have missed?
Personally I myself prefer jsp/servlet but theoretically Struts has some advantages.
Here are some of the advantages i know of, you might have mentioned them already, but i thought it would be better if i list all of them here.
Centralized File-Based Configuration.
Struts values/mapping are represented in XML or property files. This loose coupling means that many changes can be made without modifying or recompiling Java code, and that wholesale changes can be made by editing a single file. This approach also lets Java and Web developers focus on their specific tasks (implementing business logic, presenting certain values to clients, etc.) without needing to know about the overall system layout.
Form Beans.
Bean Tags.
Struts provides a set of custom JSP tags that let you easily output the properties of JavaBeans components.
HTML Tags.
Struts provides a set of custom JSP tags to create HTML forms that are associated with JavaBeans components. This bean/form association serves two useful purposes:
It lets you get initial form-field values from Java objects.
It lets you redisplay forms with some or all previously entered values intact.
Form Field Validation.
Struts has a robust, extensible validator that can be used to uniformly validate your form fields. This validation can be performed on the server (in Java), or both on the server and on the client (in JavaScript).
"Plumbing code" contained within the Struts framework.
Mapping HTTP request parameters to Java objects is handled by Struts, for example. You don't have to do it. This allows you to focus more on the domain problem instead of building infrastructure.
Good documentation & plenty of books.
If you have to leave the project and/or someone else has to maintain it then using a well known and well documented framework will make that job much easier. A homebrewed framework just can't match that.
Broad user testing.
Since Struts is used in plenty web-apps the framework will get looked at by many more eyes than anything you could write alone. Usually, but not always, that means any problems you have will have been seen by someone else (and hopefully resolved) first.
Large knowledge base.
I agree that this perhaps isn't as valid as it used to be but Struts has been used in a lot of projects over the years. From a maintainability point of view using a well known framework makes it easier for other people to work on your application and also help build your own resumé for the future. Right now most development is either in the component based space (like JSF, wicket, tapestry) or in the rails-like space (like rails, grails, lift) but the struts arcitechture is still in use and valid.
You didn't say if you develop in a corporate environment or not, for a personal project perhaps the maintainability issue isn't that much of a problem.
If you decide that struts suits you well you could also have a look at stripes, a struts-like framework that's based on the same concepts but is less verbose when it comes to configuration with more sensible defaults, less xml and support for annotations.
I totally agree with your points about Struts - personally I think its time has come and gone.
I went off Struts in v1 (which I believe is nothing like the latest versions) because the form beans where just added boilerplate code to write.
Since then most applications I've worked on are using Spring as the dependency injection framework, which has made Spring MVC the natural choice - it's simple, straight forward and minimal.
Not just for Struts. But some points to consider for using a framework:
Standarization.
Specialized IDE or plugins for your favourite IDE.
Portability. For example, someone can develope a portlet for integrate your existing struts application in a portal server.
Internationalization.
The most important for me:
You dont have to worry about the issues on the struts code, just upgrade.
You can focus your work in business logic.
Struts is Open Source--
Large Community----
Number of Books available-----
Proven FrameWork----
Popular framework-----
Available since 2001----
+----
the features mentioned above...........
but when u r using struts,the better choice is struts2.
I think your feeling about removing Struts is a sound and understandable reaction. Struts just doesn't seem to do very much for an application.