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

Asked

Viewed 867 times

2

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

The template that I use bootstrap, didn’t have datepicker with Angularjs, so I’m using with jQuery.

I have on my screen, a modal with multiple fields, I could ALREADY pass all data through a POST request with AJAX to my Java controller, made no mistakes.

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

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

What I’ve already done:

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

Guys, I don’t know what else to do, it seems so simple. If you need 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>

debug chrome

Java Controller:

    @Controller
    public class CadastroUsuariosController {

    @Autowired
    private UsuarioService usuarioService;

    @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);

    }
}

3 answers

2

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

It is possible to do this simply and specifically for the field using the following annotation in the attribute of your model:

@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.

  • Thank you for the reply, I will apply and return...

  • Luiz, just one question, there in my JS I’m making the conversion to go to my controller. You know why it doesn’t work? Please, I don’t understand pq.. was also trying to force in the header of the en-BR header in Accept-Language

  • 1

    @Eonardo All you need to do is order and receive in the same format. Regardless of which format is sent by javascript, use it on the server and everything will be fine. No need to worry about the location.

1


Long story short, touching the . js of the bootstrap component (Components-date-time-pickers.js, which is not advisable), could correctly format the date, but the problem was not this, when I was doing my POST by ajax, there picking the dates by Scope, was passing the whole object and not a value, as the . value would do if it wasn’t a datepicker.

Palliative solution: I passed the date string ". toString()" for my java controller, there in my DTO I received as string also and worked with Simpledateformat to format the date correctly for the database accept the insertion.

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 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" />

Browser other questions tagged

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