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


1 @formparam

其功能是可以将前端的HTML绑定,先看例子




Java代码
​​

​​


1.
2. html>
3. <body>
4. @FormQuery
5.
6. "rest/user/add" method="post">
7.
8. "text" name="name"
9.
10.
11.
12. "text" name="age"
13.
14.
15. "submit" value="Add User"
16. </form>
17.
18. </body>
19. </html>


html>
<body>
<h1>JAX-RS @FormQuery Testing</h1>

<form action="rest/user/add" method="post">

Name : <input type="text" name="name" />



Age : <input type="text" name="age" />


<input type="submit" value="Add User" />
</form>

</body>
</html>

处理:




Java代码
​​

​​


1. @Path("/user")
2. public class
3.
4. @POST
5. @Path("/add")
6. public
7. @FormParam("name") String name,
8. @FormParam("age") int
9.
10. return Response.status(200)
11. "addUser is called, name : " + name + ", age : "
12. .build();
13.
14. }


@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();

}

对于前端的HTML浏览,比如:

​​ http://localhost:8080/RESTfulExample/UserForm.html
​​ 会出现普通的HTML表单,当提交按钮时,会转到

http://localhost:8080/RESTfulExample/rest/user/add

这个URL,这样,REST就去匹配addUser方法了,所以就会把表单中提交的数据输出。



2 在JAX-RS中,有两种方法能取得HTTP REQUEST头,

1)@headparam




Java代码
​​ ​​



1.
2. @Path("/users")
3. public class
4.
5. @GET
6. @Path("/get")
7. public Response addUser(@HeaderParam("user-agent") String userAgent) {
8.
9. return Response.status(200)
10. "addUser is called, userAgent : "
11. .build();
12.
13. }


@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();

}
当访问URL:

/users/get

会输出HTTP 头信息,即:

addUser is called, userAgent : Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0


另外的方法是,


Java代码
​​ ​​



1. @Path("/users")
2. public class
3.
4. @GET
5. @Path("/get")
6. public Response addUser(@Context
7.
8. "user-agent").get(0);
9.
10. return Response.status(200)
11. "addUser is called, userAgent : "
12. .build();
13.
14. }


@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();

}
也可以同样达到目的