首页 > 解决方案 > 从请求标头 Spring Boot 中读取 POJO

问题描述

我正在尝试解析从客户端发送到我的 Spring Boot 服务器端的请求标头中的对象。

@CrossOrigin(origins = "http://localhost")
@RequestMapping(method = RequestMethod.GET, value = "/verify")
public ResponseEntity<genericResponse>   verifyToken(@RequestHeader("Authorization") Authorization header) {
    System.out.println(header.getAccess() + " - " + header.getTimeStamp() + " - ");
}

但我不断收到此错误

无法将类型“java.lang.String”的值转换为所需类型“com.bus.api.dto.Requests.Authorization”;嵌套异常是 java.lang.IllegalStateException:无法将类型“java.lang.String”的值转换为所需类型“com.bus.api.dto.Requests.Authorization”:找不到匹配的编辑器或转换策略“,路径” :“/v1/clients/验证”

所以我尝试以某种方式构建自己的转换器。下面是我的授权 POJO 和 AuthorizationEditor 转换器

public class Authorization {

    private String token;

    private String timeStamp;

    private String access;
    // ... setters and getters are removed for brevity
}

编辑

public class AuthorizationEditor extends PropertyEditorSupport {


@Override
public void setAsText(String text) throws IllegalArgumentException {
    System.out.println(text);

        JSONObject obj = new JSONObject(text);

        Authorization authorization = new Authorization();
        authorization.setAccess(obj.getString("token"));
        authorization.setTimeStamp(obj.getString("timeStamp"));
        authorization.setAccess(obj.getString("access"));
       setValue(authorization);
    }
}

给我文本 [Object Object]然后prinln给出错误

JSONObject 文本必须在 1 [字符 2 第 1 行] 处以 '{' 开头

我通过ajax的客户端请求

function Auth() {
    if (token != null && profile != null) {

        var HEADER = {
            token: token,
            timeStamp: new Date().getTime(),
            access: profile
        }

        console.log(JSON.stringify(HEADER));
        /**
        * This request would first request a token from the Auth0 Server
        * The token is returned and that token is used to access API resource 
        */
        network.call(constants.VERIFY_URL, constants.TYPE_GET, {}, JSON.stringify(HEADER).trim());
        // window.location.href = "dashboard.html";
    } else {
        webAuth.authorize();
    }
}

标签: javaspringspring-boot

解决方案


推荐阅读