2

我试图在我的 MVC 应用程序中构建一个干净的 URL 映射,我发现了很多常见的 URL,例如:

/SITE/{city}-{language}/user/{userId}

@RequestMapping(value = "/{city}-{language}/user/{userId}", 
         method = RequestMethod.GET)
public String user(@PathVariable String city, 
                   @PathVariable String language, 
                   @PathVariable String userId, 
                   Model model) {}

/SITE/{city}-{language}/comment/{userId}-{commentId}

@RequestMapping(value = "/{city}-{language}/comment/{userId}-{commentId}",
         method = RequestMethod.GET)
public String comment(@PathVariable String city,
                      @PathVariable String language, 
                      @PathVariable String userId,
                      @PathVariable String commentId, 
                      Model model) {}

有没有办法自动将城市和语言自动绑定到模型而不是过滤器的@PathVariable,我认为它可以减少@RequestMapping 函数参数的数量。

4

2 回答 2

1

我做了一个满足我需要的工作,我创建了一个映射公共参数的抽象基类。

public abstract class AbstractController {

    @ModelAttribute("currentCity")
    public CityEntity getCurrentCity(@PathVariable CityEntity city) {
        //CityEntity via a converter class
        return city;
    }

    @ModelAttribute("language")
    public String getLanguage(@PathVariable String language) {
        return language;
    }
}

现在两个通用属性将在模型对象中可用

@RequestMapping(value = "/{city}-{language}")
public class UserController extends AbstractController {

      @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
      public String user(@PathVariable String userId, 
               Model model) {...}

}
于 2013-01-19T19:36:22.383 回答
0

您只需要为每种类型实现接口转换器:

例如

public class StringToCityConverter<String, City> {
    ...
    public City convert (String cityName) {
        return this.cityDao.loadByCityName(cityName);
    }
}

你需要注册它们。一种方法是使用格式化程序注册器。

一些注册商注册格式化程序

public class MyRegistrar implements FormatterRegistrar {
    ...
    @Override
    public void registerFormatters(final FormatterRegistry registry) {
        registry.addConverter(new StringToCityConverter(cityDto));
    }
}

这注册了注册商

<!-- Installs application converters and formatters -->
<bean id="applicationConversionService"
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="formatterRegistrars">
        <set>
            <bean
                class="MyRegistrar" autowire="byType" />                               
        </set>
    </property>
</bean>

然后你可以这样写你的控制器:

@RequestMapping(value = "/{city}-{language}/comment/{userId}-{commentId}",
     method = RequestMethod.GET)
public String comment(@PathVariable City city, ... Model model) {}
于 2013-01-07T18:44:00.223 回答