博客
关于我
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:从 FTP 服务器下载文件
查看>>
python:从列表中创建元组列表
查看>>
Python:从嵌套列表中删除重复项
查看>>
Python:从间隔映射到值
查看>>
Python:使用 shell=False 的子进程调用不起作用
查看>>
Python:修改 PATH 环境变量的平台无关方式
查看>>
Python:假与 0
查看>>
Python:函数使用
查看>>
Python:函数进阶
查看>>
Python:在整数的二进制表示中查找最长的二进制间隙
查看>>
Python:如何从二进制转换为 base 64 并返回?
查看>>
Python:如何以非阻塞方式读取子进程的标准输出
查看>>
Python:如何使用 plotly 制作阴影区域或交替背景颜色?
查看>>
Python:如何根据日期时间获取值的计数
查看>>
python:如何检测串行 COM 上的设备名称/ID
查看>>
Python:如何模拟 datetime.utcnow()?
查看>>
Python:如果DataFrames之间的其他值匹配,则对DataFrame中的值求和
查看>>
Python:字典思维
查看>>
Python:将 HEX 字符串转换为字节
查看>>
Python:将列表与范围列表合并
查看>>