有 Java 编程相关的问题?

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

JavaSOAP响应模式

我现在正在探索SOAP WS,并创建了一个非常简单的 我将作为Web服务公开的类

@WebService
public class StudentWS {   
    @WebMethod
    public Student getStudent(){
      Student stud = new Student();
      stud.setId(99);
      stud.setFirstName("John");
      stud.setLastName("Doe");
      stud.setGpa(2.1);
      return stud;
    }
}

当我调用此Web服务时,返回的SOAP响应如下 这种格式

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:getStudentResponse xmlns:ns2="http://annotation/">
         <return>
            <firstName>John</firstName>
            <gpa>2.1</gpa>
            <id>99</id>
            <lastName>Doe</lastName>
         </return>
      </ns2:getStudentResponse>
   </S:Body>
</S:Envelope>

我的问题是,是否有某种方式可以影响SOAP响应以遵循以下某种模式

<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
   <S:Body>
      <ns2:getStudentResponse xmlns:ns2="http://annotation/">
        <student gpa="2.1">
            <id>99</id>
            <name>
                <firstName></firstName>
                <lastName></lastName>
            </name>
        </student>
      </ns2:getStudentResponse>
   </S:Body>
</S:Envelope>

我的数据来自这样一个POJO类

@XmlRootElement
public class Student {
    private int id;
    private String firstName;
    private String lastName;
    private double gpa;
    //getters and setters
}

谢谢


共 (2) 个答案

  1. # 1 楼答案

    如果您想将gpa作为属性,您必须创建两个类并使用@XmlAttribute注释

    本例中的注释只是说明性的

    public class Student {
    
        @XmlAttribute
        private String gpa;
    
        @XmlElement
        private String id;
    
        @XmlElement
        private Name name;
    
    }
    
    public class Name {
    
        @XmlElement
        private String firstName;
    
        @XmlElement
        private String lastName;
    
    }
    
  2. # 2 楼答案

    我不知道您是否已经解决了这个问题,但我最近开始研究WS,并且面临着完全相同的问题。不管怎样,我还是解决了它:

    您需要创建2个Bean类 豆1

    public class ResultBean {
    
        private String id;
            private String student;
        private StudentName name = new StudentName ();
    
    //corresponding getter setter methods
        ....
            ....
            ....
    }
    

    豆子2

    public class StudentName {
    
        private String firstName;
        private String lastName;
    //corresponding getter setter methods
        ....
            ....
    }
    

    像你一样继续。 我希望这能解决你的问题