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

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.

Related

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

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.

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Currently doing some exams and I'm struggling through some concepts. These have all been 'mentioned' in my notes really but I didn't really understand how they all linked together. As far as my understanding is:
SOA - a solution to make service consumers/providers communicate. (as far as I understand this is the umbrella term for everything else)
WSDL - A language that describes the provider service.
SOAP - A XML protocol 'wrapper' used by the services to send messages. Works in conjunction with WSDL as to provide parameters?
REST - A design pattern that is similar to SOAP in function but avoids the XML? (really not sure about this one)
JSON - An alternative to XML that uses javascript? (not sure about this one either)
Looking around in the internet there doesn't seem to be a clear definition of what all of these are and how they interlink.
Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.
Web services make functional building-blocks accessible over standard
Internet protocols independent of platforms and programming languages.
So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".
That's where SOAP and REST come in.
They are standard ways you'd pick communicate with the web-service.
SOAP:
SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed.
WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.
REST:
REST is a design concept.
The World Wide Web represents the largest implementation of a system
conforming to the REST architectural style.
It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)
Flickr's REST API goes further and lets you return images as well.
JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.
WSDL: Stands for Web Service Description Language
In SOAP(simple object access protocol), when you use web service and add a web service to your project, your client application(s) doesn't know about web service Functions. Nowadays it's somehow old-fashion and for each kind of different client you have to implement different WSDL files. For example you cannot use same file for .Net and php client.
The WSDL file has some descriptions about web service functions. The type of this file is XML. SOAP is an alternative for REST.
REST: Stands for Representational State Transfer
It is another kind of API service, it is really easy to use for clients. They do not need to have special file extension like WSDL files. The CRUD operation can be implemented by different HTTP Verbs(GET for Reading, POST for Creation, PUT or PATCH for Updating and DELETE for Deleting the desired document) , They are based on HTTP protocol and most of times the response is in JSON or XML format. On the other hand the client application have to exactly call the related HTTP Verb via exact parameters names and types. Due to not having special file for definition, like WSDL, it is a manually job using the endpoint. But it is not a big deal because now we have a lot of plugins for different IDEs to generating the client-side implementation.
SOA: Stands for Service Oriented Architecture
Includes all of the programming with web services concepts and architecture. Imagine that you want to implement a large-scale application. One practice can be having some different services, called micro-services and the whole application mechanism would be calling needed web service at the right time.
Both REST and SOAP web services are kind of SOA.
JSON: Stands for javascript Object Notation
when you serialize an object for javascript the type of object format is JSON.
imagine that you have the human class :
class Human{
string Name;
string Family;
int Age;
}
and you have some instances from this class :
Human h1 = new Human(){
Name='Saman',
Family='Gholami',
Age=26
}
when you serialize the h1 object to JSON the result is :
[h1:{Name:'saman',Family:'Gholami',Age:'26'}, ...]
javascript can evaluate this format by eval() function and make an associative array from this JSON string. This one is different concept in comparison to other concepts I described formerly.

In MVC, can model make use of services to load some data into a list box of a view?

Is it legal In MVC, so that a "model" make use of "services" to load some data ( from web) so that the data after loading can be passed into a list box of a "view" ?
My focus is on "Can Model make use of Services directly for such purposes?"
V.
I agree with Anshu's answer but I'm personally flexible about this kind of thing on my own projects if I plan them to be very small scale, that is it doesn't seem to always be worth the time to create the clear MVC separation. There's also MVVM based on MVC, some decent info on that on wikipedia and you can find it elsewhere http://en.wikipedia.org/wiki/Model_View_ViewModel
There's no set in stone rules when it comes to design pattern usage, but if you set your own rules and work within them (particularly adhering to MVC in one or more layers of abstraction) can be helpful particularly on large projects or where a team is involved.
So the answer to your question about a model making use of services is yes this is possible, is it conforming to a strict MVC pattern, no.
The model should simply be the structure that holds the data in whatever way the data relates to other data, that's what the model is made up of. The controller handles the dirty work of making the calls to the service and updating the model. The view simply is bound to or updated when changes to the model occur and makes use of the controller (usually in as3 by using event handlers on ui components) to make the right updates to the model (or calls to then update the model).
You'll likely have extra helper classes that may sort of fit somewhere in between or outside of the parts that make up the model the view or the controller, this is okay but you should be conscious of what purpose these serve and document them well and make sure it wouldn't make sense for them to somehow be handled more elegantly within the whole setup.
I would say, its rather the responsibility of the Controller to make use of services and populate the model with the data obtained from services.
This link should provide more clarity about the responsibilities of Model, View and controller in Actionscript-3

