Reputation: 1670
I have a login form with two values name and password. I pass this value as in my rest service. I get this value in my rest service using FormParam
annotation. But, my requirement is to get that values as a class. I tried below methodology. But it's not work and shows the compile time error:
@Form cannot be resolved to a type.
@POST
@Path("login")
@Produces(MediaType.TEXT_PLAIN)
public String login(@Form User form) {
return "Logged with " + form.email + " " + form.password;
}
public class User {
@FormParam("email")
private String email;
@FormParam("password")
private String password;
}
My form is
<form method="POST" action="rest/login">
Email Address: <input type="text" name="email">
<br>
Password: <input type="text" name="password">
<input type="submit">
</form>
How to receive form value as object?
Upvotes: 3
Views: 10891
Reputation: 5329
If your requirement is only to have the data in the form of an object, you can call your ReST service by passing a JSON request:
ReST method
@POST
@Consumes(MediaType.APPLICATION_JSON)
public String login(User form) {
// access values from inputObject
form.getEmail();
form.getPassword();
}
User class
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
private String email;
private String password;
//getters and setters
}
You need to use Jackson feature for overcoming MessageBody related error. If you are using Jackson version 2.x BELOW, you'll need to register Jackson feature in your web.xml
file.
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
In case of Jackson version 2.x and above, only add Jackson 2.x jars. The above mentioned snippet won't be required in web.xml
Upvotes: 0
Reputation: 68715
You need to use @RequestParam even if it is a composite Java object. So change this
public String login(@Form User form)
to
public String login(@RequestParam("form") User form)
You just need to send user details under "form" param from client.
Upvotes: 1