[REST Jersey] @QueryParam Demo

This demo sourced from the jersey tutor. https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e1433 provides the necessary info for you.

HelloWorldResource.java

package com.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
/**
 *
 * @author 
 */
@Path("helloworld")
public class HelloWorldResource {
    public static final String CLICHED_MESSAGE = "Hello World!";
    /*
    @GET
    @Produces("text/plain")
    public String getHello() {
        return CLICHED_MESSAGE;
    }
*/
    @GET
    @Path("/get")
    @Produces("text/plain")
    //@Produces("application/json")
    public String getQueryObj(
        @QueryParam ("featureID") @DefaultValue("0") String fid,
        @QueryParam ("userID") @DefaultValue( "0" ) int uid,
        @QueryParam ("color") @DefaultValue("red") ColorParam clr
        // color default value: green, blue
        ) {
        return new String("QueryParam: {"+ fid + ": " + uid + " : " + clr + "}." + CLICHED_MESSAGE);
    }

}

ColorParam.java

package com.example;
import java.awt.Color;
import javax.ws.rs.WebApplicationException;
import java.lang.reflect.Field;

public class ColorParam extends Color {

    public ColorParam(String s) {
        super(getRGB(s));
    }

    private static int getRGB(String s) {
        if (s.charAt(0) == '#') {
            try {
                Color c = Color.decode("0x" + s.substring(1));
                return c.getRGB();
            } catch (NumberFormatException e) {
                throw new WebApplicationException(400);
            }
        } else {
            try {
                Field f = Color.class.getField(s);
                return ((Color)f.get(null)).getRGB();
            } catch (Exception e) {
                throw new WebApplicationException(400);
            }
        }
    }
}

Call it after the above java files are packaged as a war deployed in tomcat container.

http://hostname:8080/simple-service-webapp/webapi/helloworld/get?featureID=12
QueryParam: {12: 0 : com.example.ColorParam[r=255,g=0,b=0]}.Hello World!

http://hostname:8080/simple-service-webapp/webapi/helloworld/get?featureID=12&userID=123
QueryParam: {12: 123 : com.example.ColorParam[r=255,g=0,b=0]}.Hello World!

http://hostname:8080/simple-service-webapp/webapi/helloworld/get?featureID=12&userID=123&color=yellow
QueryParam: {12: 123 : com.example.ColorParam[r=255,g=255,b=0]}.Hello World!


curl -v -i -o out -X GET "http://localhost:8080/simple-service-webapp/webapi/helloworld/get?featureID=12&userID=123"


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值