Project structure to use jquery ajax in spring mvc using json data in eclipse - json

I am new to spring mvc. I have a lot of doubts to be cleared before i can continue.
I want to create a simple application wherein an employee details such as name age phone etc is entered and through ajax call the form data has to be to sent to server using json. For server side i am using spring. And the submitted data has to be shown in a jquery data table. And again to retrieve data an ajax call has to be used to get the data as a json. And no binding tool like jackson should be used.
1.) how do i go about creating an application in eclipse. If i should do a simpel java project or a dynamic web project?
2.) Could any one pls provide a sample code of each of the steps.
Thank you in advance

First, I think it's easier to start with Maven, create a WAR project, and use that to generate the Eclipse project files, which you can then import. This has the advantage of allowing Maven to not only create the correct folder structure, but also let it manage your dependencies. There are plugins for Eclipse that help you work with Maven, and you should be able to find lots of How-Tos using Google. Otherwise, you would have to create a project type that generates the WAR, one of which I believe is a Web Project, and layout the folder structure manually.
After you have the proper folder layout, you will need to setup your web.xml to enable Spring, add your Java classes and view files (html, jsps, whatever), and build a WAR. The final step would be to deploy that WAR to a web container of some sort, like maybe Tomcat or Jetty. You can ether run it externally, or configure Eclipse to deploy and launch your WAR in the IDE directly. I prefer the latter approach, as it makes it easier to setup debugging, not that running it external makes it impossible.
In addition, I would recommend adding the Spring pluggins to Eclipse, or just download their STS (Spring Tool Suite), which is just Eclipse with all the Spring plugins already added and configured. STS has the bonus of already having tcServer available, which is Spring Source's flavor of Tomcat. Again, loads of how-tos available on how to do all of this.
Edit to answer first comment
I don't know if I can address your comment here fully, as it's a very broad request. You are basically asking how do I write a full application using jQuery and Spring MVC. The volumes of books dedicated to this subject, as well as many websites you could visit that give tutorials on how to start developing. In fact, I think the Spring website has a tutorial for building their demo Pet Clinic site using Spring MVC. What I will try to do is give you some direction on what you should be asking.
Spring MVC, as the name suggests, is a Model-View-Controller framework that leverages the Spring Framework. I will not attempt to go into any great detail, as again there are volumes of books out there on the subject of Spring and all its wonders, but in general Spring MVC wants an application broken into the following chunks:
1. The Model
These are the objects you are using to represent your "data". This can be data from a Database, flat file, some other web service call, or maybe just passed around in your Controller. You will hear them commonly referred to as domain objects or entities to name a few. But, no matter how you refer to them they are typically POJO (Plain Old Java Objects) Java Beans with no real business logic, who's only existence is to represent some "data" and how it relates to other "data".
Some people prefer to have this object know how to read/write itself to its data store, some people like to have an external object that is only used to handle the read/writes. These are sometime referred to as a DAO (Data Access Object) or a Repository. There are also frameworks you can use for dealing with this stuff, like Hibernate or JPA for databases.
2. The Service Layer
This isn't represented in the MVC acronym, and one might argue this is part of the "Controller", but it's usually a good idea to put your business logic into a service layer. This is typically a POJO class that has methods to do the things you need to do with your Model objects. It houses your business logic so all the business rules are in one place. These are usually split to represent business functions. For instance, if you had an application dealing with car purchases you might have one service class to deal with the User related functions (create a user, update a password, get his preferences), one to deal with inventory (what is in stock, what is on its way, what is the current sales price), and one to deal with making a purchase (validate the customer's credit, start the tag process, etc). Its also common for these services to have reference to each other. For instance, the User service above might use the Inventory service to get a list of VIN numbers for cars Bill sold last week.
3. The Controller
The controller is what glues the "view" to the service layer. It provides the mapping of the URLs in your app to the function(s) they perform in the service layer. Most people try not to clutter the Controller object with too much code, and try to push as much down into the Service layer as they can. But, as long as it's simple logic I personally don't mind having a tad bit of code in the Controller.
4. The View
This is what you are sending to the user. It may be a web page backed by a JSP. It may be an Excel spreadsheet report generated from user input. It may be a simple JSON response to a REST call. It's sort of "the sky's the limit" here. But, for the most part this is either a JSP view or a JSON or XML response from a web service call.
Now to address your comment more directly...
Since you are a novice, I would recommend one of 3 approaches:
Go get a book...do what the book says to do. There are tons out there. Find one that has a good walk-through of a project, and copy/paste their procedures. A good book will usually have a chapter on how to setup all the necessary tools (Eclipse, Tomcat/Jetty, etc)
Find a good how-to on the Internet. There are lots of people that have tutorials. Find one and copy/paste their procedures.
Use something like Spring Roo. Spring Roo is a code generation tool that can be used to build a fully working site with little to no code. I am a big fan of Roo, especially for lone developers not working in a team, as it can generate a TON of the boiler plate code most developers hate to write. It also does things in a very Spring-like fashion, since after all it was created by the Spring folks.
These will get you past the "how do I create the project in Eclipse" problem. Part 2 of question one is a little more tricky. I would say, for now, don't focus on AJAX and stuff. Focus on simply understanding how Spring MVC works. The problem is, you are basically trying to cram 10 things down at once. Spring MVC is hard enough to get your head wrapped around (the annotations, JSTL, EL, and the Spring custom tag libraries, not to mention all the other things you will probably be touching like Spring Data, etc), but then you want to add dynamic web pages, which is JavaScript (and most likely some framework like jQuery), and to cap it off you don't want to use anything like Jackson (not sure why, but ok...) to help ease the transition from Java to JavaScript. That's a tall order. Again, I would cut out AJAX/JavaScript stuff at first, get a good handle on how a SIMPLE application is built, and then you can jump into all the dynamic stuff.
For the last question, providing code samples, I would point you to mkyong's fantastic blog full of Spring-related tutorials as well as Spring's own Tutorial site and Spring's Sample site as a good starting point.

Related

Why present view with servlet if we can do it with jsp?

It seems that both can represent a view, that is if you request a servlet it will show you an html page, and so the same if you request a jsp file, just the way they are implemented are different.
Now I know that servlet are more than, that. They control requests and so on, but still after reading so many days, still don't know how to use them in harmony together.
If i need some logic, do I put it in a servlet, and then what? How do I present my data, from the servlet or from a jsp file located in the same folder?
In other words, do I even need jsp files when I use servlet, and if yeas why???
It seems that both can represent a view, ...
JSP was introduced because it's much easier to invoke Java to render parts that are dynamic in an otherwise static HTML template rather than trying to print out the whole page in Java through servlets (too many println(), escaping quotes etc. it's a mess). So, JSP is better suited for rendering views.
MVC is all about separation of concerns: request handling and routing, business logic and application data, and the views with all the presentation logic.
JSPs later enhanced with EL (Expression Language), JSTL (Java Standard Tag Lbrary) and other such tag libraries that encapsulate the presentation logic are better suited to support the View layer.
Model represents your application data and all the business rules that you apply on them. They're implemented as POJOs (plain old Java objects i.e. not extending or implementing platform specific classes or interfaces) .
Servlets and Filters with their request dispatching capabilities and inherently existing in the Java environment are better suited as Controllers to interact with the Application Server, the Model and the View. They facilitate all the routing and the flow of data between the three layers.
If i need some logic, do I put it in a servlet, and then what?
Your business logic neither goes in Servlets nor JSPs. That goes into your business classes (POJOs) insulated as much as possible from the type of application platform (which is J2EE here).
A simple request to demonstrate its use would be to ask you to port your application into .Net. A-ha! Suddenly, writing all that business logic inside your Servlets/JSPs, that cannot be easily reused now, doesn't feel like such a good idea.
So, ideally, your servlets would intercept the client requests and invoke some business class to fulfill it. This may return some data (like results from a SQL query) wrapped as a domain data object (also referred to as data value or data transfer objects).
How do I present my data, from the servlet or from a jsp file located in the same folder?
Before redirecting to an appropriate View, the Controller servlet would push the domain object into some scope (could be request, session or application depending on the requirements) or a sophisticated data store available with an MVC framework (like the ValueStack in Struts 2).
The View, which is your JSP, would then pull the domain object from one of these scopes or ValueStack and render its required properties for display through EL with JSTL tags or OGNL expressions with tag libraries provided by the MVC framework.
It is of good style to separate logic from presentation. (1) You can easily change the logic not touching the presentation and vice versa. (2) You can use a right tool for each task. Pure Java in servlet's code is good for implementing logic. Templating engine, including JSP, is good for presentation, where your work is largely in HTML with some points where you're inserting data from the application.
You can read about Spring as an example how to use JSP in the best way.

