用Jersey简单实现的helloworld demo版

来源:互联网 发布:徐州有mac专柜吗 编辑:程序博客网 时间:2024/05/22 09:44

第一步:引包(如果你用maven的话就没必要了)
第二步:写一个资源类
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/helloworld")
public class HelloWorldResource {

 @GET
 @Produces("text/plain")
 public String getClichedMessage() {

  return "Hello World !";
 }
}

第三步:启动 grizzly

public class TestMain {

 public static void main(String args[]) {

  final String baseUri = "http://localhost:9998/";
  final Map<String, String> initParams = new HashMap<String, String>();
  /**
   * creates an initialization parameter that informs the Jersey runtime
   * where to search for root resource classes to be deployed. In this
   * case it assumes the root resource class in the package
   * com.sun.jersey.samples.helloworld.resources
   */
  initParams.put("com.sun.jersey.config.property.packages",
    "com.spring.jpa.hibernate.jersey");
  System.out.println("Starting grizzly...");
  SelectorThread threadSelector = null;
  /**
   * deploys the root resource to the base URI "http://localhost:9998/"
   * and returns a Grizzly SelectorThread. The complete URI of the Hello
   * World root resource is "http://localhost:9998/helloworld".
   */
  try {
   threadSelector = GrizzlyWebContainerFactory.create(baseUri,
     initParams);
  } catch (IllegalArgumentException e1) {
   e1.printStackTrace();
  } catch (IOException e1) {

   e1.printStackTrace();
  }
  System.out.println(String.format(
    "Jersey app started with WADL available at %sapplication.wadl/n"
      + "Try out %shelloworld/nHit enter to stop it...",
    baseUri, baseUri));
  try {
   System.in.read();
  } catch (IOException e) {

   e.printStackTrace();
  }
  threadSelector.stopEndpoint();
  System.exit(0);

 }

}
然侯运行这个程序
第四步:
输入
http://localhost:9998/helloworld
就会显示结果:
HelloWorld!

 

 

原创粉丝点击