Spring Framework check query parameter or path variable

I know that I can validate forms in Spring, but can I apply similar validations for URL parameters? For example, I have a method in my controller as follows:

public String edit(@PathVariable("system") String system, @RequestParam(value="group") String group, ModelMap model) throws DAOException { 

Is it possible to check the values ​​of system and group before calling the method to make sure that they have a specific value or match a specific regular expression?

thanks

+4
source share
3 answers

You might be able to use Spring Asserts for this. Assert api (http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/Assert.html) runs the provided expression against the specified parameters, and if the expression is false, it throws an exception .

Example: Assert.isTrue (system.equals ("ValidSystemName"), "You must provide a valid system");

It also contains functions to verify that the parameters are not null or are not empty strings, etc.

0
source
  • Create an annotation that marks the parameters that need to be checked. This annotation requires @Retention RUNTIME and a @Target of ElementType.PARAMETER .
  • Create a validator implemented as AspectJ Aspect.
  • Wrap calls with controllers using this validator.

Annotation Example:

 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) @Documented public @interface ValidSystemParameter { } 

Validation Example:

 @Aspect public class ValidSystemParameterValidator { @Pointcut("TODO: write your pointcut expression") public void controllerMethodWithValidSystemParameter(); @Before(pointcut = "controllerMethodWithValidSystemParameter()") public void validateSystemParameter(String systemParameter) { // validate the parameter (throwing an exception) } } 

To learn about AspectJ's pointcut expression language, see below: http://www.eclipse.org/aspectj/doc/released/progguide/language-joinPoints.html

To learn about integrating AspectJ into Spring, see http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-ataspectj

0
source

I may be a little late, but with Spring 3.0 you can use the JSR-303 check with @Valid annotation. There are also some more specific annotations like @DateTimeFormat and @NumberFormat . More details here: http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/validation.html#validation-mvc As I can see, you have two options:

  • Define your query parameters as objects and user JSR-303 Validation.
  • Use Assert api as above.

If you just want to do a simple check on a single value, I would go with the latter (this is what I did when I had simple int values ​​to check the maximum value).

0
source

All Articles