I wanted a simple way to get the values of request parameters into an Object. I've implemented a DTO (Data Transfer Object) class that can be used for this.

Suppose you want to implement a query request. You could do something like:

        public class QueryDTO extends DTO {
            @Required public String q;
            public SortOrder order; // SortOrder is enum { NAME, DATE, SIZE }
            public Boolean desc;

            QueryDTO( Request request ) throws DTOException {
                super( request );
                if ( order == null ) order == SortOrder.NAME;
                if ( desc == null ) desc = Boolean.FALSE;
            }
        }

What this says is that a request has 3 query parameters. Of those, "q" is a required String. The DTO constructor takes care of all the parsing of form data (for both APPLICATION_WWW_FORM and MULTIPART_FORM_DATA cases), enforces @Require constraints, and handles enum values. You can then use it like:

        public void handleGet() {
            try {
                QueryDTO dto = new QueryDTO( getRequest() );
                // ... use dto.{members} as you please ...
            }
            catch ( DTOException e ) {
                e.setStatusOf( getResponse() );
            }
        }

DTO also correctly handles array values.  For example, specifying:

            public String[] field;

allows "field" to be specified more than once:

        http://server/foo?field=val1&field=val2&;...

There are also @Permitted and @Forbidden annotations.  For example:

            @Permitted( onlyIf={"y"} )
            public Integer x;

            @Permitted( onlyIf={"x"} )
            public Integer y;

This will cause DTO to throw an exception if either "x" or "y" is given without the other. (@Forbidden works similarly, but in reverse.)

If there's interest, I'd be willing to donate this code to Restlet.

- Paul

Reply via email to