私の質問は、@PathParam を使用する場合、リクエスト パラメータを検証するにはどうすればよいかです。
たとえば、name と id という 2 つのリクエスト パラメータがあります。
path is localhost:/.../search/namevalue/idvalue
ユーザーが名前またはIDの空白を送信した場合、名前が必要である/ IDが必要であるという応答を送信する必要があります。
@QueryParam を使用すれば検証を実行できますが、パス変数を使用する必要がある場合の検証方法がわかりません。
http:/localhost:/.../search/namevalue
またはを使用してテストした場合http:/localhost:/.../search/idvalue
、http:/localhost:/.../search/
サーブレット例外がスローされます。
以下はコードです。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 }