您的位置:首页 > 其它

restful URI 匹配原理,它是咋构成的?

2016-04-15 09:09 302 查看
如果你写了一个JAX-RS (restful 风格的web service)程序,放在了tomcat 等web service上面,那restful 客户端程序或者browser 如何知道你的资源地址 URI呢?

下面就说下这个JAX-RS web service对外提供的URI是由那几部分组成的。

/*

 * How Request URI is Matched?

Lets assume 
1) you have a web application called 'rest'  , in this example, it is  'rest.war'  deployed on tomcat server.

2) CXFServlet's url-pattern is "/test/*"  (here it is defined in web.xml as below example shows)

web.xml 的内容如下:

.......

<servlet>

<servlet-name>CXF315</servlet-name>

<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>

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

</servlet>

<servlet-mapping>

<servlet-name>CXF315</servlet-name>
<url-pattern>/WSRest/*</url-pattern>
</servlet-mapping>

...

3)  Finally, jaxrs:server's address is "/bar" 

(it is defined in Spring's bean xml such as applicationContext.xml as below shown) 

<bean id="WSRestfulBean" class="cxf.server.MyServiceImpl"/>   

<jaxrs:server id="userService" address="/userws">

<jaxrs:serviceBeans>

  <ref bean="WSRestfulBean"/>

</jaxrs:serviceBeans>

</jaxrs:server>

4) 后面就是你的JAX-RS (restful web service)的代码提供的@Path参数了

例如

 RS.java

@Path("/")

public interface EmployeeWSRestFulService {

@Path("/getUserById/{id}/")
@GET
@Produces({"application/json","application/xml"}) //json is high priority
User getUserById(@PathParam("id") String id);

@Path("/")
@GET
//json is high priority, default is application/xml
@Produces({"application/json","application/xml"}) 
List<User> findAllUsers();

@Path("/updateUser/")
@PUT
@Consumes({"application/json","application/xml"})   
Response updateUser(User user);

@Path("/getUserById/{id}/")
@GET
@Produces({"application/json","application/xml"}) //json is high priority
User getUserById(@PathParam("id") String id);

@Path("/")
@GET
//json is high priority, default is application/xml
@Produces({"application/json","application/xml"}) 
List<User> findAllUsers();

...

}

这样 带有  /test/WSRest/userws/
的 Http Get 请求就会被List<User> findAllUsers()处理,而带 /test/WSRest/userws/getUserById/1/  Get HTTP request
就会被getUserById("1")处理。

注意这里的root @Path是"/",如果不是"/",则上面的URI还会加一级。例如,假设上面的代码是这样:

@Path("/thb")
public interface EmployeeWSRestFulService {

//里面内容不变

}

则  带 URI /test/WSRest/userws/ thb/getUserById/1/ 的  HTTP Get  才会被getUserById("1")处理了。

Requests like /rest/test/bar or /rest/test/bar/baz will be delivered to one of the resource classes in a given jaxrs:server 

endpoint. For the former request to be handled, a resource class with @Path("/") should be available, in the latter case - 

at least @Path("/") or a more specific @Path("/baz").

 * 

 */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: