Java EE 6 - JSF Controllers - jsf-2

I'm starting off with Java EE 6 after not touching EE for years (I've been in Spring land for a while).
In JSF 2, am I right in thinking that we don't really have controllers any more. That job is done by managed beans?
If so, is it considered normal practice to then inject a 'Service' class (with CDI) into my managed bean to handle the business logic (and subsequently call DAOs)?
I bought a book (PacktPub's 'EE 6 with Netbeans') and read quite a few tutorials but I'm still a little unclear on how to do it right.
As a bonus question, is there a reference 'PetStore' style app that I can download that shows it all linked together in a best-practices kind of way?
Thanks

In JSF 2, am I right in thinking that we don't really have controllers
any more. That job is done by managed beans?
It depends on how you define the term controller. Some people confuse managed beans with controllers but they rather belong to the model part of MVC or are located "between" model, view and controller (see this great answer by Arjan Tijms to a similar question).
If so, is it considered normal practice to then inject a 'Service'
class (with CDI) into my managed bean to handle the business logic
(and subsequently call DAOs)?
This can be done and is normal practice (I do it in all of my projects). But note, that injection does not always work as expected, so for instance you cannot inject a managed bean into a CDI bean (see my answer to a similar question).
As a bonus question, is there a reference 'PetStore' style app that I
can download that shows it all linked together in a best-practices
kind of way?
You could take a look at the Netbeans tutorials. There you find a lot of information about the topic. A visit to BalusC's blog is also highly recommended.

Related

How can I make a good use of the JSF 2.0 framework?

Currently I have only one controller AppController (SessionScope - ManagedBean) that handles all of the requests and logic of my system, but somehow this doesn't seem right. I want to make this project as modular as possible so it can be very easy to maintain.
I have read a little about Dependency Injection, but I just can't make it work, that is, I don't know what's the issue with the "scope" of the beans. For example, I have my AppController and my Users bean, but I can't make use of the AppController from the Users bean (although I have tried with dependency injection). I think that the logic of the users (edit names, set relationships, etc.) must be handled by the Users bean, but right now those tasks are handled by the AppController, which doesn't seem right.
The issue is, Is there any good tutorial where I can learn how to make a proper use of the JSF 2.0 framework? My objective is to make the AppController as light as possible. I have found several tutorials, but they seem to be more focused on older versions of the JSF or I just don't happen to understand them (maybe they are too technical, I don't know).
Any help with this would be very appreciated.
As to the concrete problem, you shouldn't have a single managed bean which acts as a front controller to handle all requests. JSF's own FacesServlet is supposed to do that. The common consensus is to have a single request/view scoped managed bean per <h:form> you have. And one or two session scoped bean(s) to represent the logged-in user and its settings like locale, if any. You could have an application scoped bean for applicationwide data such as dropdown constants.
As to the concrete question (which is rather subjective and per definition offtopic here, but ala), there is not really a simple tutorial for this. It's a matter of understanding what you're doing and what the code is doing and ultimately using the right tool for the job. In order to learn that, you've to read a self-respected JSF2 book from top to bottom and play a lot around with simple projects. JSF can't be learnt and fully understood in 1 day. It took me years. You can find useful links/references in our JSF wiki page.

Developing webapplications with grails - no idea how it really works

