WebMVC映射.jsp基于Java的配置,不带@ComponentScan

时间:2014-10-29 17:44:28

标签: java spring jsp maven

我在项目hello中使用Spring的基于Java的配置。

这是我的配置:

@Configuration
@EnableWebMvc
public class Config{
    @Scope("session")
    public A a(){
        return new A();
    }
}

这是我的web.xml

<web-app>
  <servlet>
    <servlet-name>world</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>world</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
</web-app>

这是我的班级A

@Controller
public class A{
  @RequestMapping("test.html")
  public String foo(){
    return "bar";
  }
}

这是我的档案bar.jsp

abc

这是我的pom.xml

...
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.1.RELEASE</version>
    </dependency>
...

无论如何,如果我请求http://localhost/hello/test.html,我会得到一个空白页而不是abc和输出:

DispatcherServlet with name 'world' processing GET request for [/hello/test.html]
Looking up handler method for path /test.html
Did not find handler method for [/test.html]
No mapping found for HTTP request with URI [/hello/test.html] in DispatcherServlet with name 'world'

2 个答案:

答案 0 :(得分:0)

我在配置中错过了@Bean

@Configuration
@EnableWebMvc
public class Config{
    @Bean
    @Scope("session")
    public A a(){
        return new A();
    }
}

foo必须是这样的:

public String foo(){
   return "bar.jsp";
}

答案 1 :(得分:0)

我无法添加评论,因此将此作为答案发布..

您可以在Config.java中添加以下代码段:

  • 避免在foo方法中添加.jsp扩展名
  • 解析视图而无需添加@Bean注释
@Bean
public UrlBasedViewResolver setupViewResolver() {
  UrlBasedViewResolver resolver = new UrlBasedViewResolver();
  resolver.setPrefix("/WEB-INF/pages/");
  resolver.setSuffix(".jsp");
  resolver.setViewClass(JstlView.class);
  return resolver;
}

将前缀替换为Web应用程序中JSP的路径,您也可以在world-servlet.xml中定义视图解析器

相关问题