How to use the controller in a java application

Asked

Viewed 2,457 times

1

Staff I am starting in programming and would like to take a question that does not want to shut up, how to use the controller correctly whether it is being used in a design Pattern model or even in frameworks like spring mvc, Vraptor etc...

Example:

I have a java application that performs user registration in it I have a model (User), User controller and a Daousuario when logging in or adding any other type of screen that needs a business rule or receives requests I must create another controller?

Example:

I need to log in and keep user data for that session so I must create a new controller?

2 answers

0

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

0


When you’re talking about Controller. I believe you’re talking about architecture MVC (Model-View-Controller). When we use the standard MVC terms as a goal to separate the application into 3 layers. The business rule (Model) of the user interface (View) and of application flow (Controller).

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

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

The services, holders of business rules, manipulate the information coming via request and return to sponse to the controller return to the application.

Think of the following analogy about the controller, as a waiter who seeks the order and returns the food. He does not cook. He is just an intermediary between the cook and the client. Likewise the controller seeks to serve as an intermediate layer between the presentation layer and the logic.

Finally, to understand the theory, let’s go to practice. I will use the Spark framework 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.

First of all every request that comes from front-end, reaches the back-end through the application routes. Let’s assume our route is debitos, soon, the url will look 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 be in charge of delivering the information Request at the Controller::metodo that we specify on the route. Here begins the intermediation of the controller between the application and the logic of the system.

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 go explain:

  • Note that to capture the request and transfer to an object I use the method fromJson() of new Gson(). It is very simple to use. The following are examples: example 1 and example 2;
  • I created a specific service to treat and mainly treat standardize the response structure of the application. The response;
  • I created another exclusive service to treat 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 services MensalService, FiltroService, DiarioService contain the same methods: execute() and getResponse().
  • About the controller: The ideal is a context/responsibility controller. In the example I showed you the controller route manager Debitos. Let’s assume that enforcement contains another responsibility: Creditos, it would be right to create a controller to "control" functionality routes Creditos. In short: A controller context/responsibility.
  • Finally, return the response to the front in json format return apiResponse.json(), because in this example the application is a API Rest.

Obs.:

  • Just so there is no doubt... So I should use a controller for my entire application because it performs the middle field in my application as well as in your example of the waiter, then I must process the data in my service and just send the response to my controller so that it can return the response to the view, right?

  • If I understand your doubt well. Use a single controller for the entire application? No. The ideal is a controller by context/responsibility. In the example I showed you the controller route manager Debitos. Let’s assume that enforcement contains another responsibility: Creditos, it would be right to create a controller to "control" functionality routes Creditos. To summarize: A controlText/responsibility.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.