我第一次使用泽西岛。
我只希望我的服务接受APPLICATION_FORM_URLENCODED
和MULTIPART_FORM_DATA
帖子表格,就像在Django或php中一样。
更好的是,我希望APPLICATION_JSON
也可以。
所以我在我的UserResource
课程中尝试了以下代码:
@POST
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON, MediaType.MULTIPART_FORM_DATA})
@Produces(MediaType.APPLICATION_JSON)
public User createUser(
@FormDataParam("username") @FormParam("username") String username,
@FormDataParam("password") @FormParam("password") String password,
@FormDataParam("mobile") @FormParam("mobile") String mobile,
@FormDataParam("email") @FormParam("email") String email) {
User user = new User();
user.setUsername(username);
user.setMobile(mobile);
user.setEmail(email);
user.setPlainPassword(password);
userDao.save(user);
return user;
}
然后我通过x-www-url-form-urlencoded
提交成功,但是当我提交multipart/formdata
时,它会下降:
当我删除@FormParam
注释时,它无法接受x-www-url-form-urlencoded
提交,并显示:
所以这是我的问题:
@JsonParam
这样的Param类型接受application/json
的请求表单类型?答案 0 :(得分:0)
请使用消费为@Consumes({MediaType.MULTIPART_FORM_DATA})
。
因此,端点可以接受多部分对象和表单数据,如下所示
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("email") String email)
请从邮递员那里测试它作为表格数据,文件应该是'文件'类型,电子邮件应该是'text'类型
答案 1 :(得分:0)
Finally I found the solution myself:
Jersey routes the request with different @{METHOD}
, @Consumes
and @Path
.
So if we declare two different method, which has same @POST
method, same @Path("/")
, but different @Consumes
in our resource:
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public User create(
@FormParam("username") String username,
@FormParam("password") String password,
@FormParam("mobile") String mobile,
@FormParam("email") String email) {
User user = new User();
user.setUsername(username);
user.setMobile(mobile);
user.setEmail(email);
user.setPlainPassword(password);
userDao.save(user);
return user;
}
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public User createUser(
@FormDataParam("username") String username,
@FormDataParam("password") String password,
@FormDataParam("mobile") String mobile,
@FormDataParam("email") String email) {
User user = new User();
user.setUsername(username);
user.setMobile(mobile);
user.setEmail(email);
user.setPlainPassword(password);
userDao.save(user);
return user;
}
See, then when we make a request which Content-Type equals x-www-form-urlencoded
, the request is then route into the first method. Or when we post the same url with Content-Type
equals multipart/formdata
, the request will then route to the second.
And we can separately code the dealing work, which uses either @FormParam
or @FormDataParam
, but never both.