Spring - multiple command class with AbstractWizardFormController - java

Can i have a AbstractWizardFormController controller with different command class for each page ?

Sounds like a hack to me, but sure --the formBackingObject() method is called for each page, so you can override that method and add code to determine which command object to return (based on which page view is being requested).
On the other hand, that's going to add complications when you handle each pages submission -- will you have to figure out which type of object you're getting and cast? I'd rethink -- maybe this isn't really a wizard-type situation and you should have separate controllers? Or perhaps you should look at Web Flow? My experience is that the Wizard controller is useful if you're using it as envisioned, but when you start trying to squeeze it into a scenario it's not meant for, it becomes more complicated than helpful.

Related

why not call service class directly from jsp

So i have a sort of design question:
I have a jsp, and a controller that fetched the data for that jsp. Some of that data come from service classes.
I know that mvc pattern tells me to use the controller to call the service class and pass that info to my view (jsp).
Why can't I call the service class from my jsp directly?
You can, and that's what developers sometimes do. But you shouldn't.
MVC is about interchangeability and separation of concerns. If you call your service from JSP, you create a tight coupling, to parameters and return types, for example.
Moreover, usually, systems are not developed singlehandedly. Let's say you have getAllAdmins() method in your service, which you use for internal logic. Do you really want another developer to use it directly in JSP, and by mistake display all your admins? Probably not.
You can. You can even put everything in one class and maybe it will work. But why? Doing like that ruin all flexibility.
You think only about little example, but you should think what advantages it gives to big applications.
Read this.

JSP and MVC Best Practices

I am new to JSP programming and am writing a web app for a family member. As I study, I hear a lot about how JSP's are supposed to be used for presentation and servlets are for business logic. My question is basically about how far that goes and when my use of JSTL would be bad practice. Here's an example: I have a login page for my app, and I am using c:if's with custom functions connected to my java classes to process the form. Would that be considered poor MVC practice or, since I'm only referencing my logic code from EL, is this a legitimate use of JSP's?
Your question contains a lot of what are best-practices which invokes a lot of opinion and debate, which is usually frowned upon in this forum. In general, the JSP is the "V"iew in MVC and should be used to present the data provided by the "M"odel which would be your Java code. The "C"ontroller is often scattered between the M and the V (inviting more debate, sorry).
Any logic you put in your JSP that is beyond looking at the data given you and deciding how to present it, moves it towards the Model. Your login page should just collect the credentials and present them to the Model, which should in turn respond with "Invalid" and re-request the credentials (or fail completely) or if valid, move on to the next page.
In practice, IMHO, you should not put a lot, if any, code that manipulates the data except for formatting it - creating table entries, wrapping with links, etc. You should not (IMHO) query databases, perform calculations, etc., in the JSP - let the Model do that.
As duffymo stated, JSPs are old, but they are still valid. I would suggest that you also consider AngularJs (ng) (after reading about the controversy of V1 v. V2).
JSP is an outdated technology and there are very few Softwares that still use it. But if you want to use it I would suggest that you use Oracle Coding Standards with it. This page should give you a clear idea of what you should and shouldn't do with it.
The best practice with JSP - is not to use JSP at all. I’ll try to explain why and be clear.
First I have to explain something that does not have a connection to JSP at all, but it will help you to understand exact problems with JSP technology.
In functional programming there is a term - pure function. It means that it does not have side effects. Additionally, such function does guarantee that for each invocation with the same input it ALWAYS return the same output.
In OOP functions are not pure. It may have side effects. It makes our life more complicated. But what is important is that these side effects can happen only WITHIN your function. You can debug it. More or less it is UNDER YOUR CONTROL.
Let’s imagine our functionality written in JSP as a function f with input I and output O:
O f(I)
The first problem with JSP is that it DOES have side effects AND such side effects can happen not only inside of your function f, but also can affect it from outside. A simple example: you use tiles technology, your jsp page is used as a component in a tiles template. Another component of this template uses getOutputstream() method and writes to this output stream. But an application can either call getOutputStream or getWriter on any given response, it's not allowed to do both. JSP engines use getWriter, and so you cannot call getOutputStream. And you get in your jsp page that works fine when it is alone:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
getOutputStream() has already been called for this response
With a function you get explicitly input parameters. The input is always clear. Additionally you can use constants or, if your function has side effect use another service to get data for processing. But it is always WITHIN your function and more or less under control. With JSP pages you do not have such control at all. Input data can be put into session with different servlets/web components, input data can be put into request scope via servlet with a lot of if statements. You must first investigate a logic of this servlet. It is additional complexity that is not obvious when you create “Hello World!” program, but that really makes you crazy when you maintain such pages, written several years ago.
I think you have already read that mixing both output and logic is not a good idea. JSP allows people to do that. Cause it is “so convenient”.
You cannot test logic within your jsp pages. Or it makes it more difficult.
You can say that correct usage of jsp technology and applying best practices resolve most of issues. Yes. Agree. But it will never get rid of its internal drawbacks and complexity. You always have to check, really developers followed best practices or not? There are better, much better technologies our days.
Note: the only exception, or use case, when I’d personally would use it: for localisation. You do not have get all messages from server. You do not want to ask a server to get a localized string one by one. You do want to get a batch of values, that will be used on your web form, for instance. With JSP + JS you can do that very easily and explicite.

