Do not parse the bootstrap datepicker for dd / mm / yyyy - 400 Bad Request (POST)

2

I have a web application, basically pure wheel with JSP + AngularJS.

The template I use from the bootstrap, did not have datepicker with AngularJS, so I'm using it with jQuery.

I have on my screen, a modal with several fields, I could already pass all the data through a POST request with AJAX to my Java controller, did not give errors.

When I added the datepicker, it started giving the 400 error. What I figured out is that the date is being passed to my java controller as mm/dd/yyyy .

I made the deal with the option format of the datepicker , before sending the dates for the POST to be executed.

What I've done:

  • format of the datepicker already being set to dd/mm/yyyy and pt_BR , it still does not work.
  • I have already checked my DTO to see if what is being passed in the request has the same type ( DATE in case).
  • I checked my imports, as I saw in some posts related attention to the import sequence.

Galera, I do not know what to do, it seems so simple. If you need me to post more code, just talk. .

BoxApp.controller("UsuariosController", function($scope, $http) {   

    $scope.usuarios={};
    $scope.usuariosParaAlterar={};

    $scope.iniciar = function() {
        $http.get('/boxmlV2/usuario').success(function (response) {
            $scope.usuarios = response;
        });
    };
    $scope.iniciar();

    $scope.setSelected = function(selecao){
        $scope.usuariosParaAlterar = selecao;
    };

    /**
     * Trecho para validar o form ao submeter.
     */
    $scope.submitted = false;
    $scope.submitForm = function(formUsuarios) {
        $scope.submitted = true;        

        if (formUsuarios.$valid) {
            $("#dataValidadeConta").datepicker({
                format: 'dd/mm/yyyy',                
                language: 'pt-BR'
            });
            $("#dataValidadeSenha").datepicker({
                format: 'dd/mm/yyyy',                
                language: 'pt-BR'
            });     
            $scope.editaUsuario();
        }
    };

    $scope.editaUsuario = function() {      

        $http.post('/boxmlV2/usuario/salvarUsuario', {
            ativo : $scope.usuariosParaAlterar.ativo, 
            idUsuario : idUsuario.value,
            nome : nome.value,
            senha : senha.value,
            email : email.value,
            bloqueado : $scope.usuariosParaAlterar.bloqueado,
            dataValidadeConta : $scope.usuariosParaAlterar.dataValidadeConta,
            dataValidadeSenha : $scope.usuariosParaAlterar.dataValidadeSenha, 
            resetSenha : $scope.usuariosParaAlterar.resetSenha,
            perfil : $scope.usuariosParaAlterar.perfil          
        }).then(function(response) {
            $scope.sucesso();
        }, function(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });

    };

    $scope.sucesso = function() {
        $scope.closeMyPopup();
        $scope.iniciar();       
    };

    $scope.closeMyPopup = function() {
        $(myModal_autocomplete).modal('hide');
    };



});
<div class="form-group">
    <label class="control-label col-md-3">Data Validade Conta:<span
        class="required" aria-required="true"> * </span></label>
    <div class="col-md-9">
        <input
            class="form-control form-control-inline input-medium date-picker"
            name="dataValidadeConta" id="dataValidadeConta"
            ng-model="usuariosParaAlterar.dataValidadeConta" size="16"
            type="text" value="" required /> <span class="help-block">
            Selecione a data </span> <span style="color: red"
            ng-show="submitted && form.dataValidadeConta.$error.required">Campo
            Data Validade Conta Obrigatório.</span>
    </div>
</div>

<div class="form-group">
    <label class="control-label col-md-3">Data Validade Senha:<span
        class="required" aria-required="true"> * </span></label>
    <div class="col-md-9">
        <input
            class="form-control form-control-inline input-medium date-picker"
            ng-model="usuariosParaAlterar.dataValidadeSenha"
            name="dataValidadeSenha" id="dataValidadeSenha" size="16" type="text"
            value="" required /> <span class="help-block"> Selecione a
            data </span> <span style="color: red"
            ng-show="submitted && form.dataValidadeSenha.$error.required">Campo
            Data Validade Senha Obrigatório.</span>
    </div>
</div>

JavaController:

@ControllerpublicclassCadastroUsuariosController{@AutowiredprivateUsuarioServiceusuarioService;@RequestMapping(value="/usuario", method=RequestMethod.GET)
    public ModelAndView iniciar(ModelMap modelMap){
        return new ModelAndView("usuario");
    }

    @RequestMapping(value="/usuario",method=RequestMethod.GET,produces={"application/json"})
    public @ResponseBody List<UsuarioDTO> obterTodos(ModelMap modelMap){
        return usuarioService.obterTodos();
    }

    @RequestMapping(value = "/usuario/salvarUsuario", method = RequestMethod.POST, produces = { "application/json" })
    public @ResponseBody RetornoDTO insereOuEditaUsuario(
            @RequestBody UsuarioDTO usuarioDTO) {

        usuarioService.insereOuEditaUsuario(usuarioDTO);
        return new RetornoDTO(RetornoEnum.SUCESSO);

    }
}
    
asked by anonymous 07.01.2016 / 17:49

3 answers

1

In summary, by moving the .js of the bootstrap component (components-date-time-pickers.js, which is not advisable), I could format the date correctly, but the problem was not this, when I was doing my POST ajax, there taking the dates by the scope, was passing the whole object and not a value, as the .value would do if it were not a datepicker.

Palliative solution: I did pass the string ".toString ()" to my java controller, there in my DTO I received it as a string too and I worked with SimpleDateFormat to format the date correctly for the bank to accept the insert.     

13.01.2016 / 13:48
1

You are using SpringMVC and need to tell it what date format to expect for this field from your model.

You can do this simply and specifically for the field by using the following anotation in the attribute of your template:

@DateTimeFormat(pattern="dd/MM/yyyy")

Or you can do the same at the controller level by adding the following method to the controller:

@InitBinder
private void binders(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
    CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
    binder.registerCustomEditor(Date.class, editor);
}

This is a mechanism for defining arbitrary input formats. See documentation for more details.

    
08.01.2016 / 00:15
0

I use this way, in my template on top of the attribute add this annotation.

@DateTimeFormat(pattern="dd/MM/yyyy")

In the main class

@Bean
public LocaleResolver localeResolver() {
    return new FixedLocaleResolver(new Locale("pt", "BR"));
}

And in my input I use it that way

<input id="dataNascimento" type="text" class="form-control" th:field="*{dataNascimento}"
data-provide="datepicker" data-date-format="dd/mm/yyyy" data-date-language="pt-BR"
data-date-autoclose="true" data-date-today-highlignt="true" data-date-orientation="bottom" />
    
21.09.2016 / 17:32