【问题标题】:WebMVC mapping .jsp Java-Based-Configuration without @ComponentScan没有@ComponentScan的WebMVC映射.jsp基于Java的配置
【发布时间】:2014-10-29 17:44:27
【问题描述】:

我在我的项目 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'

【问题讨论】:

  • 尝试使用 http://localhost:8080/{alpha}/world/hello/test.html,您缺少端口 (8080) 和 servlet 名称 world,如果您直接使用 Tomcat 或使用Context Root 如果您使用的是 IDE,则可以通过以下方式获取该值:在 IDE 中选择项目 -> 右键单击​​ -> 属性 -> Web 项目设置
  • 我的错,不是servlet-name,是url-pattern,从*.html改成/
  • @ManuelJordan Port 80 是正确的,因为我在控制台中得到了输出。 url-pattern 也是正确的,因为我在控制台中得到了输出。上下文根是正确的,因为我在控制台中得到了输出。 url 模式是正确的,因为我在控制台中得到了输出。
  • 您是否直接通过 IDE 工作?或者您在某些 Tomcat 中有 .war 文件?
  • @RequestMapping("test.html")改成@RequestMapping("/test.html"),怎么看添加/

标签: java spring jsp maven


【解决方案1】:

我在配置中错过了@Bean

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

而 foo 必须是这样的:

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

【讨论】:

    【解决方案2】:

    我还不能添加 cmets,所以将其发布为答案..

    您可以在Config.java 中包含以下 sn-p 到:

    • 避免在 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中定义视图解析器

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 2020-07-03
      • 2013-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 2016-03-13
      • 1970-01-01
      相关资源
      最近更新 更多