在我的REST应用程序中,我有@POST
方法,该方法使用x-www-form-urlencoded
并生成application/json
,旨在为美容中心创建新约会:
@POST
@Produces("application/json")
@Consumes("application/x-www-form-urlencoded")
public Response bookAppointment(@FormParam("date") Date appDate,
@FormParam("time") Time appTime, @FormParam("type") String appType,
@FormParam("clientName") String clientName, @FormParam("email") String clientEmail,
@DefaultValue("") @FormParam("message") String clientMsg) {
//externalize the validation of all fields to concentrate on "positive"
//scenario only
validator(appDate, appType, clientName, clientEmail);
Appointment appointment = build(appDate, appTime, appType,clientName,
clientEmail, clientMsg);
try {
repository.add(appointment);
return Response.ok(appointment).build();
} catch (Exception e) {
throw new InternalServerErrorException("Something happened in the application "
+ "and this apointment could not get saved. Please contact us "
+ "to inform us of this issue.");
}
}
正如您可能看到的两个Endpoint方法属性是Java对象(sql.Time
和sql.Date
)。要从来自客户端的字符串转换它们,我正在使用{Burke的 Restful Java with JAX-RS (p.70-71)中所教导的ParamConverterProvider
Stack Overflow question
我正在使用Postman chrome附加组件来发送请求,如果时间和日期我发送valueOf()
和{sql.Date
构建器方法的完整字符串必需属性,一切正常并且花花公子1}}(分别为sql.Time
和yyyy-MM-dd
)。但是,当我在没有秒数的情况下发送时间时,我会收到带有通用消息的404异常。
如果您要查看其中一个hh:MM:ss
,您会看到我正在考虑部分用户输入,并以任何方式为ParamConverterProvider
投放自定义消息(适用于其他人)验证约束):
BadRequestException
使用NetBeans调试器足够有趣我发现在上面代码中的这一行之后:
@Provider
public class SqlTimeConverterProvider implements ParamConverterProvider {
@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
System.out.println("SqlTimeConverterProvider");
if (rawType.equals(Time.class)) {
return new ParamConverter<T>() {
@Override
public T fromString(String value) {
//in case the ParamConverter does not do URI deconding
value = value.replaceAll("%3A", ":");
if (value.length() < 6) {
value = value.concat(":00");
}
if (!value.matches("([01]?[0-9]|2[0-3]):[0-5][0-9]"
+ "(:[0-5][0-9])*")) {
throw new BadRequestException(value + " is not an accepted Time format "
+ "please use this pattern: hh:mm:SS");
}
return rawType.cast(Time.valueOf(value));
}
@Override
public String toString(T value) {
Time timeRepr = (Time) value;
if (timeRepr.toLocalTime().getMinute() < 10) {
String reply = timeRepr.toLocalTime().getHour()+":"
+timeRepr.toLocalTime().getMinute();
return reply.concat("0");
}
return timeRepr.toLocalTime().toString();
}
};
}
return null;
}
}
&#39;跳过&#39;将断点移动到返回null ,并为Date转换器提供程序重复相同的操作。由于我仔细地遵循了本书中的例子,我不确定为什么System.out.println("SqlTimeConverterProvider");
if (rawType.equals(Time.class)) {
被评估为假