Im really new to Grails and I try to understand how it works. I did some tutorials and wrote a sample application with a mysql database connection. Ive got three tables and therefor three domain-classes and three controller using def scaffold = true. So the views are generated automatically. Now I can add and remove and ... the data in my tables. Thats working.
But now I dont know how to go on. I mean, creating those tables and filling them is nice and its nice that this is possible so fast, but... Now I really want develope an application! Normally I work with Spring Framework, Spring Security, Spring MVC and so on to generate web applications. There, everything is logical. I have the requests comming in, the mapping to controllers, classes which work on the requests, answers given back, jsps rendered.... logical!
In Grails, I dont even know where to start for a real application! All tutorials I find show the same: Setting up those tables and being able to fill them, nice, nice - but after that?
Where do I save the "main.gsp". Do I need a controller for it? How does the application at start up redirect to "main.gsp".
Where can I define the "real logic" - I want to develope something like a "questions with multiple answers - try to select the correct answers"-application. Well, I must admit, I really dont know where to start. And I don't see the use of the Controllers and the possibility to add Data to my tables in my application. Thats for admins but not for users.
Could anyone give me an hint how to go on? Or maybe someone knows a good tutorial which is not about "setting up domain classes, controllers with scaffold, adding data to your database" - I dont see so much sense in it.
Thanks for your help! :-)
[EDIT] Thanks for the answers! Services, that was exactly what I was looking for. I guess I simply must get more familiar with it. The tutorials were just confusing me, but now I understand better!
If you are familiar with Spring and Spring MVC, the concepts in grails should be no surprise to you. Grails actually uses Spring MVC under the covers.
Grails can auto-generate Domain classes, controllers and views as you have tried in tutorials. This is to give you a starting point for your application. This is often enough for those textbook tutorials. For real applications though, you may not always have 1 domain class to 1 controller to 1 set of views. You might not always be doing CRUD operations on that domain. For this, you need to dig a bit deeper into Grails. You can do everything you previously have done in Spring MVC in Grails!
Here are some links to help you get going.
If you are trying to understand the 'flow' better. How requests get mapped to controllers/views, check out the UrlMappings.groovy in your config directory. Docs on that are located here: URLMappings
If you are trying to understand controllers better, check out this: Controllers. Keep in mind that your controller do not need to work on domain models. That is simply the default convention. They work similar to a Spring MVC controller.
Models are simple in Grails. Typically the controllers just return a map of the items you want to return. In Spring MVC, you often create a Model object, most times in Grails you will return something like [name: bean1, name2: bean2]. This allows you to easily get those two beans in the vies.
Start with 'Grails In Action'. The first chapter would give you details about the CRUD Sample app creation , but on reading further you would understand the grails flow better. Services are to be used for the logic, Controllers are used for delegation. You dont need explicit xml mapping as is done in Struts, Spring because everything here works on Convention.
Here is info on controllers: Controllers
Also you can use the same manual to find information on other stuff. For example about where to put business logic you should read in The Service Layer chapter.
Read Beginning Groovy, Grails and Griffon by Vishal Layka, Christopher M. Judd, Joseph Faisal Nusairat and Jim Shingler. They are building a real web application throughout the book with models, database access, authentication, css, templates and layouts, and many other things.

Architecting ASP.net MVC App to use repositories and services

I recently started reading about ASP.net MVC and after getting excited about the concept, i started to migrate all my webform project to MVC but i am having a hard time keeping my controller skinny even after following all the good advices out there (or maybe i just don't get it ... ).
The website i deal with has Articles, Videos, Quotes ... and each of these entities have categories, comments, images that can be associated with it. I am using Linq to sql for database operations and for each of these Entities, i have a Repository, and for each repository, i create a service to be used in the controller.
so i have -
ArticleRepository
ArticleCategoryRepository
ArticleCommentRepository
and the corresponding service
ArticleService
ArticleCategoryService ...
you see the picture.
The problem i have is that i have one controller for article,category and comment because i thought that having ArticleController handle all of that might make sense, but now i have to pass all of the services needed to the Controller constructor. So i would like to know what it is that i am doing wrong. Are my services not designed properly? should i create Bigger service to encapsulate smaller services and use them in my controller? or should i have an articleCategory Controller and an articleComment Controller?
A page viewed by the user is made of all of that, thee article to be viewed,the comments associated with it, a listing of the categories to witch it applies ... how can i efficiently break down the controller to keep it "skinny" and solve my headache?
Thank you!
I hope my question is not too long to be read ...
This is the side effect of following the Single Responsibility Pattern. If each class is designed for only one purpose, then you're going to end up with a lot of classes. This is a good thing. Don't be afraid of it. It will make your life a lot easier in the long run when it comes to swapping out components as well as debugging which components of your system aren't working.
Personally, I prefer putting more of my domain logic in the actual domain entities (e.g. article.AddComment(comment) instead of articleCommentService.AddComment(article, comment)), but your approach is perfectly fine as well.
I think you are headed in the right direction. The question is how to instantiate your services? I'm no MVC.NET guru, but have done plenty of service oriented Java projects and exactly the pattern you are discussing.
In Java land we would usually use Spring to inject singleton beans.
1) You can do the same thing in .NET, using dependency injection frameworks.
2) You can instantiate services as needed in the method, if they are lightweight enough.
3) You can create static service members in each controller as long as you write them to be threadsafe, to reduce object churn. This is the approach I use in many cases.
4) You can even create a simple, global service factory that all controllers access, which could simply be a class of singletons.
Do some Googling on .NET dependency injection as well.

