Dealing with Dependencies when instantiating MVC objects in Java - java

I know that's not the most amazing title in the world, but bear with me.
I'm developing an application in Java, for part of which I'm using the MVC design pattern.
Above is my understanding of the MVC structure, or at least how I'm choosing to implement it. However I've run into a problem instantiating the objects. Since any given controller requires a reference to it's view pair, and any given view requires a reference to it's controller pair, I'm not sure how to actually create the objects.
I could pass the view into the controller as null and then immediately set it, but not only does this feel like bad coding practice it raised questions about where I actually should be creating the view. Is it something normally delegated to the controller? Any guidance would be greatly appreciated.

You can pass one as a constructor parameter to the other like this:
public class Controller {
private View view;
public Controller() {
this.view = new View(this);
}
}
public class View {
private Controller controller;
public View(Controller controller) {
this.controller = controller;
}
}

Related

How to properly define a Controller in Spring MVC compared to a JavaFX Controller

I'm having a hard time trying to understand the differences between a JavaFX Controller and a Spring MVC Controller. I came from a JavaFX background and I have seen many differences between a Spring MVC Controller vs a JavaFX Controller and I am currently working with Spring MVC.
There are important differences between them, for example, in JavaFX, each fxml view has its own controller e.g. LoginViewController.java with loginview.fxml, RegisterViewController.java and registerview.fxml.
This is the code of a simple ToDo List in JavaFX to be more clear in my question:
ToDoListViewController.java:
public class ToDoListViewController {
// private properties tied to the fxml view via #FXML annotation
private List<TodoItem> todoItems;
#FXML
private ListView<TodoItem> todoListView;
#FXML
private TextArea itemDetailsTextArea;
// ...
public void initialize() {
// code to initialize stuff
// ...
}
#FXML
public void showUpdateItemDialog() {
//get the item to be updated
// do stuff to update item
// ....
}
}
This Controller is tied to a todolistview.fxml, which I think is pretty straight forward.
Now in Spring, I have seen some controllers been oriented by the view and other by routes and it kind of confuses me. I have seen controllers like:
HomeController.java: (View Oriented)
#Controller
public class HomeController {
#RequestMapping("/")
public String showPage() {
return "main-menu";
}
}
CustomerController.java: (Route Oriented)
#Controller
#RequestMapping("/customer")
public class CustomerController {
private CustomerDAO customerDAO;
public CustomerController(CustomerDAO customerDAO) {
this.customerDAO = customerDAO;
}
#RequestMapping("/list")
public String listCustomers(Model theModel) {
// get the customers from the dao
// add the customers to the model
return "list-customers";
}
#RequestMapping("/add")
public String addCustomer() {
// return the jsp view to add a new customer
return "customer-form";
}
// same goes for get by id, update and delete
//...
}
Which is the best way to understand these differences? Which approach to use in Spring MVC? View oriented, Route oriented? Thanks for reading!
It all depends on requirement,
for example:
In your case,
if you want to access anything directly, (as homepage) you can go with view oriented one.
and if anything you want the access the like CUSTOMERS , so in your case,
you can use view orientation, for example for viewing customer you can just create a method with just "/customerList" and you will also get the required result, but every time for the customers you will need to do this for everything,
Instead what you can do is
Use route mapping since the (customer)feature establishes a route with it's creation, so you can use route mapping, as you have post in second example,
in that case all the request with "/customer" will come there and then will get to the exact method which you want(have written in the method's mapping). It is good for end mapping and can use to pass parameter id needed.
So it all depends on requirement and level of code one is writing.
Route oriented is a good way of dealing with endpoints in spring MVC. This way gives a good look to our code, Our code looks more organized and easier to understand. Route-oriented ways also provide additional rules like parameter filters and content type.

MVP, JavaFx and components references

I've studied all popular GUI patterns - MVP,MVC,MVVM and finally I decided to implement MVP (Supervising Controller). So I have the following OBJECTS(!). Stage<-View<->Model. It's important Stage!=View, it is another object. Between view and model data binding. Besides I have a presenter(controller) which handles all events and works with view and model, so View<-ViewInterface<-Controller->Model.
The problem is now how to get references to labels, textAreas etc in view. Javafx allows to use #FXML annotation to inject these components to controller. However, using MVP I need these components in View, as all logic for view is in View and I don't need them in controller. The only solution I know is:
public class MyView{
private Button button;
public MyView(){
...
button=(Button) root.lookup("#myButton");
}
}
That is to get references by their ID. However I don't like it. Or I do something wrong or I understand something wrong but I think a better solution exist. Please, help me to find it.
JavaFX has been designed to work with the MVC pattern. Hence it is much easier to use MVC than MVP. In MVP Presenter is responsible for formatting the data to be displayed. In JavaFX, it is done automatically by View. Here's a quick overview of JavaFX MVC:
Model - the domain data / data structure that you work with in your application (e.g. Person, Employer, Coursework, etc)
View - the UI definition of the application and its Model. The preferred way of creating a view is via an FXML file, which is essentially the View in JavaFX MVC.
Controller - the bridge between Model and View. The code is typically isolated in XController class (where X is the name of the FXML View). The instance of Controller is automatically injected by FXMLLoader or can be done manually in case you require a custom Controller. The Controller class will have access to UI (View) elements in order to be able to manipulate different properties and also the Model, so that it can perform operations based on the UI (View) input.
To sum up, in JavaFX you don't need to have class View, the View definition should be entirely in the FXML file. All UI elements should be injected with #FXML into your Controller class. If you absolutely have to use MVP, then AWT/Swing or MVP4j - http://www.findbestopensource.com/product/mvp4j might be a better option.
For more detailed explanation please have a look at the official Oracle tutorial for JavaFX: http://docs.oracle.com/javase/8/javafx/get-started-tutorial/jfx-overview.htm
If you require help building UI using FXML: http://docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/introduction_to_fxml.html
This tutorial covers basics of MVC in JavaFX and how each component communicates with others: http://code.makery.ch/library/javafx-8-tutorial/part1/
As an Android developer, I always use MVP pattern in my applications. MVC compared to MVP seems so old to me, so when I started working on a new Java app, I felt a little bit lost.
Here there is my solution:
Initial steps
In fxml files create the UI, without specifying a controller, because you don't need one.
Create the Java interfaces (IView, IPresenter and so on..)
Implement the IPresenter interface in the Presenter class, as you would do normally (do http requests, query a DB..)
Now the interesting part:
Adapting your view to MVP pattern
Let's see some code:
Create your GUI (for example a Main GUI) and implement your View interface
public class MainGUI extends Application implements MainContract.View {
public static void main(String... args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws IOException {
//here we will load fxml or create the ui programmatically
}
//method from view interface
#Override
public void onServerResponse(String message) throws IOException {
//update the view
}
Now the last step:
Communicating with the presenter
To do this, we first create an istance of our presenter:
private MainContract.Presenter presenter;
public MainGUI() {
presenter = new MainPresenter(this);
}
this is, of course, the MainContract.View implemented in the MainGUI class
Now we have to get a reference to the view components
private ComboBox<Double> mySimpleList;
#Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("layout_main.fxml"));
Parent root = loader.load();
mySimpleList= (ComboBox<Double>) loader.getNamespace().get("mysimplelist_id");
...
primaryStage.setScene(new Scene(root, -1, -1));
primaryStage.show();
I prefer using fxml files instead of creating the ui by code, but the logic behind is identical.
Set the items
...
mySimpleList.setItems(ValuesFactory.getMyValues());
And the listener
...
mySimpleList.valueProperty().addListener(simpleListListener);
What is simpleListListener?
A simple ChangeListener, where we finally call a presenter method
simpleListListener = (ChangeListener<Double>)
(observable, oldValue, newValue) -> presenter.doTheLogic(newValue);
This is an easy scenario, but in principle this is how we can use MVP Pattern with JavaFX. I also understand that it isn't the definitive solution, so I hope that one day there will be more docs where I can learn more about this argument!
Let me know if I wasn't clear in some part of the code

How to put DAO and GUI together with MVC

I'm creating a Java Application that represents a school. My aim is to keep the application open for new features, so I'm trying to apply some Design Patterns to it.
What I have so far is a HSQLDB connected to my program.
In the database one can store
pupils
courses
years
exams
grades
The current structure is as follows:
there are classes for each of the objects that contain the attributes + setters and getters
for each object there is a DAO that manages the CRUD operations on the DB
each DAO implements a GenericDAO interface
If i want to create a new pupil i can call:
PupilDao pupil = new PupilDao();
pupil.connectToDB();
pupil.add(new Pupil(name, age,...));
pupil.disconnectDB();
Every DAOs connectToDB() and disconnectDB() methods point to a DBuser-Classes connect() and disconnect() methods. So if I want to change the connection, there's only one place to do so.
So far, those operations work.
My questions are the:
1.) Is the current design a proper use of DAOs? I'm asking because i would rather have one
Dao for all objects because right now there's a lot of repetitive code in the DAOs. (e.g. get, update, delete...)
Now that the DB-Access works, I want to create a GUI using Swing. I have some experience doing this although not with the MVC-Pattern.
2.) As far as I understand, the DAOs + my object classes would be the Model here. Is that correct?
3.) My understanding of MVC is that in my View-Class (i.e. the GUI) I set listeners for my actions which point to different Controller-Classes implementing the ActionListener interface and in my Controller-Classes I would for example have a actionPerformed() that creates a new Pupil (using the DAO / Model - Classes). Am I on the right track here?
4.) Is it favourable to have one big Controller managing all actions over having different Controllers?
I'm asking those questions because I read/watched a lot about patterns/OO-Design and want to make sure my understanding is correct.
Furthermore I highly appreciate your thoughts on my design! What could be done more flexible or better to maintain later?
Thanks in advance for every suggestion and sorry for the somewhat long explanation!
Felix
While I still can't answer my questions for sure, I think I found a suitable way
for me and want to share the design (suggestions/answers are still appreciated!).
1) The applications entry-point is the main-application class (MVC.class). This class creates the
view using a main-controller. Here's the code:
public static void main(String[] args) {
// view is declared as class-variable
view = new View();
MainController mcontroll = new MainController(view);
view.getFrame().setVisible(true);
}
The main-controller only takes the view as parameter as its only purpose is to display the view.
As stated in my post above my aim was to display different database tables from a HSQLDB and modify them.
2) In the menubar there are entries for managing years, courses, etc. If one entry is clicked, the controller for the clicked category (e.g. years) takes control. Here is, how the controller is changed:
public void addManageYearsListener(ActionListener listener) {
mntmYears.addActionListener(listener);
}
The above method is located in the view class (i.e. the GUI class) but the main-controller implements the actionPerformed()-method. To do that, the main-controller calls the method defined in the view in his constructor like that:
public MainController(View view) {
this.view = view;
this.view.addManageCoursesListener(new ManageCourses());
this.view.addManageYearsListener(new ManageYears());
}
The corresponding class "ManageYears" is then defined as inner class:
class ManageYears implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
MVC mvc = new MVC("years");
}
}
What happens here is that when the menuitem is clicked, the main-controller "hears" the click (cause he is listening to it) and calls the main class again, although this time with a string as parameter. The constructor of the main class checks the string and sets the model and the controller that is needed. See here:
if (controller.equals("year")) {
YearDaoImpl yearDao = new YearDaoImpl();
YearController ycontroller = new YearController(view, yearDao);
}
"controller" is the string that is passed with the constructor and "yearDao" is the Data Access Object that handles the CRUD-operations which have to do with the object "year" (which is a class itself).
So now it's possible to switch controllers at runtime.
3) The year controller sets the ActionListeners for a add and remove button in his constructor (just like the main controller did for the menu item), get's the data from the database (via the yearDao) and sets the table model in the view (view has a setTableModel()-method for that) passing the returned ResultSet as parameter of the table Model class:
public void showYears() {
try {
con = yearDao.connectToDB();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM YEARS;");
view.setTableModel(new YearTableModel(rs));
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
As you can see, the yearDao has a connectToDB()-method that returns a connection (the connection is actually gotten from a c3p0 connection pool) which is then used to get a ResulSet of years from the database. The setTableModel()-method is then called setting the YearTableModel - a custom class extending AbstractTableModel and passing the ResulSet as parameter.
With the explained design it is now possible to:
1.) only have one table in the GUI that is populated with different database outputs.
2.) seperate the view from the data (which is what this whole fuss is about ;-)).
3.) add new controllers or models when needed without changing a lot of code.
As mentioned at the beginning I still appreciate every suggestion or improvement!
If you made it till the end of this post, I hope you found something to use in your own program!
regards,
Felix

