我的问题是如果我使用@PathParam,我如何验证请求参数。
例如我有两个请求参数,name 和 id
path is localhost:/.../search/namevalue/idvalue
如果用户提交姓名或 ID 的空白,我应该发送一个回复,提及该姓名是必需的/ID 是必需的。
如果我使用@QueryParam,我可以进行验证,但如果我必须使用路径变量,我不知道该怎么做。
如果我只是测试使用http:/localhost:/.../search/namevalue
orhttp:/localhost:/.../search/idvalue
或者http:/localhost:/.../search/
它抛出 servlet 异常。
下面是代码,如果我使用 QueryParams 验证工作得很好,请让我知道当我使用 pathparam 时的方法
@Controller
@Path("/customer")
public class CustomerController extends BaseController implements Customer {
@Override
@GET
@Produces({ "application/json", "application/xml" })
@Path("/search/{name}/{id}/")
public Response searchCustomerDetails(
@PathParam("name") String name,
@PathParam("id") Integer id) {
ResponseBuilder response = null;
CustomerValidations validations = (CustomerValidations) getAppContext()
.getBean(CustomerValidations.class);
CustomerResponse customerResponse = new CustomerResponse();
CustomerService customerService = (CustomerService) getAppContext()
.getBean(CustomerService.class);
try {
validations.searchCustomerDetailsValidation(
name, id,customerResponse);
if (customerResponse.getErrors().size() == 0) {
CustomerDetails details = customerService
.searchCustomerDetailsService(name, id);
if (details == null) {
response = Response.status(Response.Status.NO_CONTENT);
} else {
customerResponse.setCustomerDetails(details);
response = Response.status(Response.Status.OK).entity(
customerResponse);
}
} else {
response = Response.status(Response.Status.BAD_REQUEST).entity(
customerResponse);
}
}
catch (Exception e) {
LOGGER.error(e.getMessage());
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
}
return response.build();
} }
@Component
@Scope("prototype")
public class CustomerValidations {
public void searchCustomerDetailsValidation(
String name, Integer id,
CustomerResponse customerResponse) {
if (id == null) {
customerResponse.getErrors().add(
new ValidationError("BAD_REQUEST",
""invalid id));
}
if (name== null
|| (name!= null && name
.trim().length() == 0)) {
customerResponse.getErrors().add(
new ValidationError("BAD_REQUEST", "invalid id"));
}
} }
@XmlRootElement
public class CustomerResponse {
private CustomerDetails customerDetails;
private List<ValidationError> errors = new ArrayList<ValidationError>();
//setters and getters }
public class ValidationError {
private String status;
private String message;
public ValidationError() {
}
public ValidationError(String status, String message) {
super();
this.status = status;
this.message = message;
}
//setters and getters }