in Apache CXF, REST, Web Services

[Tutorial] RESTful web services with CXF

This is a short follow-up to a previous post about Web Services with CXF.

Developing RESTful web services with CXF is quite easy. Here I quickly explore 2 ways to do it.

1) HTTP Binding :

One way to do it is to use HTTP Binding as described here : https://cwiki.apache.org/CXF20DOC/http-binding.html

The spring bean xml configuration file (cxf.xml) is modified to add the bindingUri parameter and also the  JaxWsServiceFactoryBean factory :

cxf.xml :

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:jaxws="http://cxf.apache.org/jaxws"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://cxf.apache.org/jaxws
 http://cxf.apache.org/schemas/jaxws.xsd
">

 <import resource="classpath:META-INF/cxf/cxf.xml" />
 <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
 <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
 <import resource="classpath:META-INF/cxf/cxf-extension-http-binding.xml"/>

 <jaxws:endpoint id="calcBMI"
 implementor="com.company.bmi.services.IBMICalculatorImpl"
 address="/cxfBmi"
 bindingUri="http://apache.org/cxf/binding/http">
 <jaxws:serviceFactory>
 <bean>
 <property name="wrapped" value="true" />
 </bean>
 </jaxws:serviceFactory>
 </jaxws:endpoint>

</beans>

Then add to the interface the annotations from the Java Rest Annotations codehaus project :

IBMICalculator.java:
package com.company.bmi.services;

import javax.jws.WebParam;
import javax.jws.WebService;

import org.codehaus.jra.Get;
import org.codehaus.jra.HttpResource;

@WebService
public interface IBMICalculator {

 @Get
 @HttpResource(location = "/computeBMI/{weight}/{height}")
 public  double computeBMI(@WebParam(name="weight") double weight, @WebParam(name="height") double height) ;
}

In the JBoss console, we can observe that the mapping is done :

20:21:59,250 INFO  [ReflectionServiceFactoryBean] Creating Service {http://services.bmi.company.com/}IBMICalculatorImplService from class com.company.bmi.services.IBMICalculator
20:21:59,469 INFO  [JRAStrategy] Mapping method computeBMI to resource /computeBMI/{weight}/{height} and verb GET
20:21:59,512 INFO  [ServerImpl] Setting the server's publish address to be /cxfBmi
20:21:59,528 INFO  [ContextLoader] Root WebApplicationContext: initialization completed in 710 ms

However, as stated in CXF web site,  the “binding has been deprecated and is likely to be removed from CXF in one of its future releases.” So it’s best to use a different way before it’s too late !

2) JAX-RS

An alternative way is to use the implementation of the JAX-RS api provided by CXF. So all you need to do is annotate the class with the JAX-RS annotations and modify the spring configuration file (called cxf.xml in the example of my previous post).

cxf.xml :


<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:jaxrs="http://cxf.apache.org/jaxrs"
 xmlns:jaxws="http://cxf.apache.org/jaxws"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://cxf.apache.org/jaxrs
 http://cxf.apache.org/schemas/jaxrs.xsd
 http://cxf.apache.org/jaxws
 http://cxf.apache.org/schemas/jaxws.xsd
">

 <import resource="classpath:META-INF/cxf/cxf.xml" />
 <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
 <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
 <import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/>

<jaxws:endpoint id="calcBMI"
 implementor="com.company.bmi.services.IBMICalculatorImpl"
 address="/cxfBmi"  />

 <jaxrs:server id="bmiservice" address="/">
 <jaxrs:serviceBeans>
 <ref bean="IBMICalculatorImpl"/>
 </jaxrs:serviceBeans>
 </jaxrs:server>

 <bean id="IBMICalculatorImpl"/>

</beans>

And annotate the class that implements the interface :

IBMICalculatorImpl.java :

package com.company.bmi.services;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Produces("text/plain")
public class IBMICalculatorImpl implements IBMICalculator{

 //@Override
 @GET
 @Path("/computeBMI/{weight}/{height}")
 public double computeBMI(@PathParam("weight") double weight, @PathParam("height") double height) {
 return weight / (height * height);
 }

}

IBMICalculatorImpl computeBMI(weight, height) is mapped to an HTTP GET request on /computeBMI/{weight}/{height}. This request contains 2 parameters : weight and height.

The data format, defined with the annotation @Produces, is plain text but it could be XML, JSON…

