博客
关于我
JAX-RS之@formparam和@HeaderParam
阅读量:129 次
发布时间:2019-02-26

本文共 1671 字,大约阅读时间需要 5 分钟。

今天继续学习JAX-RS中的@formparam和@headerparam。

1. @formparam

@formparam是一种在JAX-RS中强大的绑定机制,允许前端HTML表单数据直接传递给后端服务。通过@formparam,可以轻松将HTML表单字段映射到Java方法参数中。

示例

考虑以下HTML表单:

  

JAX-RS @FormQuery Testing

Name :
Age :

当表单提交时,数据会发送到rest/user/add endpoint。服务端可以通过@formparam注解来接收表单数据。

服务端代码

@Path("/user")public class UserService {    @POST    @Path("/add")    public Response addUser(        @FormParam("name") String name,        @FormParam("age") int age    ) {        return Response.status(200)            .entity("addUser is called, name : " + name + ", age : " + age)            .build();    }}

2. @headerparam

除了@formparam,JAX-RS还提供了@headerparam用来获取HTTP请求头信息。通过@headerparam,可以直接从HTTP请求头中获取特定头字段的值。

方法一:@HeaderParam注解

@Path("/users")public class UserService {    @GET    @Path("/get")    public Response addUser(        @HeaderParam("user-agent") String userAgent    ) {        return Response.status(200)            .entity("addUser is called, userAgent : " + userAgent)            .build();    }}

当访问/users/get endpoint时,会返回包含用户代理信息的响应。

方法二:@Context HttpHeaders

另一种获取HTTP头信息的方法是使用@Context注解获取HttpHeaders对象,然后手动获取所需头字段。

@Path("/users")public class UserService {    @GET    @Path("/get")    public Response addUser(        @Context HttpHeaders headers    ) {        String userAgent = headers.getRequestHeader("user-agent").get(0);        return Response.status(200)            .entity("addUser is called, userAgent : " + userAgent)            .build();    }}

测试

  • 访问http://localhost:8080/RESTfulExample/UserForm.html会看到一个标准的HTML表单。-提交表单后,数据会发送到http://localhost:8080/RESTfulExample/rest/user/add endpoint。

通过以上方法,可以轻松地在JAX-RS服务中处理HTML表单数据和HTTP请求头信息。

转载地址:http://aacf.baihongyu.com/

你可能感兴趣的文章
Python+Pytest+Allure+Git+Jenkins接口自动化框架
查看>>
python+pytest接口自动化 —— 参数关联
查看>>
python+pytest接口自动化 —— 参数关联
查看>>
Python+pytest接口自动化 —— 接口测试基础
查看>>
python+pytest接口自动化 —— 自动化用例编写思路 (使用pytest编写一个测试脚本)
查看>>
Python+pytest接口自动化之cookie绕过登录(保持登录状态)
查看>>
python+pytest接口自动化:接口测试
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
python+requests+unittest执行自动化接口测试!
查看>>
Python+Requests编码识别Bug
查看>>
python函数编写_[零基础学python]传说中的函数编写条规
查看>>
Python+selenium —— UI自动化之鼠标操作
查看>>
python函数注释,参数后面加冒号:,函数后面的箭头→是什么?
查看>>
Python+Selenium+Threading进行兼容性测试
查看>>
Python+selenium+unittest的GUI自动化框架实现
查看>>
python函数拟合不规则曲线_Python计算&绘图——曲线拟合问题(转)
查看>>
python函数定义的基本格式_零基础学python-2.19 定义函数、调用函数与默认参数
查看>>
Python+Selenium之数据驱动测试的实现
查看>>
python函数定义与使用+返回值简解
查看>>