这两天有幸玩了把Jersey,Jersey是RESTful的封装,通过Jersey可以快速地开发出web service。目前,Jersey在Git上的最新版本是2.8,我实际用到了Jersey2.7. 废话少说,动手!
1.新建Maven工程
打开eclipse,new->project->Maven Project
next->输入'maven-archetype-webapp',选择搜索出来的选项,next
设定groupid,artifactid,package,Finish
2.修改pom.xml文件
主要是添加Jersey jar包,只需要添加jersey-container-servlet即可,另外,为保证使用jdk1.7编译执行,添加plugin,同时保留系统原有的junit包,具体配置如下
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8</version> <scope>test</scope> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>2.7</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project>
3.添加Jersey Servlet至web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="false" version="3.0"> <servlet> <servlet-name>org.glassfish.jersey.examples.helloworld_servlet.MyApplication</servlet-name> </servlet> <servlet-mapping> <servlet-name>org.glassfish.jersey.examples.helloworld_servlet.MyApplication</servlet-name> <url-pattern>/jaxrs/*</url-pattern> </servlet-mapping> </web-app>
4.创建ResourceConfig继承类
创建MyApplication类,同时,注册一个resource类,用于实现真正的发送请求
package com.zliang.jerseyhelloworld; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; @ApplicationPath("jaxrs") public class MyApplication extends ResourceConfig { public MyApplication(){ register(MyHelloWorldResource.class); } }
5.创建Resource类用于实现Restful
package com.zliang.jerseyhelloworld; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("hello") public class MyHelloWorldResource { @GET @Produces(MediaType.TEXT_PLAIN) public String sayHello(){ return "hello world!"; } }
6.创建index.jsp
实际上是在页面上加一个链接,能够让用户通过这个链接call restful
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Hello Jersey</title> </head> <body> click me <a href="jaxrs/hello">hello jersey</a> </body> </html>
7.结果