Working of MVC architecture for Servlets - java

So, yeah, this is what I understood.
Servlet is just an intermediary responsible for finding out what the parameters in the request mean. These parameters are given to the .java file. It is a mere intermediary
.java file is the Model which does business logic
View is the JSP that will do the presentation
Did I get that right?

The Model View Controller pattern is not specific to Java or Servlet technology. There are many non-java MVC implementations, and in Java, there are non-Servlet implementations (Swing is an example).
In Java, when using Servlet-based MVC, usually an MVC framework is used. There are two main categories here: action based and component based, the difference being that action based frameworks listen each registered URL independently while component based frameworks keep a component tree and maintain server-side state.
Action based frameworks are Spring MVC, Struts 1+2, Stripes, Play etc. Component based frameworks are Wicket, JSF 1 & 2, Tapestry etc.
Your diagram gets close to the truth, but there are a few subtle misconceptions.
First, it doesn't make sense to speak of .java files. Java source files are totally irrelevant to a deployed web application, it uses compiled .class files only, and the JavaVM can be programmed in many different languages, so the application doesn't care whether the .class files were compiled from Java, Scala, Groovy, JRuby, Clojure, AspectJ or anything else as long as they comply to the Java Class File specification.
Second, while JSP has long been the default view technology in Java Servlet technology, it's far from the only one. Other technologies include Facelets, Velocity, Freemarker etc., and there's also nothing to stop you from writing data directly to a request from a controller without a dedicated view technology (although this is usually not advisable).
Basically, what MVC stands for is a system where there is separate code for business logic (the M), the view technology (V) and the Controller that ties things together. In a well-organized MVC architecture, the M part is so well encapsulated that the same business logic can also be executed through other channels (e.g. web services, direct library access etc.). Also, it should be possible to switch view technologies through configuration from the outside without editing the actual controller logic.
I would advise you to read the docs for the Spring MVC framework, it is to my knowledge the most robust (and also easy-to-use) MVC framework out there, and the tooling support is also great (in either InteliJ Idea or the Eclipse-based SpringSource Tool Suite).

When you are talking about MVC, then all three layers should be separated from each other.
In web application :
1: A controller should be responsible handling the user request then filtering & executing the appropriate actions and then forward the generated response to the client.
2: A model consist of your Business logic,beans & Pojo classes. This should deal with you logic ,perform some operation and renders the generated result to some kind of persistent object or DTO's.
3: A view is consist of your GUI, some presentation-logic , it should be separated from your back-end ,ultimately you are showing an encapsulated form of result to your client i.e. what a client actually needed.
There are two types of MVC: MVC1(Push-MVC) and MVC2(Pull-MVC)
Pull-MVC and Push-MVC are better understood with how the view layer is getting data i.e. Model to render. In case of Push-MVC the data( Model) is constructed and given to the view layer by the Controllers by putting it in the scoped variables like request or session. Typical example is Spring MVC and Struts1. Pull-MVC on the other hand puts the model data typically constructed in Controllers are kept in a common place i.e. in actions, which then gets rendered by view layer. Struts2 is a Pull-MVC based architecture, in which all data is stored in Value Stack and retrieved by view layer for rendering.

Related

When to use Servlet or #Controller

