Шаг № 1: Настройте зависимости RESTEasy + Spring с помощью Maven.
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
<project xmlns= 'http:maven.apache.orgPOM4.0.0' xmlns:xsi= 'http:www.w3.org2001XMLSchema-instance' xsi:schemaLocation='http:maven.apache.orgPOM4. 0.0 http:maven.apache.orgmaven-v4_0_0.xsd'> <modelVersion> 4.0 . 0 <modelVersion> <groupId>com.sivalabs<groupId> <artifactId>resteasy-demo<artifactId> <version> 0.1 <version> <packaging>war<packaging> <properties> <project.build.sourceEncoding>UTF- 8 <project.build.sourceEncoding> <org.springframework.version> 3.1 . 0 .RELEASE<org.springframework.version> <slf4j.version> 1.6 . 1 <slf4j.version> <java.version> 1.6 <java.version> <junit.version> 4.8 . 2 <junit.version> <resteasy.version> 2.3 . 2 .Final<resteasy.version> <properties> <build> <finalName>resteasy-demo<finalName> <build> <dependencies> <dependency> <groupId>junit<groupId> <artifactId>junit<artifactId> <scope>test<scope> <dependency> <dependency> <groupId>org.slf4j<groupId> <artifactId>slf4j-api<artifactId> <version>${slf4j.version}<version> <dependency> <dependency> <groupId>org.slf4j<groupId> <artifactId>jcl-over-slf4j<artifactId> <version>${slf4j.version}<version> <scope>runtime<scope> <dependency> <dependency> <groupId>org.slf4j<groupId> <artifactId>slf4j-log4j12<artifactId> <version>${slf4j.version}<version> <scope>runtime<scope> <dependency> <dependency> <groupId>log4j<groupId> <artifactId>log4j<artifactId> <version> 1.2 . 16 <version> <scope>runtime<scope> <dependency> <dependency> <groupId>org.springframework<groupId> <artifactId>spring-context-support<artifactId> <version>${org.springframework.version}<version> <exclusions> <exclusion> <artifactId>commons-logging<artifactId> <groupId>commons-logging<groupId> <exclusion> <exclusions> <dependency> <dependency> <groupId>org.springframework<groupId> <artifactId>spring-web<artifactId> <version>${org.springframework.version}<version> <dependency> <dependency> <groupId>org.jboss.resteasy<groupId> <artifactId>resteasy-jaxrs<artifactId> <version>${resteasy.version}<version> <scope>provided<scope> <dependency> <dependency> <groupId>org.jboss.resteasy<groupId> <artifactId>resteasy-jaxb-provider<artifactId> <version>${resteasy.version}<version> <scope>provided<scope> <dependency> <dependency> <groupId>org.jboss.resteasy<groupId> <artifactId>jaxrs-api<artifactId> <version> 2.3 . 0 .GA<version> <scope>provided<scope> <dependency> <dependency> <groupId>org.jboss.resteasy<groupId> <artifactId>resteasy-spring<artifactId> <version> 2.3 . 0 .GA<version> <exclusions> <exclusion> <artifactId>commons-logging<artifactId> <groupId>commons-logging<groupId> <exclusion> <exclusion> <artifactId>org.jboss.resteasy<artifactId> <groupId>resteasy-jaxb-provider<groupId> <exclusion> <exclusion> <artifactId>jaxb-impl<artifactId> <groupId>com.sun.xml.bind<groupId> <exclusion> <exclusion> <artifactId>sjsxp<artifactId> <groupId>com.sun.xml.stream<groupId> <exclusion> <exclusion> <artifactId>jsr250-api<artifactId> <groupId>javax.annotation<groupId> <exclusion> <exclusion> <artifactId>resteasy-jaxb-provider<artifactId> <groupId>org.jboss.resteasy<groupId> <exclusion> <exclusion> <artifactId>activation<artifactId> <groupId>javax.activation<groupId> <exclusion> <exclusions> <dependency> <dependency> <groupId>javax.servlet<groupId> <artifactId>servlet-api<artifactId> <version> 2.5 <version> <scope>provided<scope> <dependency> <dependency> <groupId>org.apache.httpcomponents<groupId> <artifactId>httpclient<artifactId> <version> 4.1 . 2 <version> <dependency> <dependencies> <project> |
Шаг № 2: Настройте RESTEasy + Spring в web.xml
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<web-app xmlns:xsi= 'http:www.w3.org2001XMLSchema-instance' xmlns= 'http:java.sun.comxmlnsjavaee' xmlns:web= 'http:java.sun.comxmlnsjavaeeweb-app_2_5.xsd' xsi:schemaLocation='http:java.sun.comxmlnsjavaee http:java.sun.comxmlnsjavaeeweb-app_3_0.xsd' id= 'WebApp_ID' version= '3.0' > <listener> <listener- class >org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap<listener- class > <listener> <listener> <listener- class >org.jboss.resteasy.plugins.spring.SpringContextLoaderListener<listener- class > <listener> <servlet> <servlet-name>Resteasy<servlet-name> <servlet- class >org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher<servlet- class > <servlet> <servlet-mapping> <servlet-name>Resteasy<servlet-name> <url-pattern>rest*<url-pattern> <servlet-mapping> <context-param> <param-name>contextConfigLocation<param-name> <param-value>classpath:applicationContext.xml<param-value> <context-param> <context-param> <param-name>resteasy.servlet.mapping.prefix<param-name> <param-value>rest<param-value> <context-param> <context-param> <param-name>resteasy.scan<param-name> <param-value> true <param-value> <context-param> <web-app> |
Шаг № 3: Создайте класс Spring Service UserService и обновите UserResource для использования компонента UserService.
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
|
package com.sivalabs.resteasydemo; import java.util.List; import org.springframework.stereotype.Service; import com.sivalabs.resteasydemo.MockUserTable; @Service public class UserService { public void save(User user){ MockUserTable.save(user); } public User getById(Integer id){ return MockUserTable.getById(id); } public List<User> getAll(){ return MockUserTable.getAll(); } public void delete(Integer id){ MockUserTable.delete(id); } } package com.sivalabs.resteasydemo; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @Path ( 'users' ) @Produces (MediaType.APPLICATION_XML) @Consumes (MediaType.APPLICATION_XML) public class UserResource { @Autowired private UserService userService; @Path ( '' ) @GET public Response getUsersXML() { List<User> users = userService.getAll(); GenericEntity<List<User>> ge = new GenericEntity<List<User>>(users){}; return Response.ok(ge).build(); } @Path ( '{id}' ) @GET public Response getUserXMLById( @PathParam ( 'id' ) Integer id) { User user = userService.getById(id); return Response.ok(user).build(); } @Path ( '' ) @POST public Response saveUser(User user) { userService.save(user); return Response.ok( '<status>success<status>' ).build(); } @Path ( '{id}' ) @DELETE public Response deleteUser( @PathParam ( 'id' ) Integer id) { userService.delete(id); return Response.ok( '<status>success<status>' ).build(); } } package com.sivalabs.resteasydemo; import java.util.List; import org.springframework.stereotype.Service; import com.sivalabs.resteasydemo.MockUserTable; @Service public class UserService { public void save(User user){ MockUserTable.save(user); } public User getById(Integer id){ return MockUserTable.getById(id); } public List<User> getAll(){ return MockUserTable.getAll(); } public void delete(Integer id){ MockUserTable.delete(id); } } package com.sivalabs.resteasydemo; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @Path ( 'users' ) @Produces (MediaType.APPLICATION_XML) @Consumes (MediaType.APPLICATION_XML) public class UserResource { @Autowired private UserService userService; @Path ( '' ) @GET public Response getUsersXML() { List<User> users = userService.getAll(); GenericEntity<List<User>> ge = new GenericEntity<List<User>>(users){}; return Response.ok(ge).build(); } @Path ( '{id}' ) @GET public Response getUserXMLById( @PathParam ( 'id' ) Integer id) { User user = userService.getById(id); return Response.ok(user).build(); } @Path ( '' ) @POST public Response saveUser(User user) { userService.save(user); return Response.ok( '<status>success<status>' ).build(); } @Path ( '{id}' ) @DELETE public Response deleteUser( @PathParam ( 'id' ) Integer id) { userService.delete(id); return Response.ok( '<status>success<status>' ).build(); } } applicationContext.xml <?xml version= '1.0' encoding= 'UTF-8' ?> <beans xmlns= 'http:www.springframework.orgschemabeans' xmlns:xsi= 'http:www.w3.org2001XMLSchema-instance' xmlns:p= 'http:www.springframework.orgschemap' xmlns:context= 'http:www.springframework.orgschemacontext' xsi:schemaLocation='http:www.springframework.orgschemabeans http:www.springframework.orgschemabeansspring-beans.xsd http:www.springframework.orgschemacontext http:www.springframework.orgschemacontextspring-context.xsd'> <context:annotation-config> <context:component-scan base- package = 'com.sivalabs.resteasydemo' > <beans> |
Шаг # 4: Тот же JUnit TestCase для тестирования веб-сервиса REST, описанного в части 1.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
package com.sivalabs.resteasydemo; import java.util.List; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.util.GenericType; import org.junit.Assert; import org.junit.Test; import com.sivalabs.resteasydemo.User; public class UserResourceTest { static final String ROOT_URL = 'http:localhost:8080resteasy-demorest' ; @Test public void testGetUsers() throws Exception { ClientRequest request = new ClientRequest(ROOT_URL+ 'users' ); ClientResponse<List<User>> response = request.get( new GenericType<List<User>>(){}); List<User> users = response.getEntity(); Assert.assertNotNull(users); } @Test public void testGetUserById() throws Exception { ClientRequest request = new ClientRequest(ROOT_URL+ 'users1' ); ClientResponse<User> response = request.get(User. class ); User user = response.getEntity(); Assert.assertNotNull(user); } @Test public void testSaveUser() throws Exception { User user = new User(); user.setId( 3 ); user.setName( 'User3' ); ClientRequest request = new ClientRequest(ROOT_URL+ 'users' ); request.body( 'applicationxml' , user); ClientResponse<String> response = request.post(String. class ); String statusXML = response.getEntity(); Assert.assertNotNull(statusXML); } @Test public void testDeleteUser() throws Exception { ClientRequest request = new ClientRequest(ROOT_URL+ 'users2' ); ClientResponse<String> response = request.delete(String. class ); String statusXML = response.getEntity(); Assert.assertNotNull(statusXML); } } |
Важные вещи, которые следует иметь в виду:
1. org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap Слушатель должен быть зарегистрирован перед любым другим слушателем.
2. Вам следует настроить resteasy.servlet.mapping.prefix @lt; context-param>, если шаблон URL сервлета HttpServletDispatcher отличается от / *
3. Вы должны зарегистрировать REST Resource как Spring bean, добавив аннотации @Component или @Service.
Ссылка: учебное пособие RESTEasy, часть 2: Spring Integration от нашего партнера по JCG Шивы Редди в блоге « Мои эксперименты по технологии» .