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

你可能感兴趣的文章
ReentrantReadWriteLock读写锁解析
查看>>
php laravel实现依赖注入原理(反射机制)
查看>>
php laravel请求处理管道(装饰者模式)
查看>>
ReentrantReadWriteLock读写锁底层实现、StampLock详解
查看>>
PHP mongoDB 操作
查看>>
ReentrantLock读写锁
查看>>
ReentrantLock的公平锁与非公平锁
查看>>
php mysql procedure获取多个结果集
查看>>
php mysql query 行数,PHP和MySQL:返回的行数
查看>>
php mysql session_php使用MySQL保存session会话
查看>>
PHP mysql_real_escape_string() 函数防SQL注入
查看>>
php mysql优化方法_MySQL优化常用方法
查看>>
PHP OAuth 2.0 Server
查看>>
php odbc驱动,php常用ODBC函数集(详细)
查看>>
php openssl aes ecb,php openssl_encrypt AES-128-ECB iOS
查看>>
php paypal rest api,PayPal REST API指定网络配置文件PHP
查看>>
php pcntl 多进程学习
查看>>
PHP pcntl_fork不能在web服务器中使用的变通方法
查看>>
php private ,public protected三者的区别
查看>>
php PSR规范
查看>>