Java Restful Web Services (二)——参数注解1

51 篇文章 2 订阅

本章主要介绍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/";

	@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().get(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;program=java;type=web;kind=1,2,3").request().get(String.class);
		System.out.println(result);
		assertEquals("matrixparam program = java type = web", result);
	}
	
	
}

执行结果







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值