Generating RESTful controllers without full scaffolding

I want the Roo-generated JSON controller stuff. I don't want the full HTML scaffolding stuff.
As far as I can see, I can only generate the former as an aspect on the latter. Is it possible to generate them separately? I have a whole set of view controllers I'm writing of my own. Is there an annotation I can put on my controller to have Roo give me REST functions?
I figured it out.
The annotation #RooWebScaffold is the answer. I can't find a roo command to install those, but putting that annotation on my classes makes it generate the web scaffolding for the REST interface.
EDIT: Actually that completely doesn't answer my question. It DOES generate the REST access code, but it ALSO generates all the web scaffolding stuff. I've submitted a ticket on the JIRA for this feature.

Question about Domain Objects, A Service Layer, and Using Linq2SQL and ASP.net MVC with the Repository Pattern

First off, apologies for the long description of my brainspace below. I'm still wrapping my head around lots of these new ideas, so I'm sure I'm describing something incorrectly. Please feel free to correct me where I'm wrong.
We are in the R&D phase of a new ASP.net MVC2 site and want to ensure that we can 1) decouple our data store from our application, 2) allow for our application to be tested via unit tests and 3) allow us to change out our datastore or use something other than Linq2SQL down the line.
This seemingly simple goal has opened up a whole new world to me that includes the Repository pattern, IoC, DI, and all sorts of other things that are making my head swim. Here's what is so far coming into focus, or at least what I believe is a somewhat correct plan to reach our goals:
We will have a number of ISpecificRepository interfaces that define the contract between users of the interface and the underlying data store.
The SpecificRepository implementations will query specific datastores and return POCO representing our domain objects (or collections of them).
Our Service Layer will perform the application specific business logic using an instance of ISpecificRepository passed to the various service methods and pass these POCO domain objects back to our presentation layer.
As mentioned, we are planning on using Linq2SQL to implement our specific repositories for the application and have decided to decouple our service layer from this implementation by creating the POCO for our domain objects and create a mapping to and from these objects to the LINQ generated entities. In the service layer, we can then create business logic to query the repository, add data, and do whatever else we need to do for each use case. This seems fine but my concern is that since we're using Linq2SQL, our specific Linq repository implementation will now have to house all of the many Get queries that the service layer requires to implement the business logic efficiently.
I'm curious as to whether this somehow breaks the Repository pattern since we're now housing application specific logic not in the service layer but in the repository instead.
The reason I feel that we need to do it this way is so that I can write more efficient Linq queries on my specific Linq repository using various DataLoadOptions, etc. without returning IQueryable from my repository up to my service layer, where it would seem that sort of logic actually belongs. Also, all of the example IRepository interfaces I've seen seem very lightweight and only provide a few methods to GetByID, GetAll, Find, Insert, Delete, and SubmitChanges to the underlying data store. In my case, it sounds like my specific repositories will be doing a great deal more than that.
Thanks for reading this far. Any and all help that can clarify my misconceptions would be greatly appreciated.
-Mustafa
our specific Linq repository
implementation will now have to house
all of the many Get queries that the
service layer requires to implement
the business logic efficiently.
I'm curious as to whether this somehow
breaks the Repository pattern
Not at all. A Repository is a collection of domain entities. If I have a Repository of Accounts, it is perfectly reasonable to want Accounts.ThatAreOverdue().
I personally prefer fluent naming. Accounts.ThatAreOverdue() feels better than AccountRepository.GetOverdue() .. but I suppose that is a point of preference.
Also, all of the example IRepository
interfaces I've seen seem very
lightweight and only provide a few
methods to GetByID, GetAll, Find,
Insert, Delete, and SubmitChanges to
the underlying data store.
A Repository interface can be thin. Find is meant to be used with the Specification pattern. Encapsulate the criteria in another object. The implementation of the criteria can be passed Linq2Sql objects from which to query - but it will be more difficult to re-use the criteria classes against in-memory domain objects (versus in database, where Linq2Sql is involved).
Our Service Layer will perform the
application specific business logic
using an instance of
ISpecificRepository passed to the
various service methods and pass these
POCO domain objects back to our
presentation layer.
Are you saying that your logic will all be in Services and the "domain objects" will be bags of properties and bound to in the view?
I don't think I'd recommend that.
If the same object that is used in the application logic is also used in the view, then you have tightly coupled the two application layers and experience says that causes problems. It will be very difficult to maintain coherence in the Services and Domain through changes if the View uses the same objects. The View will need pieces of data and they will inevitably get stuck onto places they don't really belong in the domain.

