Java Restful Web Services (ii)--parameter annotation 1__java

Source: Internet
Author: User

This chapter mainly introduces jersey of different parameters annotation

Parameters of a resource method is 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 RE Quest 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 SA Me 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 cookies related HTTP headers.

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

In short, @pathparam gets @path-defined matching parameters from the URL path of the request, @QueryParam gets the matching parameter from the requested URL query component element, @MatrixParam gets the parameter information from the path segment, @ Headerparam gets the parameter value from the head parameter of the HTTP request @CookieParam from the cookie.

Examples of Pathparam, @QueryParam, and Matrixparam. For a later example @context and @cookieparam.

Defining Resource Classes

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) {Retu
	RN "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, @PathP
		Aram ("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 Conditi On, @MatrixParam (' program ') final string program, @MatrixParam ("type") final String type} {return CONDITION.GETP
	Ath () + "program =" + program + "type =" + type;
 }

}

Defining Test Classes

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/";
	@BeforeClass public static void Setupbeforeclass () throws Exception {System.out.println ("Setupbeforeclass");
	@AfterClass public static void Teardownafterclass () throws Exception {System.out.println ("Teardownafterclass");
		@Before public void SetUp () throws Exception {System.out.println ("setUp");
		Client C = clientbuilder.newclient ();
		target = C.target (Base_uri);
	System.out.println (Target.geturi ());
	@After public void teardown () throws Exception {System.out.println ("teardown"); @Test public void Testgethello () {String REsponsemsg = Target.path ("HelloWorld"). Request (). get (String.class);
		
	Assertequals ("Hello world!", responsemsg); @Test public void Testgethellowithpathparam () {String responsemsg = Target.path (' HELLOWORLD/ICBC '). Request (). Get		
		(String.class);
		
	Assertequals ("Hello Path Param ICBC", responsemsg); @Test public void Testgethellowithqueryparam () {String responsemsg = Target.path ("Helloworld/user"). Queryparam		
		("Param", "ICBC"). Request (). get (String.class);
		
	Assertequals ("Hello Query Param ICBC", responsemsg); @Test public void Testgethellobefore () {String responsemsg = Target.path ("helloworld/before/"). Request ().
		Get (String.class);

	Assertequals ("Hello before", responsemsg); @Test public void Testgetbyaddress () {String result = Target.path ("Helloworld/china/henan/kaifeng/gulou"). Request
		(). get (String.class);
	Assertequals ("China-henan-kaifeng-gulou", result);
@Test public void Testgetbyconditionmatrixparameters () {		String result = Target.path ("helloworld/query/restful;program=java;type=web;kind=1,2,3"). Request ().
		String.class);
		SYSTEM.OUT.PRINTLN (result);
	Assertequals ("Program=[java] type=[web] kind=[1,2,3", result); @Test public void Testgetbyconditionmatrixparam () {String result = Target.path ("Helloworld/weather/matrixparam;pr
		ogram=java;type=web;kind=1,2,3 "). Request (). get (String.class);
		SYSTEM.OUT.PRINTLN (result);
	Assertequals ("Matrixparam program = java type = web", result);
 }
	
	
}

Execution results







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.