What is the breakdown of all of the layers required/recommended for an Asp.Net Mvc Application following best programming practices?

The more I read into Asp.Net MVC the more layers and components I find out are required in order to make my application follow all of the standards and best programming practices.
It's starting to get a bit confusing because some of the new layers don't seem to fit in as easily as the others I learnt. So I just wanted someone to go over all of the required/recommended layers for an Asp.Net MVC application- what purpose they serve and how they interact with the other layers.
Here's a few of the layers I've found and how they link up:
(Some of them may be wrong)
View/UI --> Model Binder --> Controller --> Service Layer --> Repository --> Entity Framework/LINQ to SQL --> DB
Could someone go over ones I may be missing, how they all link up, and what each of their purposes are?
Thanks,
Matt
Good question, I think you covered all the layers I have seen: Modal binder and service layer are optional.
Maybe, you can add another Error Handling layer such as elmah.
View/UI --> You put your html markup / Javascript code.
Model Binder --> You perform the magic to bind your input to the action parameters, normally, you will use the default binder, so you don't need worry about it. However, you can override this with your own binder, and do validation in this layer. Here is a good example on this.
Controller --> Enough documentation online.
Service Layer --> A lot of people do validation and other business logic processing here before sending it to repository. Asp.net mvc contact manger example has a good example here. This is also the layer to actually work with your modal.
Repository --> Simple read/write operation.
Entity Framework/LINQ to SQL --> DB - Actually writing to database. Nhibernate is another good candidate here.
First of all, I think software and patterns have a tendency to overcomplicate things. As the ASP name implies the main idea of the framework is Model-View-Controller (MVC). You could be able to put a lot of things between these components, including DBs, Services, APIs, etc. However, the main concept of the Model-View-Controller pattern is pretty simple: Separate those functionalities into modules so the project could be easier to mantain.
MVC could be applied to ANY programming or scripting you do. Even for a shell script MVC could be helpfull. Here are some examples of each one:
View - Here is how the user interacts. It could be a web page, and Windows Form, or a command line interface.
Controller - The brains of the program, it should be aware of everything, but should be pretty simple. It basically gets messages or events from the view and/or model and decides on what to do. Good controllers are basically a dispatcher of events. Depending on events, it call view or model methods. In ASP MVC, the controller is the one providing the ActionResults for the View and interacts with the Model.
Model - This is basically where the data is. This could be a DB, file system, a Web Session, or memory.
Now the good part. The Controller does not care how the View is managing the interaction with the user. It could be a command line interface or a web form. The Controller does not know how the data is stored, it does not matters if it is a DB or a file. It just request data and pass it to the View. It not of its business to know how the view is getting the inputs, or the model the data.
Then the question, Why the hell do we want to overcomplicate things with this pattern? Well, Imagine that you have an MVC application using a MySQL DB and know you want to use SQL Server. What module you should change? Obviously the Model is the one affected. The Controller and the View should not have any major impacts. Now, imagine that you have another MVC application using Windows Forms, and now you want to change it to Web Forms? Well basically the View is the one that will be affected (and some parts of the controller), but your Model should be the same.
In summary, MVC is a great pattern, and it should be used more. However, I think there are some projects which are not suitable for MVC due its simplicity. It will be like building a laser to kill flies. Of course you will kill them, but the effort is not worthy on all cases.

Asp.net Mvc: Creating Model Classes with LINQ to SQL

