一、Hello World
编写一个名为HelloResource的资源
- 资源类(Resource Class):注意,资源类是一个简单的 Java 对象 (POJO),可以实现任何接口。这增加了许多好处,比如可重用性和简单。
- 注释(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。
@Path
:定义资源基 URI。由上下文根和主机名组成,资源标识符类似于 http://localhost:8080/Jersey/rest/hello。@GET:
这意味着以下方法可以响应 HTTPGET
方法。@Produces:
以纯文本方式定义响应内容 MIME 类型。
在 web.xml 文件中定义 Jersey servlet 调度程度
需要的类包:
- jersey-server.jar,
- jersey-core.jar,
- jsr311-api.jar,
- asm.jar
如果报错:com.sun.jersey.spi.service.ServiceConfigurationError: jersey-server-components: A dependent class, org/jvnet/mimepull/MIMEParsingException, of the class com.sun.jersey.multipart.impl.MultiPartReader implementing the provider class java.lang.Object is not found. The provider implementation is ignored.
类包引起的问题,具体不详,只要保持以上4个包绝对没问题。
然后在url中输入http://localhost:8080/contextPath/rest/hello,即可看到“Hello Jersey”的纯文本回复。
二、Root Resource Classes
Root Resource Classes是普通的POJO类,由@Path标注
有一个方法被@Path标注,或被@GET,@PUT,@POST,@DELETE标注。
1、@Path的值 就是 URL路径。
2、@Path可以传递变量,在运行时会被替换掉:
如:
在这个例子上,用户访问这个URL就需要传递username这个参数
如:http://example.com/users/Galileo
然后通过在一个请求方法中标注@PathParam来获得这个参数
3、@Path上定义的参数,可以使用正则表达式
如:@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
此处,如果用户输出的参数不匹配,就会报404(Not Found)错误。
4、@Path中定义的URL前后是否有"/",都不会有影响。
所以在请求URL的末尾有无"/"也不会有影响。
所以http://localhost:8080/JerseyDemo/hello 和
http://localhost:8080/JerseyDemo/hello/ 是一样的