So we see that very little is needed to transform the IBMICalculator service to make it available in the form of an HTTP GET method at the following URL : http://localhost:8085/BMI/services/computeBMI/75/170 . The result is displayed in plain text :

Rest

Link : https://cwiki.apache.org/CXF20DOC/restful-services.html

Webmentions

  • jaki biustonosz b臋dzie najlepszy do sukienki bez plec贸w

    jaki biustonosz b臋dzie najlepszy do sukienki bez plec贸w

    lista desideri carta vivasantoro costume da bagno bimba gorjuss piscina mare ps bikini bambinapigiama estivo uomo yamamaycoperte in pile personalizzate

  • boss down parka

    boss down parka

    prada eyeglasses vpr 03q pdn sportted havana pink 52 18 140 acetatethom browne designer glassesilluminata eyewear emporio armani sunglasses emporio armanidolce gabbana 1162 womens ladies designer full rim spring hinges eyeglasses eye glasses

  • nike air max 97 womens mens nike air max 97 hyp darkblue beige shoes trainer

    nike air max 97 womens mens nike air max 97 hyp darkblue beige shoes trainer

    black buckle strap vegan leather platform heel bootssequin flip flops sale off66 discountedshoes worlds a stage wedges blacknew balance 442 womens low profile sneakers shoes wide width

  • stock photo young school boy with backpack holding a book

    stock photo young school boy with backpack holding a book

    girls converse grey all star print t shirt t shirts tops girlsshoes nike free beautiful cool sneakers sneaks so rad grunge black white grey grey perfect nikerihanna yellow platform creepers. m 5united states nike air jordan 10 retro bg men women white…

  • petite strapless high waisted bandeau bikini

    petite strapless high waisted bandeau bikini

    older girl jumpsuits playsuitshelen deep plunge wrap over maxi playsuit2019 wholesale 2018 hot design luxury full length female jumpsuitvictoria s secret angel credit card manage your account comenity

  • toddler newborn kid boy girl strap romper jumpsuit playsuit sunsuit outfits summer cotton linen yellow rompers 0

    toddler newborn kid boy girl strap romper jumpsuit playsuit sunsuit outfits summer cotton linen yellow rompers 0

    this is what were getting for our little man to come home inlets get married sara is in love withladies suits for wedding party indian dresses for teenage girls to wear to a wedding nafadidas by stella mccartney women footwear sneakers yellow

  • zapatos pepitos lona puntera azules

    zapatos pepitos lona puntera azules

    miu miu oversized cable knit sweater brownsnike shoes womens wmns air max thea prm black black sail dark grey mama zondersigerson morrison neon fuchsia jelly rubber kitten heel thong flip flops sandals sz5uk shoes retro mans lacoste sport black trainin…

  • barbell and plates

    barbell and plates

    womens halston heritage jumpsuits rompers free shippingmen never summer frosthammer thermal lined hooded flannel shirt standard fit black white redplans for the weddings with additional trendy kohls wedding guest dresses with additional 15 best dresses…

  • ipanema anatomic temas vii noir au centre commercial

    ipanema anatomic temas vii noir au centre commercial

    c茅line paris tie bag cognac blue satchel italysalvatore ferragamo women medium wave flap bagsalvatore ferragamo sale beltferragamo shoes outletconverse city bag charcoalclassic backpack large

  • at the gorillaz sound system event at londons 100 club. the sneakers are finally making the trip stateside

    at the gorillaz sound system event at londons 100 club. the sneakers are finally making the trip stateside

    nike moon racer blackcamron dmx run 10 killa cam reebok collaboration harlem nightsreebok zigtech big n fast foggy greyvans classic slipon baby blue checkerboard

  • phone case iphone xs max

    phone case iphone xs max

    sele莽茫o alem茫 uniformecalcinha fio dental sensualmejores tienda camisetas casa camiseta barcelona 2017 2018 rojo azultouca c pompom em modelo simples no

  • details about adidas mens d rose 8 basketball shoe black blue white sports breathable

    details about adidas mens d rose 8 basketball shoe black blue white sports breathable

    crocs capri v flip 202502 womens toe post summer sandal robin elt shoeschaco mens fashion shopstyleh枚ga sneakers dam l氓gt pris black guess freda wedge sneakerstrappy rhinestone platform high heels

  • camisas polo luxo.marcas pre莽o de f谩brica pre莽o p kit com 10 r 60

    camisas polo luxo.marcas pre莽o de f谩brica pre莽o p kit com 10 r 60

    trespass rusler mens down jacket with hood warm puffer in green navypersonalized锛歴tamped laser etched. custom personalized real leather keychain. the text on the keychain can be stamped or laser etchedlouis vuitton limited edition python galliera pm ba…

  • texas longhorns apparel nike

    texas longhorns apparel nike

    gel quantum 360 mxkd 6 nsw lifestyle all white sport redvans womens authentic lo pro womens shoe silver sconce lilacnike womens dunk low white university blue shoes

  • guess g lux large tote schultertasche shopper tasche snow multi wei脽

    guess g lux large tote schultertasche shopper tasche snow multi wei脽

    joyeux short homme bermuda marron bermuda living bermudalave linge achat machine 脿 laver pas cherla modeuse spartiates montantes dor茅es 脿 lacet pas cher achat20 ways to wear stan smiths robe basket

  • abiti etnici da cerimonia abiti in pizzo

    abiti etnici da cerimonia abiti in pizzo

    scoop black lace evening gown high low prom dresses plus size ball gown women formal dress long sleeves party dresses robe de soiree ladies dresses ukplus size yoga clothes56 off 2019 plus size lace up bodycon skirthudson jeans olivia super skinny ankl…

  • big bird sports uk promotional products. flubber shopper tote bag

    big bird sports uk promotional products. flubber shopper tote bag

    backpacking the philippines 1 week palawan itinerary on a budgetsouthport soft leather duffle bag by cobb co online the iconic australiafall is a season loaded with fun and occasions parties in clubssling backpacks

  • 贸culos feminino

    贸culos feminino

    sunglasses ray ban rb 3648 003 i2 the marshal 54 21 unisex argentoculos raund rosa lente de cristal bijouterias贸culos sem grau lente clara dia noite trabalho importado r 39alian莽as brasilia em ouro 18k para casamento alian莽as bras铆lia

  • can t miss bargains on royalty by ymi womens roll cuff frayed hem

    can t miss bargains on royalty by ymi womens roll cuff frayed hem

    10 cute outfits ideas for baby boys birthday partyshop journee collection womens tess high heel platform clogsdiscouts lanvin wholesale at lanvin online shopdapperlads lito boys charcoal dress pants toddler

  • italian breil milano stainless steel sport style chronograph watch 100m wr 10atm

    italian breil milano stainless steel sport style chronograph watch 100m wr 10atm

    salvatore ferragamo salvatore ferragamo watch fq5050014 quartz white stainless steelchopard classic racing watchesadidas other womens adidas floral tracksuit amazinglyst guess coats wool patch pocket hooded bomber in gray for men

  • automatic sport watch

    automatic sport watch

    purple air max 2016 hot sale nike air zoom pegasus 34 mens online vr402486 top ranknike nike air force 1 06 infant trainerstraps short v neck navy blue homecoming dress on storenvywomens saddle shoes

  • yemm83 p谩nsk谩 obuv nike air max 1 essential r.45 akce 6582406071 膷ern谩

    yemm83 p谩nsk谩 obuv nike air max 1 essential r.45 akce 6582406071 膷ern谩

    elefanten dom谩c铆 obuvstylov媒 m臎stsk媒 batoh randyfialov茅 spole膷ensk茅 拧aty lady v london audrey lady v londonnumoco elegantn茅 modr茅 koktejlov茅 拧aty

  • g shock ga 110cm 9a metallic camouflage watches yellow

    g shock ga 110cm 9a metallic camouflage watches yellow

    chanel j12 42mm black ceramic diamond watch chanel watchescasio g shock gw m5600bc video reviewbulgari octo finissimo tourbillon skeleton modelduke blue devils hockey jersey adult xxl mens

  • hive91 women checkered casual red

    hive91 women checkered casual red

    buy rolex yacht master 116622genuine leather strap for iwatch 38mm 42mm band bracelet replacement wristband for apple watch double wrist5085fb 1140 52b blancpain fifty fathomsnatural bamboo leather wood watch

  • citizen eco drive radio controlled mens watch chronograph titanium image 1

    citizen eco drive radio controlled mens watch chronograph titanium image 1

    贸culos de sol polo london club oncinha marrom laranjarel贸gio technos dourado grande cron贸grafo legacy. carregandotenis ea7 emporio armani azulrayban wayfarer colorido promo莽茫o dia das crian莽as em brasil

  • valeur sup茅rieure lunettes de vue swarovski sk 5245 048 marron monture femmes marron marron transparent

    valeur sup茅rieure lunettes de vue swarovski sk 5245 048 marron monture femmes marron marron transparent

    asics descubre online su gran cat谩logo de zapatillas en zalandovendo loja f铆sica e site de cal莽ados e acess贸rios na rua tenente virmondest锚nis nike shox nz masculino preto r 240t锚nis nike downshifter 8 feminino cinza gaston paqueta esportes

  • diesel slim fit jeans 198 buy ss19 online fast global delivery

    diesel slim fit jeans 198 buy ss19 online fast global delivery

    avengers titan hero series 12 packits hallmark movie season shirt christmas movie shirt womens christmas shirt holiday tee christmas shirts forcanvas messenger bags 30624 gootiumwomen boots black carvela kurt geiger slow new arrivals

  • stivaletti bassi con originale lavorazione traforata nero 8335 scarpe donna

    stivaletti bassi con originale lavorazione traforata nero 8335 scarpe donna

    trousse daccessoires v015367 synth茅tique essentials trousse daccessoires v015367 synth茅tique essentials. desigual茅charpe rouge en laine aqualogiaecharpe burberry forumemporio armani top handle grainy sac bandouli猫re nero

  • goatee templates b beard bro king shaping tool man gentleman beard trimmer

    goatee templates b beard bro king shaping tool man gentleman beard trimmer

    mokale 5 pieces professional eyeshadow brush makeup kit designer cosmetic eye makeup tools with luxury caseconair accessories conair pro thermacell cordless hair straightenerboro plus aloe vera coconut moisturizing face wash reviewayu full glam eyes gi…

  • adidas 2015 new design lu7mni1b duramo lea cushioned running shoes black mens running

    adidas 2015 new design lu7mni1b duramo lea cushioned running shoes black mens running

    adidas neo erkeknike pijama gr l in nordrhein westfalen hagen ebay kleinanzeigennike bayan g眉nl眉k ayakkab谋 air huarache run prmclassic canvas sneakers shoes men casual shoes comfortable round toe lace up flat shoes fashion

  • danmark t shirt 179 kr

    danmark t shirt 179 kr

    k酶b top model make up bogtommy hilfiger hvid skjorte bright white bl氓continental 80 sko clear pink scarlet collegiate navygrisport arbejdssko uden sikkerhed nu ekstra nedsat

  • merrell kvinde siena sandal sort

    merrell kvinde siena sandal sort

    kompletn茅 pecifik谩cie. d谩mske elegantn茅 nohavice vero modadansk online modebutik forudser st酶rre underskudrolly toys dtsk媒 lapac铆 traktor john deere 7930 lapac铆fiskeri martstur til st. vejle 氓

  • 銉嬨儱銉笺儛銉┿兂銈?銉儑銈c兗銈?銈︺偐銉笺偔銉炽偘銈枫儱銉笺偤 new balance ww550gy12e 闈?銈般儸銉?ww550 銇忋仱 2018骞寸鍐?nb

    銉嬨儱銉笺儛銉┿兂銈?銉儑銈c兗銈?銈︺偐銉笺偔銉炽偘銈枫儱銉笺偤 new balance ww550gy12e 闈?銈般儸銉?ww550 銇忋仱 2018骞寸鍐?nb

    鐢诲儚 銉娿偆銈?銈ㄣ偄銈搞儳銉笺儉銉? 銉椼儸銈ゃ偑銉?銈儶銈搞儕銉?vs. 2013寰╁埢銉儑銉伄姣旇純 銈广儖銉笺偒銉笺偊銈┿兗銈?/a>penalty 瓒呯編鍝?penalty銉斻偣銉嗕笂涓嬨偦銉冦儓銇€氳博 by 12 28 1 3浼戙伩undercover 銈兂銉€銉笺偒銉愩兗 銇畊ndercover 銈兂銉€銉笺偒銉愩兗 nike nike gyakusou 銉°兂銈恒伄闈?/a>teva 銉嗐儛 銇?銉欍儞銉?銈儍銈?銉嗐儛 銈儍銈?銉忋儶銈便兗銉? 銈广儩銉笺儎

  • articles on self improvement

    coaching Group

    Celinio

  • help love my partner

    love Back

    Celinio

  • Difficult relationships

    Bayareanonprofits.Xyz

    Celinio

  • Eternal life

    bong88Web.com

    Celinio

  • ending a relationship

    relationship Advice

    Celinio