Exact query matching with Spring

I have in Spring

@RequestMapping("/hello") 

However, Spring automatically adds mappings for / hello / as well as /hello.*. How to execute exact url?

Only / hello should work, everything else should be 404

+4
source share
3 answers

Disabling the suffix ( useSuffixPatternMatch ) on RequestMappingHandlerMapping will solve your problem, but this is actually not so easy if you use <mvc:annotation-driven/> in your configuration (instead of manually wiring all the necessary beans infrastructure). In this case, defining an additional bean of type RequestMappingHandlerMapping will have no effect.

You have two options:

  • Remove <mvc:annotation-driven/> , expanding it to an equivalent set of bean definitions, where you can use useSuffixPatternMatch parameter.

  • Keep <mvc:annotation-driven/> as it is, and use the much lighter workaround described here: https://jira.springsource.org/browse/SPR-9371 . This basically adds a BeanPostProcessor , which retrieves the RequestMappingHandlerMapping bean created by the mvc namespace and sets the aforementioned flag.

There is also another ticket requiring it to be much easier to configure the RequestMappingHandlerMapping created by the mvc namespace without using the hacks as described above, you can vote for this ticket.

+4
source

If you are using version 3.1 / 3.2, you can try this without commenting or deleting

Write a mail processor

 public class MvcConfigurationPostProcessor implements BeanPostProcessor, PriorityOrdered { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof RequestMappingHandlerMapping) { ((RequestMappingHandlerMapping) bean).setUseSuffixPatternMatch(false); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public int getOrder() { return PriorityOrdered.HIGHEST_PRECEDENCE; } } 

use the above post processor in xml config.

 <bean class="com.beanprocbug.melia.MvcConfigurationPostProcessor" /> <mvc:annotation-driven /> 
+4
source

You can disable suffix matching like this:

 <bean name="handlerMapping" class="...annotation.RequestMappingHandlerMapping"> <property name="useSuffixPatternMatch" value="false"></property> </bean> 

See RequestMappingHandlerMapping for details.

+1
source

Source: https://habr.com/ru/post/920887/


All Articles