Java - Trying to plan the layout of a programs classes

I'm having a bit of trouble figuring this out so if you can help that would be great.
I have written a bit of code that gets a list of URLs from a sitemap. I then go each page, scrape all the links, and then test their status(200,404, etc).
I am using HttpClient. I have it all working OK but as I am new to Java I reckon my code is a complete hack/maze and I could most likely get far better performance if it was organised correctly. So what I have is
Main class - This builds the gui
Parse the sitemap class - This parses the sitemap and get a list of the urls.
Class called PingURl - I'm sure my above is poor but this is the bit I reckon is worst. This class opens all the urls, scrapes them for links, then tests the links for their status and returns it. I presume this class should be broken down? Most importantly I think I should be isolating the testing of the links in it's own class, so it would be easy to implement threads later on?
Basically I'm looking for advice. If someone could help me with laying out the project a bit better. Secondly I believe this is my weakest area so to improve I need to learn more about this, I don't even know what to call this(design/layout problem?). Can you also recommend resources to learn more about this?
Java is a language which IMO, embodies good OO design. Designing with OO in mind is very effective.
http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/oo.html
In terms of your problem, I think it works pretty well. You are kind of following a Model-View-Controller pattern: http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html
I can't tell you how to design your code, but I will tell you how I would do it if I were presented with the same problem:
I would get a class to represent a hyperlink. In that class there would be the hyperlink that has been scraped, and a getter and setter. As well as a boolean value and a ping function. That means that if I create a "hyperlink" object, then I can invoke ("ping") on that object because it is part of that class. That means that the ping function simply sets the boolean that represents connectivity.
That way, your parser basically gets a page, and for each link it finds, it creates a new "hyperlink" object based on your own "hyperlink" class. And puts it in an array. So once your parser executes you get an array of pointers to hyperlinks.
Then all you have to do is invoke the ping function on each one to see if it is there.
I think this design is the best because it scales from doing one hyperlink test to doing 1000 quite easily.
There is soooo much stuff out there about design, there are countless principals as well. There is never one absolute way to solve a problem. But the more experience you get, and the more you read up on design patterns and models the better you will get at it :)

Using sqls in JSP - What is the best practice?

Say, You have an application which lists down users in your application. Ideally, if you were writing code to achieve this in Java, irrespective of what your UI layer is, I would think that you would write code which retrieves result set from the database and maps it to your application object. So, in this scenario, you are looking at your ORM / Data layer doing its thing and creating a list of "User" objects.
Let's assume that your User object looks as follows:
public class User {
private String userName;
private int userid;
}
You can now use this list of "User" objects, in any UI. (Swing / Webapp).
Now, imagine a scenario, where you have to list down the userName and a count of say, departments or whatever and this is a very specific screen in a webapp. So you are looking a object structure like this:
public class UserViewBean {
private String userName;
private int countDepartments;
}
The easiest way of doing this is writing SQL for retrieving department count along with user name in one query. If I you to write such a query, where would you have this query? In your jsp? But, if you were doing this in a MVC framework, would you move this query to your data layer, get the result set, convert it to UserViewBean and send it to your jsp in request scope? If you write queries directly into jsps/if you are making use of connections directly in JSP, isn't that a bad practice?
I know, some of you might say, 'hey, you got your object composition wrong! if department is linked to user, you would want to create a list of departments in your User object' - Yes, I agree. But, think of this scenario - Say, I don't need this department count information anywhere else in my application other than this one screen. Are you saying that whereever I load my User object from the database, I would have to load a list of dependency objects, even if I won't be using them? How long will your object graph get with all the relational integrity? Yes, I do know that you have ORMs for this very reason, so that you get benefits of lazy loading and stuff, but I dont have the privilage to use one.
The bottom line question here is:
Would you write sqls in to your JSP if it serves just one screen? OR
Would you compose an anemic object
that caters to your view and make
your business layer return this
object for this screen - just to make
it look a bit OOish? OR
irrespective of what your screen
demands, would you compose your
objects such that an object graph
is loaded and you would get the
size of that list?
What is the best practice here?
I would never put SQL in a JSP. I would use Spring MVC or Struts controllers, or servlets to contain all of that type of logic. It allows for better error handling among other things (you can forward to error pages when queries fail).
If you really must do this, use the JSTL SQL tags.
Personally, I take a simple pragmatic approach. If I was writing screen that just displays a list of users with their deparment count, so that the entire code is maybe a page, and I don't expect this code to be used on any other screen, I'd probably just throw it all in the JSP. Yes, I know there are all the MVC purists who will say, "business logic should never go in a JSP". But aside from a dogmatic rule, why not? What would it hurt in a case like this?
If I found that I had two screens, maybe one where I had to simply display the list and another where I had to do some additional processing on the list, then I would certainly pull the common code out into a class that was called from both places.
I believe that the criteria should be: What produces the most maintainable code? What is shortest and easiest to understand? What produces the least linkages between modules? etc.
I adamantly refuse to accept the principle: "In some cases this approach leads to problems, therefore never use it." If sometimes it leads to problems, then don't use it in the cases where it leads to problems. Or worse, "Somebody wrote it in a book, therefore it cannot be questioned." Sure, there are some rules that are valid 99.99% of the time, so it gets to be pointless to check if this particular case is an exception. But there are lots of rules that are good 51% of the time and people leap from "mostly" to "always".
Would you write sqls in to your JSP if it serves just one screen?
In a prototype, just as a quick hack - maybe. In any other situation, not to mention a production environment - NEVER.
Use a proper MVC framework to separate business logic from presentation.
I am not even sure that JSP should be used, but for trivial applications. If you really have to use them, use MVC pattern or encapsulate your logic in a JavaBean.
Have a look at JPA which allow you to do object manipulations which then is persisted in the database
I wouldn't put SQL in a jsp for fear of forgetting it in future maintenance. Think of the poor guy maintaining your code-- poor guy = you in 10 months or whenever the database is restructured-- and at least put all SQL in the same general region.

