1.问题追溯

很长一段时间都在做前后端分离的vue案例,今天突然使用Thymeleaf提交表单登录到security登陆验证时一直报错
JsonParseException: Unrecognized token ‘username’: was expecting
但是使用Postman提交json数据时却没有问题,那我就可以确定是表单数据不能正确解析的问题

    /**
     * 1.获取用户名和密码
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {
            User user = new ObjectMapper().readValue(req.getInputStream(), User.class);
            System.out.println("1.获取用户名和密码=="+user);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

报错位置:
User user = new ObjectMapper().readValue(req.getInputStream(), User.class);

2.解决办法

JSON.stringify(formData)打包json数据

        $("button[type='button']").click(function () {
            var formData = {
                username: $("#username").val(),
                password: $("#password").val()
            };
            $.post("[[@{/}]]admin/login", JSON.stringify(formData),
                function (data) {
                    alert("Data Loaded: " + data);
                });
        });

    })

我是这样就可以正常使用了,如果不行你还可以尝试:

$.ajax({
            type: "POST",
            url: "xxxx",
            contentType:‘application/json;charset=utf-8‘,
            data:JSON.stringify(allData),
            success: function (data) {
                alert(data);
            }
        });
Logo

前往低代码交流专区

更多推荐