Converting WebApp into Desktop Application [Java] - java

I've been writing this very easy Webapp. It receives two parameters, a word and a letter. It counts how many times the letter can be found in said word.
I have a Dynamic Web Project in Eclipse with the following:
OccurencesCounter.java : has the method count with two params: word and letter. it returns the count (amount of times letter found)
OccurencesServlet.java In here I create an OccurencesCounter obj, I get the params, I call the function count etc, and I forwards request/response to result.jsp
result.jsp I show the results I've calculated.
This has been done for an exercice on Parameters and MVC.
According to the MVC pattern, I can change this webapp easily in a desktop application.
I know i need to change my view, result.jsp.
I need a main class. The rest of the code should stay the same.
My question is the following: What do I use the servlet for? I can't fathom how I could still need it.
I think I can use JOptionPane to input my parameters ("HelloWorld" , "o"), but bypass the servlet alltogether. I'd just need the OccurencesCounter class and my main class.
Is this normal? Or should I use the servlet (in some unknown way to me).
I'm confused, as this is an assignment telling me: We only want you to adjust the view when you create a desktop application, as it is requested by the MVC pattern. Make sure you have one model that works for both assignments.
Thank you

A Servlet listens to http requests and executes Java code, if the requests url matches the servlet mapping. This is useful when working with HTTP (server side/web application) but not in a desktop application (event driven).
We only want you to adjust the view (not your class) when you create a desktop
application, as it is requested by the MVC pattern.
They want you to reuse your OccurencesCounter class in both environments. Thats always possible, if that class does not include any kind of technique, related to the environment, for example a Servlet.
Make sure you have one model that works for both assignments.
Actually, you class is not a "model", from MVCs point of view. Its more of a service, that can be called (delegation) by a controller, returning the result (model) and displaying it on any kind of view.
So just create a class with a main method and run your OccurencesCounter class from there.

If you followed the MVC pattern in you web application you should have :
Model : a set of service, dao, and business classes that will be reused in the desktop application
Controller : a set of servlet (or controllers if you used a framework) -> al that is UI related and have to be rewritten
View : a set of HTML, JSP, CSS, etc. -> must be rewritten
The MVC model allows to (almost) easily replace the view part, if you want to migrate from JSP to Velocity or Thymeleaf but still in a web application

Related

Is it useful to use mediator pattern with MVC?

The question is about ideology of the MVC design pattern. By definition, the view is communicating with the controller directly. For instance, in JSF as well as ASP.NET web-forms, we can bind the property of the controller to a specific area of a web-page. But in this case we're doing that by directly wirte an expression like
<h:outputText value="#{partnerController.lastAccessDate}"/>
Would it be useful to create a mediator between views and controllers? I need, for instance, "send a message" to a several controller in a specific way.
In a traditional web application where a JSP page (or PHP or some other HTML generator) generates a form which is filled by the user and posted back to the server, this does not make a lot of sence. The posted form is sent directly to a controller which handels the data.
In fat client environment this makes a lot fo sence. The fat client can be something like SWING or a JavaScript framework like Angular. Here the controller acutally is a mediator. What it does is often called data binding. It makes sure the data entered into the GUI is stored in the business objects which gets eventually sent accros the wire or persisted.

How to Remove Duplication from Spring 3 MVC Standard and Ajax Request Controllers and Views

Lately I've been running into the same issue with my Spring MVC applications over and over again, and I'm trying to come up with a long term solution.
The problem is that in a standard Spring 3 controller, you add model objects, you specify the view name (either inline or from some injected field) and return. The problem I've run into is that if you have a request that returns a page with a person, and their pets you have something like (not compilable, psuedo):
#RequestMapping( value="personOverview", method="GET" )
public String getPersonOverview(model) {
model.add(personRepo.getPerson( theName ));
model.add(petRepo.getPetsForPerson( thePerson ));
return "personOverviewViewName";
}
Now, in your view you will be able to render all of this information. However, the issue arises when someone updates the "pets" for the person, and you just want to re-render the part of the page that shows the pets.
Not only do you need to rewrite the rendering logic in a JSP fragment or in JavaScript, but also you will need to duplicate the controller code for each portion of the getPersonOverview method. If you were to break the controller methods up into smaller chunks, then you will not be able to render the full page, but will have to render each chunk with a separate request.
In a normal ModelViewController pattern, the solution to this is that the view has access to the model, but in Spring MVC the model is in Java and lies behind the request layer, so you need to build request handlers for each model object.
I know this question may seem a bit abstract, but what I'm looking for is patterns or principles that can be used to allow me to build full pages with many model objects, but also be able to update portions of the page with ajax without duplication.
Not used it myself, but have you considered Tiles?

