Статьи

Spring 3 WebMVC — необязательные переменные пути

Вступление

Для привязки запросов к методам контроллера через шаблон запросов REST-функция Spring WebMVC является идеальным выбором. Возьмите запрос, например http: //example.domain/houses/213234, и вы можете легко связать его с методом контроллера с помощью аннотаций и переменных пути привязки:

...

@RequestMapping("/houses/{id}")
public String handleHouse(@PathVariable long id) {
return "viewHouse";
}

проблема

Но проблема была в том, что мне требовались маленькие сегменты пути и предварительный просмотр . Это означает, что он хотел бы обрабатывать запросы, такие как / Houses / Preview / small / 213234 , / Houses / Small / 213234 , / Houses / Preview / 213234 и оригинал / Houses / 213234 . Почему я не могу использовать только один @RequestMapping для этого.

Хорошо, я мог бы представить три новых метода с отображениями запросов:

...

@RequestMapping("/houses/{id}")
public String handleHouse(@PathVariable long id) {
return "viewHouse";
}

@RequestMapping("/houses/preview/{id}")
...

@RequestMapping("/houses/preview/small/{id}")
...

@RequestMapping("/houses/small/{id}")
...

Но представьте, у меня есть 3 или 4 дополнительных сегмента пути. У меня было бы 8 или 16 методов для обработки всего запроса. Итак, должен быть другой вариант.

Просматривая исходный код, я нашел org.springframework.util.AntPathMatcher, который отвечает за разбор uri запроса и извлечение переменных. Кажется, это правильное место для расширения.

Вот как я хотел бы написать свой метод обработчика:

@RequestMapping("/houses/[preview/][small/]{id}")
public String handlePreview(@PathVariable long id, @PathVariable("preview/") boolean preview, @PathVariable("small/") boolean small) {
return "view";
}

Решение

Давайте сделаем расширение:

package de.herold.spring3;

import java.util.HashMap;
import java.util.Map;

import org.springframework.util.AntPathMatcher;

/**
* Extends {@link AntPathMatcher} to introduce the feature of optional path
* variables. It's supports request mappings like:
*
* <pre>
* @RequestMapping("/houses/[preview/][small/]{id}")
* public String handlePreview(@PathVariable long id, @PathVariable("preview/") boolean preview, @PathVariable("small/") boolean small) {
* ...
* }
* </pre>
*
*/
public class OptionalPathMatcher extends AntPathMatcher {

public static final String ESCAPE_BEGIN = "[";
public static final String ESCAPE_END = "]";

/**
* stores a request mapping pattern and corresponding variable
* configuration.
*/
protected static class PatternVariant {

private final String pattern;
private Map variables;

public Map getVariables() {
return variables;
}

public PatternVariant(String pattern) {
super();
this.pattern = pattern;
}

public PatternVariant(PatternVariant parent, int startPos, int endPos, boolean include) {
final String p = parent.getPattern();
final String varName = p.substring(startPos + 1, endPos);
this.pattern = p.substring(0, startPos) + (include ? varName : "") + p.substring(endPos + 1);

this.variables = new HashMap();
if (parent.getVariables() != null) {
this.variables.putAll(parent.getVariables());
}
this.variables.put(varName, Boolean.toString(include));
}

public String getPattern() {
return pattern;
}
}

/**
* here we use {@link AntPathMatcher#doMatch(String, String, boolean, Map)}
* to do the real match against the
* {@link #getPatternVariants(PatternVariant) calculated patters}. If
* needed, template variables are set.
*/
@Override
protected boolean doMatch(String pattern, String path, boolean fullMatch, Map uriTemplateVariables) {
for (PatternVariant patternVariant : getPatternVariants(new PatternVariant(pattern))) {
if (super.doMatch(patternVariant.getPattern(), path, fullMatch, uriTemplateVariables)) {
if (uriTemplateVariables != null && patternVariant.getVariables() != null) {
uriTemplateVariables.putAll(patternVariant.getVariables());
}
return true;
}
}

return false;
}

/**
* build recursicly all possible request pattern for the given request
* pattern. For pattern: /houses/[preview/][small/]{id}, it
* generates all combinations: /houses/preview/small/{id},
* /houses/preview/{id} /houses/small/{id}
* /houses/{id}
*/
protected PatternVariant[] getPatternVariants(PatternVariant variant) {
final String pattern = variant.getPattern();
if (!pattern.contains(ESCAPE_BEGIN)) {
return new PatternVariant[] { variant };
} else {
int startPos = pattern.indexOf(ESCAPE_BEGIN);
int endPos = pattern.indexOf(ESCAPE_END, startPos + 1);
PatternVariant[] withOptionalParam = getPatternVariants(new PatternVariant(variant, startPos, endPos, true));
PatternVariant[] withOutOptionalParam = getPatternVariants(new PatternVariant(variant, startPos, endPos, false));
return concat(withOptionalParam, withOutOptionalParam);
}
}

/**
* utility function for array concatenation
*/
private static PatternVariant[] concat(PatternVariant[] A, PatternVariant[] B) {
PatternVariant[] C = new PatternVariant[A.length + B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
}

Теперь пусть Spring использует наш новый метод сопоставления путей. Здесь у вас есть контекст приложения Spring:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="pathMatcher">
<bean class="de.herold.webapp.spring3.OptionalPathMatcher" />
</property>
</bean>
<context:component-scan base-package="de.herold" />
</beans>

That’s it. Just set the pathMatcher property of AnnotationMethodHandlerAdapter.

Fazit

I know this implementation is far from being elegant or effective. My intention was to show an extension of the AntPathMatcher. Maybe someone gets inspired and provides an extension to handle pattern like:

@RequestMapping("/houses/{**}/{id}")
public String handleHouse(@PathVariable long id, @PathVariable("**") String inBetween) {
return "viewHouse";
}

to get the «**» as a concrete value.

The sources for a little prove of concept are attached.