您现在的位置:首页 >> 前端 >> 内容

[REST Jersey] @QueryParam Demo

时间:2013/9/4 15:01:43 点击:

  核心提示:HelloWorldResource.javapackage com.example;import javax.ws.rs.GET;import javax.ws.rs.Path;import jav...
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.

 
https://hostname:8080/simple-service-webapp/webapi/helloworld/get?featureID=12  
QueryParam: {12: 0 : com.example.ColorParam[r=255,g=0,b=0]}.Hello World!  
  
https://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!  
  
https://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!  

 

Tags:[R RE ES ST 
作者:网络 来源:不详
  • 上一篇:CSS的Hack大搜集
  • 下一篇:HTML DOM事件