How to use the controller in a java application

1

asked by anonymous 12.09.2018 / 22:55

2 answers

0

When you're talking about Controller . I think you're talking about the Model-View-Controller in>). When we use the standard MVC terms we aim to separate the application into 3 layers. The Model rule of the View UI and the Controller flow rule) .

So far, we have not involved any programming language to conceptualize what a controller is. This is not a concept of a specific language, much less a design pattern. It is a software architecture standard .

Speaking especially about controller . Its main purpose is to direct the flow of the application by mapping and directing the received actions ( request ) through the presentation layer to the respective application services.

Services, business rule holders, manipulate information coming via request and return response to the controller return to the application .

Consider the following analogy about the controller , such as a waiter looking for the order and returning the food. He does not cook. It is only an intermediary between the cook and the client. In this same way the controller seeks to serve as an intermediate layer between the presentation layer and logic.

Finally, to understand the theory, let's practice. I'll use the framework spark to illustrate our example. Let's assume that the url of our application is: http://localhost:8000/ .

Follow another example in PHP using Laravel . Good reading to understand what a route is. I recommend it.

First, every request that comes from the front-end , arrives at back-end through application routes . Let's assume that our route is debitos , so the url looks like this: http://localhost:8000/debitos .

// end-point debitos
path("/debitos", (request, response) -> {
    get("/filtros", DebitosController::filter);
    post("/mensal", DebitosController::mensal);
    post("/diario", DebitosController::diários);
});

The routes of Spark are responsible for delivering the Request information to Controller::metodo that we specify on the route. Here begins the intermediation of controller between the application and the system logic.

The controller , in turn, receives the information and passes to the service handle / use as the business rule you want.

public class DebitosController {
    public static String filtro(Request request, Response response) {
        //pelo request ser um get e apenas uma informação não precisei transformar num objeto
        String filtro = request.queryParams("filtro");

        //serviço para tratar apenas da resposta
        ResponseService apiResponse = new ResponseService(response);

        //serviço para tratar apenas do request (os filtros)   
        FiltroService dateFilter = new DateFilterService(button);

        try {
            dateFilter.execute();
            apiResponse.setResult(dateFilter.getResponse());
        } catch (Exception exception) {
            apiResponse.setError(exception);
        }

        return apiResponse.json();
    }
    public static String mensal(Request request, Response response) {
        //converto os dados do request num objeto com getters e setters
        MensalRequest mensalRequest = new Gson().fromJson(request.body(), MensalRequest.class);

        //serviço para tratar apenas da resposta
        ResponseService apiResponse = new ResponseService(response);

        //serviço para tratar apenas do request (dados mensais)  
        MensalService mensal = new MensalService(mensalRequest);

        try {
            mensal.execute();
            apiResponse.setResult(mensal.getResponse());
        } catch (Exception exception) {
            apiResponse.setError(exception);
        }

        return apiResponse.json();
    }

    public static String diario(Request request, Response response) {
        //converto os dados do request num objeto com getters e setters
        DiarioRequest diarioRequest = new Gson().fromJson(request.body(), DiarioRequest.class);

        //serviço para tratar apenas da resposta
        ResponseService apiResponse = new ResponseService(response);

        //serviço para tratar apenas do request (dados diarios) 
        DiarioService diario = new DiarioService(debtRequest);

        try {
            diario.execute();
            apiResponse.setResult(diario.getResponse());
        } catch (Exception exception) {
            apiResponse.setError(exception);
        }

        return apiResponse.json();
    }
}

Now let's explain:

  • Note that to capture request and transfer to an object I use the fromJson() method of new Gson() . It is very simple to use. Here are examples: example 1 and example 2 ;
  • I've created a specific service to deal with to treat and mostly standardize the response structure of the application . The response ;
  • I created another unique service to handle the logic of the application. In it I use a contract (interfaces) so that all services related to this functionality have the same methods. Therefore, all MensalService, FiltroService, DiarioService services contain the same methods: execute() and getResponse() .
  • About controller : The ideal is a context / responsibility controller. In the example I showed you the controller responsible for the Debitos routes. Let's assume that the application contains another responsibility: Creditos , the correct one would be to create a controller to "control" the Creditos functionality routes. In short: A% context / responsibility%.
  • Finally, return the response to the front in json controller format, because in this example the application is a API Rest .

Note:

12.09.2018 / 23:46
0

The main idea of MVC is to separate the code that creates and manipulates data from the code that displays the data. In the case of a login, who will receive the data of the request is the Controller, but it is not he who will manipulate this data, then, he delegates this task to another responsible, possibly a Service. After the Service completes processing, the result is generated and returned to the Controller. This result contains the data (Model) and View that will show this data to the user.

    
13.09.2018 / 15:15