I am trying to learn Asp.net Mvc so I am trying out
this Tutorial.
They talk about the Repository Pattern and how it is easy to change to another data access technology instead of just calling Linq to Sql directly.
Using LINQ to SQL within a controller class makes it difficult to switch data access technologies in the future. For example, you might decide to switch from using Microsoft LINQ to SQL to using the Microsoft Entity Framework as your data access technology. In that case, you would need to rewrite every controller that accesses the database within your application.
Note: I never really understood how an interface worked before reading this tutorial and it's still not 100% clear. I see it now as some sort of 'template' for a class.
After successfully using Linq to Sql I thought it would be nice to try out Ado.net Entity Framework since I've been reading a lot about this. They said using the Repository Pattern would make it easy to switch so I thought I would test that.
My question is: what should I do to change to Ado.net EF?
This is what I think I should do.
Add the Movie.edmx file and configure it(add my movie table).
Write a new class based on the IMovieRepository and maybe call it MovieEFRepository.
Change the parameter in the controller constructor to MovieEFRepository. This is the first thing I find strange because in the tutorial they say that not using the repository will force you to change all the controllers if you change to an other datasource. Don't I need to change every controller anyway since I am specifying the MovieRepository class?
The last adjustment I think I need to do is to change the View. Because it's using the Product class which was created by the Linq to Sql designer. I am not sure how I am going to do this. I guess I should have used some object that wasn't dependent on the dbml file?
Forgive me if I have a slightly simplistic view of Asp.net Mvc. I am webdesigner with a lot of interest for Asp.net webdevelopment.
So after a few days of reading and a lot of googling I got it to work. First I tried to find out what IoC (Inversion of Control) actually meant.
One of the first sites I found was a website with a screencast about Unity. Which is a DI/IoC framework for .Net.
Link: David Hayden screencast on Unity.
Looking at it now this is actually a very good screencast and example on how easy it is to use Unity and IoC/DI. At the time I didn't understand it completely so I went on and kept googling.
One website I kept running into was the one from Martin Fowler.
Link: Martin Fowler - IoC Container and the DI pattern
For me, a person that is a coding novice this website is a little to abstract. Also this might sound weird but the font, line-height and typography on that website was really awful which made it even harder to read.
The next website I read was about Windsor Castle since Alfredo Fernández said it was easy to use.
Link: Castle Project- Windsor Container
The documentation wasn't to bad but I had some problems converting their "getting started" basic example to my Asp.net Mvc application. Also part 2 and 3 were missing from their getting started.
After this I started looking for the different frameworks to see if i could find a really basic example. If I just looked at the first screencast again I would have fixed it a lot sooner but somehow I lost track of it.
Link: Scott Hanselman: List of .NET DI Containers(IOC): very good blog post with most of the .NET IOC solutions.
Link: Phil Haack: TTD and DI using Structure Map: Using the xml configuration file was to complicated for me and i couldn't get it to work.
Link:
Andre Loker: ASPNET-MVC-with-Windsor-programmatic-controller-registration: Didn't try this example. Looking at it now I might have been able to get it to work.
Link: MvcContrib: This adds functionality to Asp.net Mvc. It also has 3 or 4 IOC ControllerFactories build in. I couldn't get it to work I also didn't find a lot of documentation about this.
I had a lot of problems with xml configuration files and I couldn't seem to get them to work. I tried Windsor, Structure Map and Spring.net but I always got stuck with the xml files.
So I decided to go to the Asp.net Mvc site because that's where I started learning about Asp.net Mvc. I found the first screencasts and MIX09 presentations very clear and I understood most of what people were talking about. I got stuck at the second screencast by Rob Conery when building the Storefront application. Because I knew a little more about repository and IOC/DI now I thought it would a be a good idea to start watching Rob Conery's screencasts again. In one of the screencasts he talks about uploading all the samples to codeplex.
Link: Codeplex: Mvc sample apps
I went to codeplex and found out you can browse through the source files without downloading them. I tried to find out how Rob Conery handles IOC/DI with his repositories. So I was glad to see he was using Structure Map but instead of using a xml configuration file he was using a bootstrapper class that registers all the interfaces to their concrete class.
After trying this with my webapplication I finaly was able to get Structure Map to work in my application (Hooray).
He also showed me how to fix the dependency on my Product class that comes from Linq to Sql. He creates an extra object that then gets called by "select new product { }" in the Linq queries.
Wow, this answer is a little longer than I planned but I hope this helps other people like me who are very novice in coding and Asp.net Mvc.
You might have your repository decoupled because of injection, not if you followed just the examples because of
public MoviesController() : this(new **MovieRepository**())
I recomend you to read about IOC, is easy and very interesting, you can use and ioc container like castle windsor.
With that, your contoller will have only one constructor, the one with the interface, and not will need to be changed.
With your entities you can do the same that with the controllers, create an interface for each entity and use the ioc pattern too, with tha you will only have to change your configuration file for your ioc container.
If you don't do these things, your right, you will need to change all you said.
I hope that help! sorry about my english!

Resources