对于一个方法,我如何在一个场景中发回一个简单的String
,在另一个场景下发送一个对象?
例如。对于signup
,如果用户创建成功,我想发回一个User
对象或类似username already exists
的消息。
这就是我目前所拥有的:
@POST
@Path("/signup")
public User signup (@Valid User user) {
if (dao.doesUserExist(user.getName())
//how can I return a message here?
else
return createNewUser();
}
这有帮助吗?
@POST
@Path("/path")
public Response signup (@Valid User user)
{
if (dao.doesUserExist(user.getName())
//return a message here
Response.status(Status.CONFLICT).type(MediaType.TEXT_PLAIN).entity("user already exists, but due to OWASP (https://www.owasp.org/index.php/Authentication_Cheat_Sheet) -> An application should respond with a generic error message regardless of whether the user ID or password was incorrect. It should also give no indication to the status of an existing account. ").build();
else
return createNewUser();
}
投掷:怎么样
throw new WebApplicationException(409);
这表明存在冲突。它对客户端也比返回错误字符串更有用。
您可以使用Response向客户端返回一条简单的消息,在返回中,您可以将User更改为Response,并在响应体中返回您的creted用户或消息