weizi2012

weizi2012

jersey webservice 实例

1.       准备jersey webservice框架搭建需要的jar

2.       新建一个java web项目

3.       添加spring支持

4. 修改web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <listener>

       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

    <context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>classpath*:applicationContext.xml</param-value>

    </context-param>

    <!-- Jersey 配置 -->

    <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.jw.api.service</param-value>

          

       </init-param>

       <init-param>

           <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>

           <param-value>true</param-value>

       </init-param>

       <load-on-startup>1</load-on-startup>

    </servlet>

 

    <servlet-mapping>

       <servlet-name>JerseyServlet</servlet-name>

       <url-pattern>/api/*</url-pattern>

    </servlet-mapping>

 

    <welcome-file-list>

       <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

</web-app>

 

5. 新建一个applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans

    xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:p="http://www.springframework.org/schema/p"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 

 

</beans>

 

6.           jersey  webservice 服务端实例代码:
a. BookService.java
/**

7.            * @Probject Name: jerseyDemo

8.            * @Path: com.jw.api.serviceBookService.java

9.            * @Create By v-jiangwei

10.        * @Create In 2012-9-3 下午05:11:48

11.        * TODO

12.        */

13.       package com.jw.api.service;

14.        

15.       /**

16.        *

17.        * @Class Name BookService

18.        * @Author v-jiangwei

19.        * @Create In 2012-9-3

20.        */

21.        

22.       import java.io.UnsupportedEncodingException;

23.       import java.net.URLEncoder;

24.       import java.util.ArrayList;

25.       import java.util.List;

26.        

27.       import javax.ws.rs.GET;

28.       import javax.ws.rs.PUT;

29.       import javax.ws.rs.Path;

30.       import javax.ws.rs.Produces;

31.       import javax.ws.rs.QueryParam;

32.       import javax.ws.rs.core.MediaType;

33.        

34.        

35.       @Path("/bookapi")

36.       public class BookService {

37.               

38.                //外部传过来的参数

39.                @QueryParam("id") String userId;

40.        

41.                @GET

42.                @Produces(MediaType.TEXT_PLAIN)

43.                public String helloWorld() {

44.                          String ret = "Hello World!";

45.                          return ret;

46.                }

47.               

48.                // 子路径

49.                @Path("getUsers")         

50.                @GET

51.                @Produces( {MediaType.APPLICATION_XML })

52.                public List<User> getUsers() {

53.                          List<User> users = new ArrayList<User>();

54.                          for (long i = 1; i < 5; i++) {

55.                                   User user = new User();

56.                                   user.userId=(i);

57.                                   user.userName=("yuhan" + i);

58.                                   user.nickName=("supben" + i);

59.                                   users.add(user);

60.                          } 

61.                          return users;

62.                } 

63.               

64.                @Path("getJsonUsers")

65.                @GET

66.                @Produces( {MediaType.APPLICATION_JSON })

67.                public List<User> getJsonUsers() {

68.                          List<User> users = new ArrayList<User>();

69.                          for (long i = 1; i < 5; i++) {

70.                                   User user = new User();

71.                                   user.userId=(i);

72.                                   user.userName=("yuhan" + i);

73.                                   user.nickName=("supben" + i);

74.                                   users.add(user);

75.                          } 

76.                          return users;

77.                }

78.               

79.                // 子路径

80.                @Path("getUserById")

81.                @GET

82.                @Produces( {MediaType.APPLICATION_JSON })

83.                public User getUsersById(){

84.                          User user = new User();

85.                          //使用spring的类读取数据库信息,随便赋值

86.                          user.userId=3l;

87.                          user.userName="cccc";

88.                          user.nickName="zhangsan";

89.                          return user;

90.                }

91.                @Path("getUserXmlById")

92.                @GET

93.                @Produces( {MediaType.APPLICATION_XML })

94.                public User getUsersByIdForXML(){

95.                          User user = new User();

96.                    user.userId=2l;

97.                          user.userName="cccc";

98.                          user.nickName="zhangsan";

99.                          return user;

100.             }

101.             @Path("setUser")

102.             @PUT

103.             @Produces( {MediaType.APPLICATION_JSON })

104.             public User setUser(User user){

105.                       if(user==null){

106.                                System.out.println("数值为空!!");

107.                                user.userId=(13486197987L);

108.                                user.userName=("yuhan");

109.                                user.nickName=("supben");

110.                       }else{

111.                                System.out.println("user.userId="+user.userId);

112.                                System.out.println("user.userName="+user.userName);

113.                                System.out.println("user.nickName="+user.nickName);

114.                                user.userId=(user.userId);

115.                                user.userName=(user.userName);

116.                                user.nickName=(user.nickName);           

117.                       }

118.     

119.                       return user;

120.             }

121.             // 子路径

122.             @Path("getUserByXML")

123.             @GET

124.             @Produces( {MediaType.APPLICATION_XML })

125.             public User getUserByIdWithXML() throws UnsupportedEncodingException{

126.                       User user = new User();

127.                       user.userId=(10000L);

128.                       user.userName=URLEncoder.encode(("哈哈"), "utf-8");

129.                       user.nickName=URLEncoder.encode(("老色狼"), "utf-8");

130.                      

131.                       return user;

132.             }

133.            

134.             // 子路径

135.             @Path("getUserByIdWithXML")

136.             @GET

137.             @Produces( {MediaType.APPLICATION_JSON })

138.             public User getUserByIdWithXML1() throws UnsupportedEncodingException{

139.                       User user = new User();

140.                       user.userId=(10000L);

141.                       user.userName=URLEncoder.encode(("哈哈"), "utf-8");

142.                       user.nickName=URLEncoder.encode(("老色狼"), "utf-8");

143.    //               user.userName="哈哈";

144.    //               user.nickName="老色狼";

145.                      

146.                       return user;

147.             }

148.            

149.     

150.    }
/**

151.     * @Probject Name: jerseyDemo

152.     * @Path: com.jw.api.serviceUser.java

153.     * @Create By v-jiangwei

154.     * @Create In 2012-9-3 下午05:11:01

155.     * TODO

156.     */

157.    package com.jw.api.service;

158.     

159.    import javax.xml.bind.annotation.XmlRootElement;

160.     

161.    /**

162.     * @Class Name User

163.     * @Author v-jiangwei

164.     * @Create In 2012-9-3

165.     */

166.    @XmlRootElement

167.    public        class User {

168.     

169.                       public Long userId;

170.                       public String userName;

171.                       public String nickName;

172.                      

173.                       public User(){

174.                               

175.                       }

176.                       public User(Long userId,String userName,String nickName){

177.                                this.userId =userId;

178.                                this.userName=userName;

179.                                this.nickName=nickName;

180.                       }

181.             }

 

7. jersey webservcie 客户端调用代码:
/**

 * @Probject Name: jerseyDemo

 * @Path: com.jw.api.serviceClientDemo.java

 * @Create By v-jiangwei

 * @Create In 2012-9-3 下午05:12:59

 * TODO

 */

package com.jw.api.service;

 

/**

 * @Class Name ClientDemo

 * @Author v-jiangwei

 * @Create In 2012-9-3

 */

 

 

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;

 

 

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://127.0.0.1:8080/jerseyDemo/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));

                  

 

         }

}





posted on 2012-09-27 11:19 jiangwei 阅读(878) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

My Links

Blog Stats

常用链接

留言簿

随笔档案

文章档案

搜索

最新评论