我正在尝试在我的MVC应用程序中构建一个干净的URL映射,我发现了很多常见的URL:
/ SITE / {城市} - {语言} /用户/ {用户id}
@RequestMapping(value = "/{city}-{language}/user/{userId}",
method = RequestMethod.GET)
public String user(@PathVariable String city,
@PathVariable String language,
@PathVariable String userId,
Model model) {}
/ SITE / {城市} - {语言} /评论/ {用户id} - {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函数参数计数。
答案 0 :(得分: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) {...}
}
答案 1 :(得分:0)
您只需要为每种类型实现接口Converter:
例如
public class StringToCityConverter<String, City> {
...
public City convert (String cityName) {
return this.cityDao.loadByCityName(cityName);
}
}
你需要注册它们。一种方法是使用Formatter Registrar。
一些注册商注册格式化程序
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) {}