Have I implemented a n-tier application with MVC correctly?

Being pretty unfamiliar with design patterns and architecture, I'm having trouble explaining to others exactly how my latest application is designed. I've switched between thinking it's a pure n-tier, pure MVC and n-tier with MVC in the presentation layer. Currently I think the latter is correct, but I want thoughts from more experienced developers.
How it works:
Browser sends HTTP request to Tomcat. Maps the request via web.xml to a servlet (which I call controller)
The controller instantiates one or more business object and calls methods on these, i.e. customerBO.getById(12) which again will perform business logic/validation before calling one or more DAO methods, i.e. customerDAO.getById(12). The BO returns a list of CustomerVO's to the controller
The controller prepares attributes for the view (JSP) (request.setAttribute("customers", customers);) and chooses a .jsp file to use which in turn will iterate the list and render XHTML back to the browser.
Structure (my proposal/understanding)
Presentation tier: currently using what I think is a MVC web-implementation: servlets (controllers), jsp (views) and my own implementation of OO XHTML forms (ie. CustomerForm) lies here. It should be possible to use a Swing/JavaFX/Flex GUI by switching out this presentation layer and without the need to change anything on the layers below.
Logic tier: Divided into two layers, with Business Objects (BO) on top. Responsible for business logic, but I haven't found much to put in here besides input validation since the application mostly consists of simple CRUD actions... In many cases the methods just call a method with the same name on the DAO layer.
DAO classes with CRUD methods, which again contacts the data tier below. Also has a convertToVO(ResultSet res) methods which perform ORM from the database and to (lists of) value objects. All methods take value objects as input, i.e. customerDAO->save(voter) and return the updated voter on success and null on failure.
Data tier: At the bottom data is stored in a database or as XML files. I have not "coded" anything here, except some MySQL stored procedures and triggers.
Questions (besides the one in the title):
The M in MVC. I'm not sure if I can call this n-tier MVC when the models are lists/VO's returned from business objects in the logic tier? Are the models required to reside within the presentation layer when the controller/view is here? And can the form templates in the presentation layer be called models? If so; are both the forms and lists from BO to be considered as the M in MVC?
From my understanding, in MVC the view is supposed to observe the model and update on change, but this isn't possible in a web-application where the view is a rendered XHTML page? This in turn leads me to the question: is MVC implemented differently for web-applications vs. regular desktop applications?
I'm not using a Front Controller pattern when all HTTP requests are explicitly mapped in web.xml right? To use Front Controller I need to forward all requests to a standard servlet/controller that in turn evalutes the request and calls another controller?
The Business Layer felt a little "useless" in my application. What do you normally put in this layer/objects? Should one always have a business layer? I know it should contain "business logic", but what is this exactly? I just perform input validation and instantiate one or more DAOs and calls the appropriate methods on them...
I realize there is MVC frameworks such as Struts for Java, but since this my first Java web-application I tried to get a deeper understanding of how things work. Looking in retrospect I hope you can answer some of the questions I stumbled upon.
I'm not sure if I can call this n-tier MVC when the models are lists/VO's returned from business objects in the logic tier
Those are perfectly good models. I also consider the ActionForms in Struts to be models. ActionForms are what Struts uses to represent/model HTML forms.
in MVC the view is supposed to observe the model and update on change, but this isn't possible in a web-application
Yep, and that is a matter of debate as to whether you can have true MVC with web-applications.
Should one always have a business layer?
It depends on the type of application. Some applications are database-driven, and are essentially a UI for the database. In that case, there's very little business logic required.
Data Tier:
The stored procedures aren't really part of the data tier code. You should be creating data access objects (DAOs) which are called by the business objects. The DAOs call the stored procedures. Further, the DAO interfaces should give no hint to the business objects as to where the data is stored, whether that be a database or file system or from some web service.
I think you are getting hung up in the terminology. The MVC pattern (I believe) pre-dates the classic web app arch you describe. It use to be that people called web app arch MVC 2 (Model 2 etc.) to differentiate it from the original MVC pattern...
see this link > http://www.javaranch.com/drive/servlet/#mvc2
HTH

One or multiple servlets per webapp?

I know, it depends on the webapp. But in the normal case, what do you do: one servlet, that serves different pages (like an standalone-application with changing content) or for every page a single servlet.
Take for instance a blog. There is the start-page with the most recent blog-entries, an article-view for displaying one blog-entry and an archive. Do you implement this with three different servlets, or one that is dispatching to the functions. At least a good part of the stuff is shared, like http-headers.
So, what are your experiences, what works best?
Usually you will create a servlet per use case. Servlets acts like controllers for your application. When you identify an interaction from a user then implement a servlet to control that interaction.
That is, if you are using plain servlet/JSP to build the site. If you are using a framework like struts you will find that they implement the front controller pattern and use a single servlet that recieves all the requests and forwards these requests to action classes that implement the actual logic of the user request. this is much harder to do yourself but its a good practice...its the reason why so many people use these frameworks.
So the short answer is, you will create many servlets per webapp since each webapp will expose several use cases.
[EDIT] Re-reading your question it seems as if you are using the term site to mean page or view. Again, it depends on what is happening on that view. For instance, To display the newest blog entry, you can have a servlet that constructs the list of entries from the database for display. If the user clicks on an entry then another servlet can retrieve that single entry for viewing and so on. Mainly, each action is a use case therefore a different servlet.
Most web frameworks use a dispatcher servlet (ex: Spring MVC) that takes care of routing requests to appropriate classes/controllers.
When you start having lots of pages, this approach works best because you have a more user friendly way (in regard to web.xml) of declaring/managing a class that handles http requests and its url. Example (spring mvc again):
#Controller
public class MyController {
#RequestMapping("/viewPosts")
public void doViewPosts(HttpRequest r, HttpResponse res) {
//...
}
}
Besides, having a dispatcher servlet keeps your code flow centralized.
It depends.
In my latest projects, I have implemented a single servlet that delegates to several servlet-like objects which are instantiated in a dependency injection fashion. For instance, I have something like this in my servlet (pseudo-code):
for(Handler handler : handlers) {
if(handler.handle(request, response)) {
return;
}
}
where Handler is an interface with a boolean handle(request, response) method. I obtain my handlers from a container (be it Spring or something even more lightweight).
The reason for this is that I really like dependency injection, and it is difficult to achieve it in Servlets; and I really don't feel much at home with most frameworks that provide web-component dependency injection- I like the simplicity of servlets.
Were not for this, I would go with multiple servlets, although there's a trade-off; either you have an enormous web xml with lots (and lots) of servlet mappings or you have a very complex servlet (unless you use something like my d-i approach).

Recommended Java/AJAX design pattern?

We need some input on what is a good design pattern on using AJAX in a Java application.
Consider a simple scenario:
User clicks a button which sends a request to a Java method to fetch data from DB.
Java object is returned by method and needs to be converted into a HTML table.
HTML table is shown on JSP.
What we currently do:
On a JSP page, user clicks "Show Users" button
Button using Prototype.js calls a "middleman" JSP which forwards the request to the Java method to get the data from the DB.
The method returns the Java object to the "middleman" JSP which converts the Java object into HTML (since the AJAX call from the calling JSP won't be able to handle the Java object directly).
The HTML is then returned to the Prototype call which updates the div on the calling JSP.
Our concerns are:
We would like to keep the separation of business/presentation logic and would prefer no HTML/JavaScript code inside our Java methods.
Keeping (1) in mind, is having a "middleman" JSP an OK way to do this? Or should we return the Java object as XML/XSLT to the AJAX request?
The above way we're doing has very little JavaScript and works in all browsers.
We looked at some other packages - DWR, GWT, but either there was too much dependency on JavaScript or required UI components to be present in the Java classes.
Is our way of doing things above OK? Or is there another preferable way?
Any help/thoughts would be appreciated.
Thanks,
SP
Sounds fine. You are separating view components from model components. It shouldn't matter how the call comes to the server, AJAX or not, it should be received by a controller (a servlet say) that interacts with the model, thats your Java classes that get the data from the database and forward to a JSP page for rendering the view.
There are frameworks that could simplify the boilerplate code but the design you describe sounds fine.
I'm not sure if you noticed, but there's one significant difference between your solution and what Vincent proposed. This is that the request should be initially received by a servlet (or controller, or Struts action, etc.) rather than a "middleman" JSP.
MVC dictates that JSPs should really only we used for generating the view from the model data, flow control is better handled in Java code.

Categories

Resources