jesery與spring集成java
一、jersey在maven中的依賴包web
<!-- jersey 相關的包 --> <!-- jersey客戶端相關包--> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.18.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.18.1</version> </dependency> <!-- jersey 服務器端相關包--> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-bundle</artifactId> <version>1.18.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.18.1</version> </dependency> <!-- genson處理服務器端json數據的重要jar--> <dependency> <groupId>com.owlike</groupId> <artifactId>genson</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <classifier>jdk15</classifier> <version>2.4</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-spring</artifactId> <version>1.18.1</version> <!-- 去除自帶的spring版本 --> <exclusions> <exclusion> <artifactId>spring-core</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-beans</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-context</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-web</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-aop</artifactId> <groupId>org.springframework</groupId> </exclusion> <exclusion> <artifactId>spring-webmvc</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <!-- ****jersey 相關包****end*** -->
2.web.xml配置:spring
<servlet> <servlet-name>JerseyServlet</servlet-name> <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <!-- 系統啓動時掃描的包的路徑,指定多個包請用逗號隔開--> <param-value>com.tianque.locationtalk.api</param-value> </init-param> <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> </servlet>
3.參數支持和接口數據庫
@PathParam用來表示Restful風格下在URL中的id等標識。json
@QueryParameter能夠轉換任何有以String爲參數的構造函數的類,還能夠設定defaultValue, 當參數爲空時會自動拋異常api
@POST+ @Consumes 以POST方式傳遞XML或JSON編碼的Java對象瀏覽器
@Context UriInfo,@Context HttpHeaders, @Context HttpServletRequest 獲取靈活的,不固定的參數. 能夠從原版HttpServletRequest中獲取,也能夠用封裝好的更方便的UriInfo和HttpHeaders.服務器
4.使用Jackson處理JSONmvc
在classpath里加入jersey-json.jar後,在服務端,web.xml裏SpringServlet的定義要加入app
<init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param>
5.要生成rest的service類
pojo對象,必須加入@XmlRootElement,用於標識對象轉化成xml或者json
package com.xxx.locationtalk.api; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class User { public Long userId; public String userName; public String nickName; public User(){ } public User(Long userId,String userName,String nickName){ this.userId =userId; this.userName=userName; this.nickName=nickName; } }
具體映射出去的service類,其中調用了某個spring的service去讀取數據庫,各個不一樣的url實現了xml的對象輸出,json對象的輸出,以及list對象的輸出,以及一些賦值操做和json對象賦值操做。
package com.xxx.locationtalk.api; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.xxx.locationtalk.domain.MobileNumber; import com.xxx.locationtalk.service.MobileNumberService; @Component @Scope("request") @Path("/bookapi") public class BookService { @Autowired private MobileNumberService mobileNumberService; public MobileNumberService getMobileNumberService() { return mobileNumberService; } public void setMobileNumberService(MobileNumberService mobileNumberService) { this.mobileNumberService = mobileNumberService; } //外部傳過來的參數 @QueryParam("id") String userId; @GET @Produces(MediaType.TEXT_PLAIN) public String helloWorld() { String ret = "Hello World!"; return ret; } // 子路徑 @Path("getUsers") @GET @Produces( {MediaType.APPLICATION_XML }) public List<User> getUsers() { List<User> users = new ArrayList<User>(); for (long i = 1; i < 5; i++) { User user = new User(); user.userId=(i); user.userName=("yuhan" + i); user.nickName=("supben" + i); users.add(user); } return users; } // 子路徑 @Path("getUserById") @GET @Produces( {MediaType.APPLICATION_JSON }) public User getUsersById(){ User user = new User(); //使用spring的類讀取數據庫信息,隨便賦值 MobileNumber object=mobileNumberService.getMobileNumberById(Long.valueOf(userId)); user.userId=object.getId(); user.userName=object.getUsersName(); user.nickName=object.getMobileNumber(); return user; } @Path("getUserXmlById") @GET @Produces( {MediaType.APPLICATION_XML }) public User getUsersByIdForXML(){ User user = new User(); MobileNumber object=mobileNumberService.getMobileNumberById(Long.valueOf(userId)); user.userId=object.getId(); user.userName=object.getUsersName(); user.nickName=object.getMobileNumber(); return user; } @Path("setUser") @PUT @Produces( {MediaType.APPLICATION_JSON }) public User setUser(User user){ if(user==null){ System.out.println("數值爲空!!"); user.userId=(13486197987L); user.userName=("yuhan"); user.nickName=("supben"); }else{ System.out.println("user.userId="+user.userId); System.out.println("user.userName="+user.userName); System.out.println("user.nickName="+user.nickName); user.userId=(user.userId); user.userName=(user.userName); user.nickName=(user.nickName); } return user; } // 子路徑 @Path("getUserByXML") @GET @Produces( {MediaType.APPLICATION_XML }) public User getUserByIdWithXML() throws UnsupportedEncodingException{ User user = new User(); user.userId=(10000L); user.userName=URLEncoder.encode(("哈哈"), "utf-8"); user.nickName=URLEncoder.encode(("老色狼"), "utf-8"); return user; } }
而後經過瀏覽器發佈出去,在瀏覽器中便可經過
http://localhost:8080/api/bookapi/getUserByXML得到一個xml格式的對象
http://localhost:8080/api/bookapi/setUser能夠對一個user對象進行賦值
http://localhost:8080/api/bookapi/getUserXmlById能夠傳入一個id參數,得到一個xml格式的對象
6.client的demo演示
package com.xxx.locationtalk.api; import java.io.UnsupportedEncodingException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider; public class ClientDemo{ public static void main(String[] args) throws UnsupportedEncodingException{ ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client c = Client.create(clientConfig); String url = "http://localhost:8080/api/bookapi"; WebResource r = c.resource(url); User user = new User(); user.userId=1000L; user.userName="江江123"; user.nickName="老色狼"; System.out.println("狀態碼="+r.path("setUser").accept(new String[] {MediaType.APPLICATION_JSON}). entity(user, MediaType.APPLICATION_JSON).put(ClientResponse.class).getStatus()); MultivaluedMap<String, String> param = new MultivaluedMapImpl(); param.add("userId", "10000"); param.add("userName", "髒話"); param.add("nickName", "髒話色狼"); System.out.println(r.queryParams(param) .type(MediaType.APPLICATION_JSON).post(String.class)); } }
這個client演示了倆種rest的實現方法
輸入URL Query參數 client.path("/xxx").queryParam("name", name)
輸入JSON編碼的對象 client.path("/xxx").entity(user, MediaType.APPLICATION_JSON)