有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring SOAP Web服务请求日志中XML请求有效负载的元素

作为安全需求的一部分,我需要在使用log4j记录XML SOAP请求负载时屏蔽敏感字段值,如creditcard number等。 目前,我正在使用以下代码记录XML请求负载:

public void printDebugXMLPayload(MyWSRequest request) throws JAXBException
{
     StringWriter sw = new StringWriter();
    JAXBContext jaxbContext = JAXBContext.newInstance(MyWSRequest .class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(request,  new StreamResult(sw));
    logger.debug(sw.toString());
  
}

上面的代码记录了完整的XML请求负载,但我需要屏蔽敏感字段。 请你给我引路好吗。非常感谢! 注意:我在@XmlElement级别找不到任何用于屏蔽字段的配置


共 (1) 个答案

  1. # 1 楼答案

    一种方法是创建自定义注释,并使用reflection类查看字段是否需要屏蔽。 这是一个简单的例子

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Mask {
    }
    
    public class MyWSRequest {
        @Mask
        private String item1;
    }
    
    public void printDebugXMLPayload(MyWSRequest request) throws JAXBException {
        for (Field f : request.getClass().getDeclaredFields()) {
            if (f.isAnnotationPresent(Mask.class)) {
                logger.debug("***");
            } else {
                f.setAccessible(true);
                logger.debug(f.get(request));
            }
        } 
    }