I need to get a few things cleared up. I have been looking for an answer for this one, but I can't seem to find a good answer to my specific questions (eg. this question was nibbling on the answer: Difference between servlet and web service).
To my understanding, there are different ways you can implement the "request handling", aka "Controller", in an "MVC oriented" web application, two of them being:
A Java specific Servlet (ie. one you create by clicking new ->
Servlet, in eclipse for example), used as a "Controller". This one
extends HttpServlet and you use methods like doGet and doPost etc.
A Spring MVC annotated #Controller class (yes, using a DispatcherServlet). With this one you use the #RequestMethod GET/POST etc.
Now to my questions...
When do you use one or the other?
Are there any general advantages to use one method over the other? (Like, is one method recommended over the other in general?)
[EDIT]: Emphasized keywords
If you're a student interested in learning the language then I would stick with servlets for now. It's possible to write a web app using just servlets but in practice you'll probably want to look at JSP's too.
A JSP is a convenient way to write a servlet that allows you to mix html with scripting elements (although it's recommended to avoid Java code in your jsp in favour of tags and el expressions). Under the covers it will be compiled as a servlet but it avoids you having to use lots of messy print statements.
It's important to have at least a basic understanding of servlets and JSP's. Spring MVC is one of many frameworks built on top of servlets to try make the task of writing a web application a bit easier. Basically all requests are mapped to the DispatcherServlet which acts as a front controller.
The DispatcherServlet will then call the controller whose annotations match the incoming request. This is neater than having to write these mappings yourself in the web.xml (although with servlet 3.0 you can annotate servlets now). But you also get many other benefits that can be used like mapping form fields to an object, validating that object with jsr303 annotations, map inputs and outputs to xml or json etc etc. Plus it's tightly integrated with core spring so you can easily wire in your services for the controller to call.
It's worth noting that there are a plethora of competing frameworks built on top of servlets. Spring MVC is one of the most popular so it's not a bad choice to look into.
A Servlet and a Spring MVC Controller can be used to do the same thing but they act on different level of a Java Application
The servlet is a part of the J2EE framework and every Java application server (Tomcat, Jetty, etc) is built for running servlets. Servlet are the "low level" layer in the J2EE stack. You don't need a servlet.jar to run you application because it's prepackaged with the application server
A Spring MVC controller is a library built upon the servlet to make things easier. Spring MVC offers more built-in functionalities such as form parameter to controller method parameter mapping, easier handling of binary form submissions (i.e. when your form can upload files). You need to package the required jars to your application in order to run a Spring MVC Controller
You should use a servlet when you need to go "low level", and example could be for performance reason. Spring MVC performs good but if it has some overhead, if you need to squeeze out all you can from your application server (and you have already tuned the other layers such as the db) go with a servlet. You can choose a servlet if you want to understand the foundation of the J2EE web specifications (i.e. for educational purposes)
In all the other cases you can/should choose a web framework. Spring MVC is one of them; with Spring MVC you don't need to reinvent the wheel (i.e binary form management, form parameter to bean conversion, parameter validation and so on).
Another plus of Spring MVC is that in one class you can easily manage input from different urls and methods, doing the same in a servlet is possible but the code is more complicated and less readable.
My opinion is that Spring MVC is good for building rest services and managing simple applications (i.e web application with simple forms). If you need to manager very complex forms with Ajax, nested forms, and an application with both session and page state my advice is to switch to a component based framework (like apache wicket for example).
JSF and JSP aswell as Spring MVC builts upon Servlets. The problem this that servlets are not very "nice" to work with because you have to write direct html.
If you are able to use mordern web technologies I would just use servlets in positions that need direct http output like writing an image from a database to http.
Using SpringMVC or JSF which work with a Dipatcherservlet or FacesServlet is just faster and more fun. They parse your files and send it through a servlet.

What is the preferred way to use EJBs and Servlets for web applications?

I am trying to familiarize myself with JavaEE. I am a bit confused as to what the purpose of each "component" (for lack of a better word) is: Session Beans and Servlets, and how they properly interact with a web application (client-side JavaScript).
In an attempt to understand this I am building a simple web application. What is the preferred way to use each component to build something similar to the following:
User visits a "Log in" page
User inputs data and clicks submit. I then send an request with AJAX to log in the user.
The server side then validates the user input and "logs" the user in (returns user profile, etc.)
When sending the request, do I send it to a Servlet (which uses an EJB), or to a Session Bean through WSDL? How do I go about maintaining a "state" for that user using either method? I assume with Session Beans it's as simple as annotating it with #Stateful.
Also, I assume the requests sent from the client side must be in SOAP format. How easy is it to use something more lightweight (such as JSON)? While I would prefer to use something lightweight, it's not necessary if SOAP makes development faster/easier.
The Java Enterprise Edition tutorial address pretty much all of the topics you bring up; what's the purpose with the different kind of bean types, how do I implement web services, how do I implement authentication, etc.
I highly recommend you take the time to build the sample application, especially if you're completely new to the Java Enterprise Edition (Java EE). It is important you build up a good understanding of the core concepts because it can be hard to know what to focus on in the beginning due to the breadth and depth of technologies and standards that comprise Java EE.
One thing to keep in mind is that while Java EE certainly tries to support best practice and enable design and development of secure enterprise applications that perform and scale well, it does not prescribe or limit enterprise applications to follow one particular protocol, data format, and enterprise application design pattern. Some protocols and formats are better supported out of the box by the core framework implementations, and some choices are vendor-dependent, but very few specific technology choices are locked into the specification.
To answer some of your specific questions, Java EE has great support for SOAP, but it does not preference nor limit web services to the SOAP protocol. With JAXB and JAX-RS it is just as easy to develop RESTful web services that accept and return XML or JSON, or both. It's up to you to decide whether you need to use SOAP, REST, or another protocol.
It's also your choice whether you want to use frameworks like JAX-RS or explicitly develop Servlets to handle HTTP requests and responses. In many cases, JAX-RS will have everything you need, meaning you'll be able to implement your web services as plain old Java methods with a few annotations without ever having to bother with marshalling and unmarshalling contents and parameters.
Similarly, with JAXB it's up to you whether you want to use WSDL or not. It's great if you have WSDL definitions, but no problem if you don't.
In many cases you will typically maintain state using the Java Persistence Architecture framework (JPA), and access and manipulate such data through stateless session beans. Developers new to Java EE are often tempted to use stateful session beans to maintain state that is better managed in the persistent storage. The tutorial takes you through the different kinds of bean types and their purpose.
Web services (WSDL, SOAP, etc.) are usually used for communications between applications.
Inside a single web app, you usually make simple GET/POST requests, using AJAX or not, and receive either a full HTML page, or a fragment of HTML (AJAX), or XML or JSON data (AJAX). The browser usually talks to a servlet, but it's rare to use servlets directly.
The usual way is to use a framework on top of servlets. The frameworks can be divided in two big categories : action-based frameworks (Stripes, Spring MVC, Struts, etc.) or component-based frameworks (JSF, Wicket, Tapestry, etc.).
In a n-tier application, all of the above technologies are supposed to only contain the presentation layer. This presentation layer talks to a business layer, where the real business logic happens, where transactions are used to access databases, messaging systems, etc. This business layer is where EJBs are used.
You can create basic architecture as follows :
Create EAR instread two different Project like EJB Jar and Web Application WAR
You can create servlets which will call some delegate class which has logic to reffer the EJB
Either by calling it as remote call/ Either by Using #EJB annotation in the Delegation Class.
ServletClass {
do/post(){
DelegateClass d = new DelegateClass();
d.callMethod(withParam);
}
}
DelegateClass {
#EJB
EJBlocalinterface ejbintance;
void callMethod(DefinPrarm){
ejbinstance.callEJBMethod();
}
}
#Statelss
EJBbeanClass implements EJBlocalinterface{
void callEJBmethod(someParam){
}
}

what is the difference between MVC1 and MVC2

I am using MVC design pattern in jsp-servlet web application, and want to what is the exact difference between MVC1 and MVC2 , can someone help?
EDIT newly I hear that there is 2 versions of using MVC in servlet programming, I hear that in MVC1 there is kind of coupling between controller and view , but in MVC2 they overtake it, if someone know whether this is right or wrong I'll be very thankful.
It might be possible that you read this version in connection with asp.net MVC, as there different versions of that framework. There is no version 2.0 of the mvc pattern, just a version 2.0 of the asp.net MVC framework.
In context of jsp servlets see: Model 1 and Model 2. In a nutshell: Model 1 doesn't have a controller to dispatch requests, Model 2 does.
In MVC 1, controller and model,both are JSP. While in MVC2 controller is servlet and model is java class.
In MVC1 there is tight coupling between page and model as data access is usually done using Custom tag or through java bean call.
In MVC2 architecture there is only one controller which receives all the request for the application and is responsible for taking appropriate action in response to each request.
MVC1 was a first generation approach that used JSP pages and the JavaBeans component architecture to implement the MVC architecture for the Web. HTTP requests are sent to a JSP page that implements Controller logic and calls out to the Model for data to update the View. This approach combines Controller and View functionality within a JSP page and therefore breaks the MVC paradigm. MVC1 is appropriate for simple development and prototyping. It is not, however, recommended for serious development.
MVC2 is a term invented by Sun to describe an MVC architecture for Web-based applications in which HTTP requests are passed from the client to a Controller servlet which updates the Model and then invokes the appropriate View renderer-for example, JSP technology, which in turn renders the View from the updated Model.
The hallmark of the MVC2 approach is the separation of Controller code from
content. (Implementations of presentation frameworks such as Struts, adhere to the MVC2 approach).
That's what I found here: http://www.theserverside.com/discussions/thread.tss?thread_id=20685
MVC-1 Architecture
1) In MVC-1 Architecture, single web component(Servlet/JSP) is used as Controller and view but for other layers separate web components are taken....
2) Since, single component is taken as Controller and view, logics are mixed up..
MVC-2 Architecture
1) In MVC-2 Architecture separate components should be taken for separate layers...
2) Logics are not mixed, there is clean separation between the logics....