Thin controllers

I am getting my feet wet with javafx. This is what I am doing.
FXML Views
DI Controllers
Weld-SE Managed Services and Models
Trying to confine UI to FXML
Trying keep the Controllers thin
Problem:
While trying to code the UI, most static UI is confined inside the fxml. But there are scenarios where I find my self adding, removing, showing, hiding elements etc.
I find myself doing this inside the controller as fx lets me configure controller method in the view which it will call on a particular action / event. All this code deals with Dynamic UI building / manipulating and belongs inside the view layer. But, it ends up in controller making the controllers fat.
javafx provides javascript integration. This is one possible way to abstract that view manupulation code away. But this would add not so perfect javascript into the mix.
How would I abstract the code away in java or fxml so that I don't break the Thin Controller Paradigm ?
EDIT
#assylias
Agreed, I have thought about this and this way that java class and fxml together become a reusable widget. But then, how do I wire this into FXML. FXML doesn't understand anything but a controller. Let say I wire this view class into fxml using fx:controller and not name it controller. So I have something like this.
This view class has nothing but view manipulation code. Then I would create another controller class. But then I would expect to somehow fill the form data into this controller. This should only happen when the user has submitted the form. So in a way, I need to tell javafx somehow that UI manipulation request / event is different from actual data manipulation request / event.
Your thoughts, sorry if it was verbose. Tried to articulate it in as few words as I could.
I think the easiest solution to this is to remember that the controller specified in FXML is a view controller. It's purpose is to contain code to modify and update the view, not to contain traditional MVC controller code or business logic.
For example, in a project I'm currently working on, I'm using JavaFX with Akka Actors. The application is written in scala. The JavaFX view controllers contain any code necessary to modify the view. One screen contains a login form. When the user clicks the login button, the view controller simply creates a message containing the username and password, and sends that message to the actor responsible for doing business logic. If that actor determines there is an error then it will send a message back to the view controller, and the view controller can decide what sort of updates need to be made on the screen.
I've found that using akka actors with JavaFX greatly simplifies coding the application for at least two reasons.
Because using an actor system mandates sending messages between actors, there is a natural boundary between presentation code and business code. The messages that are passed back and forth form this natural boundary.
Using actors completely replaces the complexity of working with threads/tasks. It completely eliminates the need to code javafx.concurrent.Task's for long running processes.
How about putting your view manipulation code in Main Class ?
Main Class :
public class SampleJavaFXApp extends Application{
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource(
"SampleUI.fxml"));
Parent root = (Parent) loader.load();
Controller controller = loader.getController();
viewManipulationLogic(controller);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
// view manipulation logic
private void viewManipulationLogic(Controller controller) {
controller.getBlueButton().setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
System.out.println(" I am just about button!");
}
});
}
Controller :
public class Controller implements Initializable {
#FXML
private Button blueButton;
public Button getBlueButton() {
return blueButton;
}
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
//real data manipulation
}
}
cons : You need getters for all Nodes u want to manipulate , in controller class.