Migrating from LINQ to SQL to Entity Framework 4.0 - Tips, Documentation, etc

I tried out EF back in .NET 3.5 SP1, and I was one of the many who got frustrated and decided to learn LINQ to SQL instead. Now that I know EF is the "chosen" path forward, plus EF 4.0 has some exciting new features, I'd like to migrate my app to EF 4.0.
Can anyone suggest any good resources that are specifically targeted towards 4.0 and L2S migration? NOTE: I can find plenty of blogs and articles related to migrating from L2S to EF on .NET 3.5, but I feel like many of those were obviously dated and unhelpful to someone using 4.0.
I'd really like as much deep, under-the-hood stuff as I can get; I want to really come away feeling like I know EF 4.0 the way I currently know L2S 3.5.
TIA!
I have done loads of this very type of conversion and FWIW, I would say there are more similarities than differences. I don't think there is any definitive documentation that will make you feel like an expert in EF4, beyond the stuff that is already out there...
http://msdn.microsoft.com/en-us/library/ex6y04yf(VS.100).aspx
What I can give you are the more obvious "gotchas." Specifically, Linq2Sql wanted to combine the business layer and the data layer a lot more obviously. It really pushed you to create your own partial classes. I could go on and on about way, but the most specific reason is the way the one-to-one mapper will create public parent and child properties for all relations.
If you attempt to use any type of serialization against this model, you will like run into circular reference problems as a serializer moves from a parent to a child and then back to the parent as the Linq2Sql serialization behavior automatically includes all children in the graph. This can also be really annoying when you try to grab a customer record to check the "Name" property and automatically get all the related order records included in the graph. You can set these parent and child navigation properties to be either "public" or "internal" which means if you want access to them, but don't want the serializers to automatically create circular references, you pretty much have to access them in partial classes.
Once you start down the partial class path you generally just continue the pattern and eventually will start to add helper methods for accessing your data into your individual entity classes. Also, with the Linq2Sql DataContext being more lightweight, you often find people using some kind of Singleton pattern or Repository pattern for their context. You don't see this as much at all with EF 3.5 / 4.
So let's say you have some environment similar to the one described and you want to start converting. Well, you need to find out when your DataContext is going to be create/destroyed...some people will just start each Business Layer method with a using() statement and let the context pretty much live for the lifetime of the method. Obviously this means you can get into some hairy situations that require adding .ToList() or some other extension method to the ends of your questions you can have a fully in-memory collection of your objects to pass to a child method or whatever and even then you can have problems with attempting to update entities on a context that they weren't originally retrieved from.
You'll also need to figure out how to much of the BusinessLogic incorporated in your Linq2Sql partial classes out into another layer if it doesn't deal explicitly with the data operations. This will not be painless as you figure out when you need/don't need your context, but it is for the best..
Next, you will want to deal with the object graph situation. Because of the difference in the way lazy-loading works (they made this configurable in EF 4.0 to make it behave more like Linq2Sql for those who wanted it) you will probably need to check any implied uses of child objects in the graph from your Linq2Sql implementation and verify that it doesn't now require an explicit .Include() or a .Load() to get the child objects in the graph.
Finally, you will need to decide on a serialization solution in general. By default, the DataContracts and DataMember attributes that are generated as part of an EF model work great with WCF, but not at all great with the XmlSerializer used for things like old .asmx WebServices. Even in this circumstance you might be able to get away with it if you never need to serialize child objects over the wire. Since that usually isn't the case, you are going to want to move to WCF if you have a more SOA, which will add a whole new host of opportunies, yet headaches.
In order to deal with the partial classes situation, and the hefty DataContext and even the serialization issues, there are a number of new code-generation templates available with EF 4.0. The POCO-Entity template has a lot of people excited as it creates POCO classes, just as you'd expect (the trouble is that excludes any class or member attributes for WCF etc etc). Also, the Self-Tracking Entities model pretty much solves the context issue, because you can pass your entities around and let them remember when and how they were updated, so you can create/dispose your contexts much more freely (like Linq2Sql). As another bonus, this template is the go-to template for WCF or anything that builds on WCF like RIA Services or WCF Data Services, so they have the [DataContract], [DataMember], and [KnownType] attributes already figured out.
Here is a link to the POCO template (not included out of the box):
(EDIT: I cannot post two hyperlinks, so just visit the visualstudio gallery website and search for "ADO.NET C# POCO Entity Generator")
Be sure to read the link on the ADO.net team blog about implementing this. You might like the bit about splitting your context and your entities into separate projects/assemblies if you fall into the WebService vs. WCF Service category. The "Add Service Reference..." proxy generation doesn't do namespaces the same way "Add Web Reference..." used to, so you might like to actually reference your entity class assembly in your client app so you can "exclude types from reference libraries" or whatever on your service references so you don't get a lot of ambiguous references from multiple services which use the same EF model and expose those entities...
I know this is long and rambling, but these little gotchas were waaay more of an issue for me than remembering to use context.EntityCollection.AddObject() instead of context.EntityCollection.InsertOnSubmit() and context.SaveChanges() instead of context.SubmitChanges()...
For EF Code First, it's mostly about reverse engineering the existing tables into EF classes. EF Power Tools now does this for you:
http://msdn.microsoft.com/en-us/data/jj200620.aspx
The rest is the obvious work of modifying your existing code to use those generated classes to talk to the database instead of LINQ to SQL.