Custom web MVC for a legacy Java EE project

I am in the middle of creating my own custom MVC web framework for a project. This project has very old code base where one JSP page directly submits a form to another JSP whereas the paths are also hardcoded. Now it is a big project and putting Struts or JSF will take considerable amount of time.
So my suggestion is to build a small custom MVC framework and convert many existing page flows into it and also encourage them to develop newer applications using this new MVC frameworks.
I would like to review this with all of you whether it makes sense or we should directly go to the standard MVC frameworks.
My idea
1. Create one front controller servlet which will have URL pattern like /*.sm
2. This servlet reads one config file and creates a map whose key is requestedURI and value is the class name of the command bean.
3. upon intercepting any action request it reads the parameter map (request.getParameterMap()). This servlet refers the already built map, understand whose command bean is to be invoked? Creates an instance of this command bean.
4. pass the parameter map to this command bean and calls execute method.
5. if any exception is found, front controller servlet forwards the request to one global error page
6. if everything is fine, it then forwards the request to the expected URI (by removong .sm and replace it with .jsp)
Do you think I am missing anything here? I know I can make it more fancy by providing error page per request page in the config file or so but those can be done later as well.
I think that you will end up reinventing the wheel rolling your own MVC framework. I know that it is tempting to make your own, since you won't have to get used to a new API but instead create your own and you can more easily adapt it to your specific usecases. But since it seems to be a very long lived application you will have to consider the fact, that your own framework (which may now be state of the art) will be legacy in a couple of years, too.
And that's where adapting one of the popular frameworks comes in handy. The creators of a new framework usually want others to move, too, so they will (or should) offer easy integration or migration options away from the frameworks they think they are doing better (Spring is a good example since it e.g. seamlessly integrates with existing Struts applications and you can gradually move your application without putting the old one into trash). Additionally most current frameworks are very versatile (which can sometimes be a problem since they need more time to get into it) and can be adapted to almost all usecases.
So I would recommend to review the existing solutions carefully (you can learn a lot from their design decisions and errors, too) and only start making your own if none of them matches your requirements.

Modular web apps

I've been looking into OSGi recently and think it looks like a really good idea for modular Java apps.
However, I was wondering how OSGi would work in a web application, where you don't just have code to worry about - also HTML, images, CSS, that sort of thing.
At work we're building an application which has multiple 'tabs', each tab being one part of the app. I think this could really benefit from taking an OSGi approach - however I'm really not sure what would be the best way to handle all the usual web app resources.
I'm not sure whether it makes any difference, but we're using JSF and IceFaces (which adds another layer of problems because you have navigation rules and you have to specify all faces config files in your web.xml... doh!)
Edit: according to this thread, faces-config.xml files can be loaded up from JAR files - so it is actually possible to have multiple faces-config.xml files included without modifying web.xml, provided you split up into JAR files.
Any suggestions would be greatly appreciated :-)
You are very right in thinking there are synergies here, we have a modular web app where the app itself is assembled automatically from independent components (OSGi bundles) where each bundle contributes its own pages, resources, css and optionally javascript.
We don't use JSF (Spring MVC here) so I can't comment on the added complexity of that framework in an OSGi context.
Most frameworks or approaches out there still adhere to the "old" way of thinking: one WAR file representing your webapp and then many OSGi bundles and services but almost none concern themselves with the modularisation of the GUI itself.
Prerequisites for a Design
With OSGi the first question to solve is: what is your deployment scenario and who is the primary container? What I mean is that you can deploy your application on an OSGi runtime and use its infrastructure for everything. Alternatively, you can embed an OSGi runtime in a traditional app server and then you will need to re-use some infrastructure, specifically you want to use the AppServer's servlet engine.
Our design is currently based on OSGi as the container and we use the HTTPService offered by OSGi as our servlet container. We are looking into providing some sort of transparent bridge between an external servlet container and the OSGi HTTPService but that work is ongoing.
Architectural Sketch of a Spring MVC + OSGi modular webapp
So the goal is not to just serve a web application over OSGi but to also apply OSGi's component model to the web UI itself, to make it composable, re-usable, dynamic.
These are the components in the system:
1 central bundle that takes care of bridging Spring MVC with OSGi, specifically it uses code by Bernd Kolb to allow you to register the Spring DispatcherServlet with OSGi as a servlet.
1 custom URL Mapper that is injected into the DispatcherServlet and that provides the mapping of incoming HTTP requests to the correct controller.
1 central Sitemesh based decorator JSP that defines the global layout of the site, as well as the central CSS and Javascript libraries that we want to offer as defaults.
Each bundle that wants to contribute pages to our web UI has to publish 1 or more Controllers as OSGi Services and make sure to register its own servlet and its own resources (CSS, JSP, images, etc) with the OSGi HTTPService. The registering is done with the HTTPService and the key methods are:
httpService.registerResources()
and
httpService.registerServlet()
When a web ui contributing bundle activates and publishes its controllers, they are automatically picked up by our central web ui bundle and the aforementioned custom URL Mapper gathers these Controller services and keeps an up to date map of URLs to Controller instances.
Then when an HTTP request comes in for a certain URL, it finds the associated controller and dispatches the request there.
The Controller does its business and then returns any data that should be rendered and the name of the view (a JSP in our case). This JSP is located in the Controller's bundle and can be accessed and rendered by the central web ui bundle exactly because we went and registered the resource location with the HTTPService. Our central view resolver then merges this JSP with our central Sitemesh decorator and spits out the resulting HTML to the client.
In know this is rather high level but without providing the complete implementation it's hard to fully explain.
Our key learning point for this was to look at what Bernd Kolb did with his example JPetstore conversion to OSGi and to use that information to design our own architecture.
IMHO there is currently way too much hype and focus on getting OSGi somehow embedded in traditional Java EE based apps and very little thought being put into actually making use of OSGi idioms and its excellent component model to really allow the design of componentized web applications.
Check out SpringSource dm Server - an application server built entirely in terms of OSGi and supporting modular web applications. It is available in free, open source, and commercial versions.
You can start by deploying a standard WAR file and then gradually break your application into OSGi modules, or 'bundles' in OSGi-speak. As you might expect of SpringSource, the server has excellent support for the Spring framework and related Spring portfolio products.
Disclaimer: I work on this product.
Be aware of the Spring DM server licensing.
We've been using Restlet with OSGi to good effect with an embedded Http service (under the covers it's actually Jetty, but tomcat is available too).
Restlet has zero to minimal XML configuration needs, and any configuration we do is in the BundleActivator (registering new services).
When building up the page, we just process the relevant service implementations to generate the output, decorator style. New bundles getting plugged in will add new page decorations/widgets the next time its rendered.
REST gives us nice clean and meaningful URLs, multiple representations of the same data, and seems an extensible metaphor (few verbs, many nouns).
A bonus feature for us was the extensive support for caching, specifically the ETag.
SpringSource seems to be working on an interesting modular web framework built on top of OSGi called SpringSource Slices. More information can be found in the following blog posts:
Modular Web Applications with SpringSource Slices
Pluggable styling with SpringSource Slices
Slices Menu Bar Screencast
Have a look at RAP! http://www.eclipse.org/rap/
Take a look at http://www.ztemplates.org which is simple and easy to learn. This one allows you to put all related templates, javascript and css into one jar and use it transparently. Means you even have not to care about declaring the needed javascript in your page when using a provided component, as the framework does it for you.
Interesting set of posts. I have a web application which is customized on a per customer basis. Each customer gets a core set of components and additional components depending on what they have signed up for. For each release we have to 'assemble' the correct set of services and apply the correct menu config (we use struts menu) based on the customer, which is tedious to say the least. Basically its the same code base but we simply customize navigation to expose or hide certain pages. This is obviously not ideal and we would like to leverage OSGi to componentize services. While I can see how this is done for service APIs and sort of understand how resources like CSS and java script and controllers (we use Spring MVC) could also be bundled, how would you go about dealing with 'cross cutting' concerns like page navigation and general work flow especially in the scenario where you want to dynamically deploy a new service and need to add navigation to that service. There may also be other 'cross cutting' concerns like services that span other of other services.
Thanks,
Declan.

Categories

Resources