Example of Passive View design pattern using JSP and POJOs

Im trying to understand how the Passive View design pattern works for simple web apps.
Can someone provide a simple example of this pattern using these requirements:
View is a JSP that prints HELLO WORLD!
Data is persisted in the data store as "hello world", call to retrieve data can be a stub
Provide example files for pieces (presenter, view, etc) and denote which piece of the pattern each file represents.
No frameworks/DSLs should be used other than jstl/el (which are optional)
Thanks
UPDATE 1: Adding my understanding of how this would be structured.
// Presenter; responsible for multiple "rendtions" of a particular view (show, index, edit, summary, etc.)
public class HelloWorldPresenter {
private HttpServletRequest request;
private DataStore dateStore;
public HelloWorldPresenter(HttpServletRequest request) {
this.request = request;
this.dataStore = DataStoreUtil.getDataStore(request);
// Do a bunch of other inits that all getXXXModels() will use
}
public getShowModel() {
HelloWorldShowModel model = new HelloWorldShowModel();
String tmp = makeLoud(this.dataStore.getMyData()); // Stub method
model.setText(tmp);
return model;
}
private String makeLoud(String str) {
return str.toUpperCase() + "!";
}
}
// Model used by view
public class HelloWorldShowModel {
private String text;
public getText() { return this.text };
public setText(String text) { this.text = text; }
}
// View
show.jsp
<c:set var="model" value="new HelloWorldPresenter.getShowModel()"/>
${model.text} -> HELLO WORLD!
or
<% HelloWorldShowModel model = new HelloWorldPresenter(request).getShowModel() %>
<%= model.getText() %>
The things I'm unsure about are:
How the Presenter would be exposed to the View (JSP) since the View shouldnt know about the presenter. I may be mixing semantics though, and the HelloWorldShowModel (which is acting as a "ViewModel" of sorts, is what shouldnt know about the Presenter).
Should I even have the HelloViewShowModel abstraction, or should I simply have a method getText() on my Presenter which is called within the JSP to get the requested text.
If I do have multiple "views" for a resource (ex. Show, Index, Edit, Summary, etc.), should I have multiple Presenters? How should this logic be broken up? Multiple presenters that inherit from a Shared presenter? Should each presenter only be responsible for returning one ViewModel?
I've read through Fowlers articles as well as a number of other write-ups - the problem (for me) is they are written in the context of .NET apps, and I dont understand how all their objects get wired up.
I hope this will aleve concerns of me being "lazy" and looking for a "hand-out" answer :)
With the requirements you state I would say the pattern can't be implemented. If you consider the view to be a JSP then there are no means a controller could actively set any values of UI components. (To me this is the core of the pattern: the controller actually updates the view actively by setting values of input / output UI components, not the other way round (view getting fields from a model object). This can't be done with the above techniques as a JSP has no means to be accessesd this way.
It could be implemented in a web environment based on Javascript though. Consider your view being the DOM and your controller being a Javascript component. The JS controller has direct write access to the DOM and therefore could update single fields actively like the pattern suggests. To update / get the model the JS controller could talk to a server-side system e. g. based on a REST API via Ajax.
A plain templating solution like JSP cannot be used to offload all logic to controller, at least in real world cases. I think this kind of thing can be achieved with JSF.
If you want to learn about how things are done I recommend you to take a look at Spring MVC. It's source code can teach you a lot.

Categories

Resources