Testing and mocking with Flex

I am developing a "dumb" front-end, it's an AIR application that interacts with a "smart" LiveCycle server. There are currently about 20 request & response pairs for the application. For many reasons (testing, developing outside the corporate network, etc), we have several XML files of fake data, and if a certain configuration flag is set, the files are loaded, a specific file is parsed and used to create a mock response. Each XML file is a set of responses for different situation, all internally consistent. We currently have about 10 XML files, each corresponding to different situation we can run into. This is probably going to grow to 30-50 XML files.
The current system was developed by me during one of those 90-hour-week release cycles, when we were under duress because LiveCycle was down again and we had a deadline to meet. Most of the minor crap has been cleaned up.
The fake data is in an object called FakeData, with properties like customerType1:XML, customerType2:XML, overdueCustomer1:XML, etc. Then in the FakeData constructor, all of the properties are set like this:
customerType1:XML = FileUtil.loadXML(File.applicationDirectory.resolvePath("fakeData/customerType1.xml");
And whenever you need some fake data (this happens in special FakeDelegates that extend the real LiveCycle Delegates), you get it from an instance of FakeData.
This is awful, for many reasons, but it works. One embarrassing part is that every time you create an instance of FakeData, it reloads all the XML files.
I'm trying to figure out if there's a design pattern that is not Singleton that can handle this more elegantly. The constraints are:
No global instances can be required (currently, all the code dealing with the fake data, including the fake delegates, is pulled out of production builds without any side-effects, and it needs to stay that way). This puts the Factory pattern out of the running.
It can handle multiple objects using the XML data without performance issues.
The XML files are read centrally so that the other code doesn't have to know where the XML files are, and so some preprocessing can be done (like creating a map of certain tag values and the associated XML file).
Design patterns, or other architecture suggestions, would be greatly appreciated.
Take a look at ASMock which was developed by a good friend of mine (and a member here Richard Szalay) and is based on .nets Rhino mocks. We've used it in several production environments now so i can vouch for it's stability.
should be able to get rid of any fake tests (more like integration tests) by using the mock object instead.
Wouldn't it make more sense to do traditional mocking with a mocking framework? Depending on your implementation, it might be possible to set up the Expects by reading the fake-data XML files.
Here is a Google Code project that offers mocking for ActionScript.