×
☰ See All Chapters

XmlElement - make input mandatory in web service

In our previous chapters we learnt to accept input from clients and return certain data from web service. In some cases we have to make input to web service field optional or mandatory. To achieve this we have support from @XmlType and @XmlElement annoatations. To make the field mandatory we have to set the required attribute of @XmlElement to true.

Follow the below example on how to use @XmlType and @XmlElement annotations in web service.

Person.java

package com.java4coding;

 

import java.io.Serializable;

 

import javax.xml.bind.annotation.XmlElement;

import javax.xml.bind.annotation.XmlType;

 

@XmlType(name="SampleRequestType", propOrder={"age", "name", "id"})

public class Person implements Serializable{

 

    private String name;

    private int age;

    private int id;

 

    @XmlElement(name="name", required=true)

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    @XmlElement(name="age", required=true)

    public int getAge() {

        return age;

    }

 

    public void setAge(int age) {

        this.age = age;

    }

 

    @XmlElement(name="id", required=true)

    public int getId() {

        return id;

    }

 

    public void setId(int id) {

        this.id = id;

    }

     

    @Override

    public String toString(){

        return id+"::"+name+"::"+age;

    }

 

}

PersonService.java

package com.java4coding;

 

import javax.jws.WebMethod;

import javax.jws.WebParam;

import javax.jws.WebService;

import javax.jws.soap.SOAPBinding;

import javax.jws.soap.SOAPBinding.Style;

 

@WebService

@SOAPBinding(style = Style.RPC)

//@SOAPBinding(style = Style.DOCUMENT)

public interface PersonService{

 

        @WebMethod

        Person getPerson(@WebParam(name = "params")Person person);

 

}

PersonServiceImpl.java

package com.java4coding;

 

import javax.jws.WebParam;

import javax.jws.WebService;

import javax.xml.bind.annotation.XmlElement;

 

//Service Implementation

@WebService(endpointInterface = "com.java4coding.PersonService")

public class PersonServiceImpl implements PersonService{

 

        @Override

        @XmlElement(required = true)

        public Person getPerson(@WebParam(name = "params")Person person) {

                return person;

        }

}

PersonPublisher.java

package com.java4coding;

 

import javax.xml.ws.Endpoint;

 

public class PersonPublisher{

 

        public static void main(String[] args) {

          Endpoint.publish("https://localhost:7779/ws/person", new PersonServiceImpl());

          System.out.println("done");

  }

}

Output:

To get output run PersonPublisher.java as java application.

Access the web services at "https://localhost:7779/ws/person?wsdl"

 


All Chapters
Author