Continue learning about @ formparam and @ headerparam in the JAX-RS today
1 @ formparam
The function is to bind the front-end html. Let's look at the example first.
Java code
- HTML>
- <Body>
- <H1> JAX-RS @ formquery testing
- <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>
html><body>
Processing:
Java code
- @ 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 ();
- }
@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(); }
For front-end HTML browsing, such:
Http: // localhost: 8080/restfulexample/userform.html
A common HTML form will appear. When the button is submitted, it will go
HTTP: /localhost: 8080/restfulexample/rest/user/Add
In this way, rest will match the adduser method, so the data submitted in the form will be output.
2 In the JAX-RS, there are two ways to get the HTTP Request Header,
1) @ headparam
Java code
- @ 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 ();
- }
@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(); }
When the access URL:
/Users/get
Will output the HTTP header information, namely:
Adduser is called, useragent: Mozilla/5.0 (Windows NT 6.1; RV: 5.0) Gecko/20100101 Firefox/5.0
In addition, the Java code
- @ 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 ();
- }
@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(); }
You can achieve the same purpose.