0

There is a way using Spring having some code like this:

@RequestMapping("/animals/view/*")
public ModelAndView view(@SomeKindOfAnnotation AnimalFilter filter) {
    return new ModelAndView("myViewPage", "animals", animalService.filterBy(filter));
}

I want call urls like these:

  • <myContextPath>/animals/view/ (extracts all animals)
  • <myContextPath>/animals/view/type/cat (extracts only cats)
  • <myContextPath>/animals/view/type/cat/color/yellow (extracts only brown cats)
  • <myContextPath>/animals/view/type/insect/legs/6 (extracts only insects with 6 legs)

and having the object animalFilter already filled with the data contained into the url.

AnimalFilter is a simple POJO class with getter and setter for every type of fields that the user can use for filter animals.

If there isn't a way doing this is possible to create the new annotation @SomeKindOfAnnotation for filling the AnimalFilter automatically?

1 Answer 1

1

What you can do is build a PropertyEditor or you can use a object mapper like Jackson if you are using json value, but if you really want to use a annotation you can use AOP:

Examples using AOP:

@Before(value="@annotation(audit) && args(.......)")
public void beforeHandler(SomeKindOfAnnotation audit, .......) {

Example using PropertiesEditor:

public class SomeKindOfPropertie extends PropertiesEditor {

@Override
public void setAsText(String text) throws IllegalArgumentException {
    // Reminding all parameters in the request are String.
            .......
            setValue(new SomeKind(text));
} 

}

In your controller you need to register the propertiesEditor on the binder:

@InitBinder("filter")
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(SomeKind.class, new SomeKindOfPropertie());
}

More Information: http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html

Sign up to request clarification or add additional context in comments.

2 Comments

With the PropertiesEditor can I parse the url to fill my class AnimalFilter?
Yes, you can do what you want, you will receive a String parameter with the value of the request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.