博客
关于我
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/

你可能感兴趣的文章
Pip 安装失败:需要 SSL
查看>>
Pip 安装挂起
查看>>
pip 或 pip3 为 Python 3 安装包?
查看>>
pip 文件损坏导致 pip无法使用 报错 ImportError: cannot import name 'main' from 'pip._int
查看>>
pip/pip3更换国内源
查看>>
pip3 install PyQt5 --user 失败
查看>>
pip3命令全解析:Python3包管理工具的详细使用指南
查看>>
pip3安装命令重复创建文件‘/tmp/pip-install-xxxxx/package‘失败
查看>>
PIPE 接口信号列表
查看>>
pipeline配置与管理Job企业级实战
查看>>
pipeline项目配置实战
查看>>
Pipenv 与 Conda?
查看>>
QVGA/HVGA/WVGA/FWVGA分辨率屏含义及大小//Android虚拟机分辨率
查看>>
pipreqs : 无法将“pipreqs”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径 正确,然后再试一次。
查看>>
pipy国内镜像的网址
查看>>
quiver绘制python语言
查看>>
pip下载缓慢
查看>>
PIP使用SSH从BitBucket安装自定义软件包,无需输入SSH密码
查看>>
pip在安装模块时提示Read timed out
查看>>
Pix2Pix如何工作?
查看>>