@MatrixVariable Spring 3.2返回Null

时间:2014-05-03 21:15:21

标签: java spring maven spring-mvc url-routing

我使用Spring 3.2.6来学习@MatrixVariable功能和基本示例。

我编写了这个方法来从URI中获取矩阵变量:

@RequestMapping(value="/matrix/{paths}", method=RequestMethod.GET)
public ModelAndView MatrixVariableExample(@MatrixVariable Integer age){
    ModelAndView mv = new ModelAndView("affichageMatrix");
    mv.addObject("age", age);
    return mv;
}

我使用此URI:localhost:8080 / SpringMVC-Maven / matrix / user; age = 23

为age变量返回的值为null,但我应该是23

3 个答案:

答案 0 :(得分:1)

在spring配置文件中启用矩阵变量

<mvc:annotation-driven enable-matrix-variables="true"/>

答案 1 :(得分:0)

尝试更改您的代码:

@RequestMapping(value="/matrix/{paths}", method=RequestMethod.GET)
public ModelAndView MatrixVariableExample(@PathVariable String paths, @MatrixVariable Integer age){
    System.out.println(paths); //or do something with it, at your choice
    ModelAndView mv = new ModelAndView("affichageMatrix");
    mv.addObject("age", age);
    return mv;
}

并使用网址:

http://localhost:8080/SpringMVC-Maven/matrix/user;age=23

您的变量paths现在应包含字符串user,而age应为23。如果您已经参数化了请求映射,我猜你不会错过路径参数。

答案 2 :(得分:0)

要使用矩阵变量,您必须启用Spring MVC框架以在您的应用程序中读取矩阵变量。 您可以使用XML表示法或通过Java配置

XML配置: 通过在dispatcher-servlet.xml中添加以下配置

<mvc:annotation-driven enable-matrix-variables="true"/>

Java配置:

public class AppInitializer  extends AbstractAnnotationConfigDispatcherServletInitializer{
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {AppConfig.class};
    }
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }
    @Override
    protected String[] getServletMappings() {
        return new String[] {"/*"};
}}

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {"com.springmvc.test"})
public class AppConfig implements WebMvcConfigurer {
    @Bean
    public InternalResourceViewResolver resolver() {
        InternalResourceViewResolver resolver=new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/jsp/");
        resolver.setSuffix(".jsp");     
        return resolver;
    }
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper=new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
}}