解析头信息并在bean中设置它

时间:2018-06-15 07:46:39

标签: java spring spring-mvc

在我的Spring rest应用程序中,我需要读取public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // Add application services. services.AddTransient<IEmailSender, EmailSender>(); services.AddTransient<IHttpContextAccessor, HttpContextAccessor>(); services.AddTransient<UserResolverService>(); services.AddMvc(); } PUT调用的标头信息,并在传递为POST的bean中设置这些信息。目前正在做的事情如下。

@RequestBody

所以我在所有方法中提取标题(POST和PUT)并在不同的实体中设置值。

我的问题是有没有办法解析/ @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) @ResponseBody public ReportRepresentation createDailyReport(@RequestBody ReportEntity reportEntity, @RequestHeader(value= "FIRST_HEAD1", required = false) boolean isHeaderSet, @RequestHeader(value= "SECOND_HEAD2", required = false) Long scondHead) { // Setting the header values into bean properties . } 全局级方法参数中的override并设置这些标题?

2 个答案:

答案 0 :(得分:2)

您可以使用RequestBodyAdvice

例如:

豆:

@Data
public class MyBean {
  private String property;
}

控制器:

@RestController
public class MyController {
  @RequestMapping("/")
  public MyBean get(@RequestBody MyBean myBean) {
    return myBean;
  }
}

顾问:

@ControllerAdvice(annotations = RestController.class)
public class MyRequestBodyAdvisor extends RequestBodyAdviceAdapter {
  @Override
  public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
    return methodParameter.getParameterType() == MyBean.class;
  }

  @Override
  public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
    MyBean myBean = (MyBean)body;
    List<String> strings = inputMessage.getHeaders().get("X-Property");
    myBean.setProperty(strings.get(0));
    return myBean;
  }
}

测试:

$ curl localhost:8080 -d '{}' -X POST -H 'X-Property: myProp' -H 'Content-Type: application/json' -s

输出: {"property":"myProp"}

答案 1 :(得分:1)

我已经实现了与这里提到的@ caco3相同的是我的实现,将值设置为bean。

 @ControllerAdvice
 public class RequestBodyAdviceChain implements RequestBodyAdvice {

 .. Other methods
 @Override
 public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
        Class<? extends HttpMessageConverter<?>> converterType) {

    HttpHeaders headers = inputMessage.getHeaders();

    List<String> emulated = headers.get("FIRST_HEAD1");
    Boolean isEmulated = false;
    Long emulatedUserId = null;
    if (!CollectionUtils.isEmpty(emulated)) {
        isEmulated = Boolean.valueOf(emulated.get(0));
    }

    if (isEmulated) {
        List<String> users = headers.get("SECOND_HEAD2");

        if (!CollectionUtils.isEmpty(users)) {
            emulatedUserId = Long.valueOf(users.get(0));
        }
    }

    if (isEmulated) {
        if (setField(body, Is_Emulated_Field, isEmulated)) {
            setField(body, EmulatedUserId_FIELD, emulatedUserId);
        }
    }

    return body;
 }

/**
 * <p>
 * Method to set the field value for the emulated user and it's id wven
 * though if the fields are defined in the super class.
 */
private static boolean setField(Object targetObject, String fieldName, Object fieldValue) {
    Field field;
    try {
        field = targetObject.getClass().getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        field = null;
    }
    Class superClass = targetObject.getClass().getSuperclass();
    while (field == null && superClass != null) {
        try {
            field = superClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            superClass = superClass.getSuperclass();
        }
    }
    if (field == null) {
        return false;
    }
    field.setAccessible(true);
    try {
        field.set(targetObject, fieldValue);
        return true;
    } catch (IllegalAccessException e) {
        return false;
    }
}
}