Java Restful Web Services (二)——參數註解1__Java

來源:互聯網
上載者:User

本章主要介紹Jersey各種不同的參數註解

Parameters of a resource method may be annotated with parameter-based annotations to extract information from a request. One of the previous examples presented the use of @PathParam to extract a path parameter from the path component of the request URL that matched the path declared in @Path.

@QueryParam is used to extract query parameters from the Query component of the request URL.

The @PathParam and the other parameter-based annotations, @MatrixParam, @HeaderParam, @CookieParam, @FormParam obey the same rules as @QueryParam.@MatrixParam extracts information from URL path segments. @HeaderParam extracts information from the HTTP headers. @CookieParam extracts information from the cookies declared in cookie related HTTP headers.

@FormParam is slightly special because it extracts information from a request representation that is of the MIME media type "application/x-www-form-urlencoded" and conforms to the encoding specified by HTML forms, as described here. This parameter is very useful for extracting information that is POSTed by HTML forms, for example the following extracts the form parameter named "name" from the POSTed form data:

簡單來說@PathParam從請求的URL路徑中擷取@Path定義的匹配參數,@QueryParam則從請求的URL查詢組件元素中擷取匹配參數,@MatrixParam從路徑段中擷取參數資訊,@HeaderParam從HTTP請求的Head參數中擷取參數值,@CookieParam從Cookie中擷取。

樣本PathParam、@QueryParam及MatrixParam。稍後樣本@Context及@CookieParam。

定義資源類

import java.util.Iterator;import java.util.List;import java.util.Map.Entry;import javax.ws.rs.GET;import javax.ws.rs.MatrixParam;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;import javax.ws.rs.QueryParam;import javax.ws.rs.core.MultivaluedMap;import javax.ws.rs.core.PathSegment;@Path("helloworld")public class HelloWorldResource {public static final String CLICHED_MESSAGE = "Hello World!";@GET@Path("/before")@Produces("text/plain")public String getHelloBefore() {return "hello before";}@GET@Produces("text/plain")public String getHello() {return CLICHED_MESSAGE;}@GET@Path("/{param}")@Produces("text/plain")public String getHello(@PathParam("param") String username) {return "Hello Path Param " + username;}@GET@Path("/user")@Produces("text/plain")public String getHelloWithQuery(@QueryParam("param") String username) {return "Hello Query Param " + username;}@GET@Path("{region:.+}/kaifeng/{district:\\w+}")public String getByAddress(@PathParam("region") final List<PathSegment> region,@PathParam("district") final String district) {final StringBuilder result = new StringBuilder();for (final PathSegment pathSegment : region) {result.append(pathSegment.getPath()).append("-");}result.append("kaifeng-" + district);return result.toString();}@GET@Path("query/{condition}")public String getByCondition(@PathParam("condition") final PathSegment condition) {StringBuilder conditions = new StringBuilder();final MultivaluedMap<String, String> matrixParameters = condition.getMatrixParameters();final Iterator<Entry<String, List<String>>> iterator = matrixParameters.entrySet().iterator();while (iterator.hasNext()) {final Entry<String, List<String>> entry = iterator.next();conditions.append(entry.getKey()).append("=");conditions.append(entry.getValue()).append(" ");}return conditions.toString();}@GET@Path("weather/{condition}")public String getByCondition(@PathParam("condition") final PathSegment condition,@MatrixParam("program") final String program,@MatrixParam("type") final String type) {return condition.getPath() + " program = " + program + " type = "+ type;}}

定義測試類別

import static org.junit.Assert.*;import javax.ws.rs.client.Client;import javax.ws.rs.client.ClientBuilder;import javax.ws.rs.client.WebTarget;import org.junit.After;import org.junit.AfterClass;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;public class HelloWorldResourceTest {private WebTarget target;public static final String BASE_URI = "http://localhost:8090/NoteMail/rest/";@BeforeClasspublic static void setUpBeforeClass() throws Exception {System.out.println("setUpBeforeClass");}@AfterClasspublic static void tearDownAfterClass() throws Exception {System.out.println("tearDownAfterClass");}@Beforepublic void setUp() throws Exception {System.out.println("setUp");Client c = ClientBuilder.newClient();target = c.target(BASE_URI);System.out.println(target.getUri());}@Afterpublic void tearDown() throws Exception {System.out.println("tearDown");}@Testpublic void testGetHello() {String responseMsg = target.path("helloworld").request().get(String.class);assertEquals("Hello World!", responseMsg);}@Testpublic void testGetHelloWithPathParam() {String responseMsg = target.path("helloworld/ICBC").request().get(String.class);assertEquals("Hello Path Param ICBC", responseMsg);}@Testpublic void testGetHelloWithQueryParam() {String responseMsg = target.path("helloworld/user").queryParam("param", "ICBC").request().get(String.class);assertEquals("Hello Query Param ICBC", responseMsg);}@Testpublic void testGetHelloBefore() {String responseMsg = target.path("helloworld/before/").request().get(String.class);assertEquals("hello before", responseMsg);}@Testpublic void testGetByAddress(){String result = target.path("helloworld/China/Henan/kaifeng/gulou").request().get(String.class);assertEquals("China-Henan-kaifeng-gulou", result);}@Testpublic void testGetByConditionMatrixParameters(){String result = target.path("helloworld/query/restful;program=java;type=web;kind=1,2,3").request().get(String.class);System.out.println(result);assertEquals("program=[java] type=[web] kind=[1,2,3] ", result);}@Testpublic void testGetByConditionMatrixParam(){String result = target.path("helloworld/weather/matrixparam;program=java;type=web;kind=1,2,3").request().get(String.class);System.out.println(result);assertEquals("matrixparam program = java type = web", result);}}

執行結果







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.