Java: Form Submission in MVC : What is the best practice?

I am using a MVC framework which is a bit like struts.
So, say I have a "Edit Store" link in my application this is how the url would look like:
http://localhost:9080/test?action=editStore&storeNum=10
Now, action determines my Action (analogous to Struts Action) to be run. The corresponding action here is: EditStoreAction. Clicking this would open a pop up with different attributes of a store for edit.
My question here is:
How do I write my actions? Do I write two actions in this context?
EditStoreAction which will render
edit.jsp
StoreSaveAction which
will invoked when user presses
accept on the rendered response of
edit.jsp.
OR Do I just write one action? EditStoreAction and submit form to the same action, I would know that the user has pressed the accept button for changes on submission. So, I would execute a different flow in the Action, which would save updates to database and redirect to a diff page.
What is the best pratice here? Create as many actions as possible coz it keeps the code modular? OR just write one action to handle everthing in a jsp?
I know this question sounds a bit trivial, however, sometimes you just want to get everything right. Hence, the question. Appreciate your help.
The idea is, similar to Spring MVC, to map your actions to the methods of a specific class, say it controller.
So, in your case, these two actions will be mapped on two different methods of the same class. You can call the class StoreFormController and two methods, editStore() and saveStore().
Better still if you make two controllers for each entity. May be one for all GET requests and another is for POST requests. So, in your case there would be two controllers StoreController for all other requests and StoreFormController for all form submissions, namely post requests. Now, your first action being GET will go to editStore() method of StoreController, whereas the second being POST request will go to saveStore() method of StoreFormController. You can define as many methods as needed in any of these two classes based on the request type.
You can easily see, where I am coming from, if you know Spring MVC API.
I like to use struts DispatchAction class because I could define more than one method in the action class (the "execute") method. Behind the hood, all it does is to find the method that it has to execute (submitted in the form or passed in the URL), find the method using reflection, invoke it with the right set of arguments (the method must have the same signature of the "execute" method), gets it result and pass it along. The DispatchAction simply overrides the "execute" method of the Action class to implement that behavior.
That being said, in your case, I would define only one class - let's say "DispatchStoreAction", and I would define two methods, probably "prepare" and "save". I like doing it that way because I still have a good class abstraction (and you don't put the "action" you're executing in the class name), because your methods can clearly identify what they are supposed to do, and also because, by definition, action classes tend to be small. You will probably have a "StoreLogic" or "StoreBusiness" defined somewhere, and this class will handle the business logic related to the entity that you're working on. I personally think that it's nice if you have one "StoreAction" and then one "StoreLogic", one "UserAction" and one "UserLogic" and so on - the relationship doesn't need to be 1 to 1 but I think it helps maintaining the code.
Check the source code of the DispatchAction class for ideas on how to do this, but the implementation should be trivial.

Categories