DRY user-input validation (clientside, serverside) using JSON-schema

As part of a extensive test-case, I'm building an ajax-based CMS-like application which provides CRUD-functionality on various documenttypes, e.g: articles, tags, etc.
on the server and client-side I'm considering to use JSON-schema ( http://json-schema.org/ ) as a way to do user input validation in a DRY way (i.e: 1 validation-schema, to be used both on the server and client-side, no duplicate-code and all that) . This seems great, because:
JSON-schema is both implemented in JS and Java, so one schema could in theory handle client-side and server-side validation
all CUD-operations requests and responses are JSON (through ajax)
However besides the usual validations on user-input I would like to have some additional checks on the server (e.g: like checking if the name of a Tag a user wants to create already exists)
Ideally, I want these type of checks to be included in my general server-side validation code (which as said would be based on JSON-schema). However, I'm not entirely convinced that this is the right approach, because these additional checks are not based on the provided JSON-data alone, but need additional data to validate (e.g: the names of existing tags in the system to check if a tag-name already exists).
So, would it be a good idea (design / architectual wise) to incorporate additional checks like the one described above in the json-schema based validation-framework on the server-side? Would this be an elegant solution? Or would you keep them seperate altogether? If not, why not and what other alternative approached would you suggest to stay DRY concerning client and server-side validation?
What do you think?
Some additional context/ goals of the text-case below for some background info.
Thanks,
Geert-Jan
Some context / goals:
ajax-based CMS using REST approach
CUD-requests are performed through ajax using a rest approach (i.e: mapping on POST, PUT, DELETE respectively). Requests and responses are all done through JSON.
CMS without forms. Instead use in-place editing (e.g using Aloha-editor: http://www.aloha-editor.org/
staying DRY.
templating: done through Mustache templating on client and server-side. Intial rendering and incremental rendering through ajax are done based on 1 and the same template. I wanted to go for something different than Mustache (bc. of it's lack of expressive power), but it works for this prototype at least. (See previous question for alternatives, on which I'm still looking for an answer: Client-side templating language with java compiler as well (DRY templating) )
DRY input-validation: as described above
Validation flow ( in case of failure):
user creates/updates/deletes item.
a validation-failure on the client would instantly give feedback to the user as what to repair. (The Javascript JSON-schema-validator would ideally return JSON which is formatted to the user)
when client-side validation succeeds, the CUD-operation is performed using ajax.
if server-side validation fails, a status-code 400 (Bad request) is returned, with a Json-object containing the validation-failure(s) which is picked up by jquery's error-callback
$.ajax({
....
error: function(xhr, status, error) {
var validationJSON = JSON.parse(xhr.responseText);
//handle server-side validation failure
},
....
});
JSON-object containing server-side validation failures are presented to the user (analogously to client-side)
It is very possible and one of the most gratifying things to have a single definition of validations in one place (per model) on the server that can then generate appropriate JS for client-side and AJAX-based validations.
Yii framework for PHP has a fantastic architecture for accomplishing this in an elegant way that stores all the validation rules together in the model (divvied up into appropriate "scenarios" as needed). From there, it's a matter of flipping a few switches to make a particular form client-side or AJAX-validateable. I believe Yii's interfaces for this were based on Rails.
Anyway I would highly recommend checking out the following key points from Yii's design; even if you don't know PHP, you can use this for inspiration:
CModel::rules() => The DRY source for model validation rules
CActiveForm => Used to generate form elements based on model attributes
See for example CActiveForm::textField()
CValidator => Base class for validators which provisions for the ability to client-validate
I think it's wise to pursue DRY validation rule declaration and in my experience it is not at all unrealistic to achieve that 100% and still have rich forms—and rich validation rules. (And boy will you love life when you don't have to manage all that client-validate JS...)
Hope this helps.

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.