【问题标题】:How to display an image with Spring MVC using JSP如何使用 JSP 使用 Spring MVC 显示图像
【发布时间】:2016-10-13 15:48:01
【问题描述】:

我很难使用带有 JSP 的 Spring MVC 来显示图像。我知道还有其他非常相似的 SO 问题,但这些问题的答案似乎都不起作用。

我有一个非常简单的项目,只有两个 java 文件和一个 JSP 文件要显示。这是我的 WebMvcConfigurerAdapter 类:

@Configuration
@ComponentScan(basePackages="com.rigatron.rigs4j")
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{

@Bean
public ViewResolver getViewResolver(){
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**")
            .addResourceLocations("/resources/");
}

这是我主页的控制器类:

@Controller
public class HomeController {

@RequestMapping(value="/")
public ModelAndView test(HttpServletResponse response) throws IOException {
    return new ModelAndView("home");
}

这是 JSP 文件中我尝试显示图像的行:

<img src="/resources/old.jpeg" alt="Photo of Youthful William" id="pic" />

我的 /resources/ 文件夹中有 old.jpeg。页面的其余部分显示正常,但此处仅显示替代文本。

我正在使用 Tomcat8 部署这个应用程序,我的 Maven pom 文件是我的 Maven pom 文件,它在每次构建时将生成的 WAR 文件复制到 Tomcat 的 webapps 目录中:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <configuration>
    <outputDirectory>C:\my\local\dir\tomcat8\webapps</outputDirectory>
  </configuration>
</plugin>

所以当我使用浏览器导航到 localhost:8080/myprojectname 时,JSP 文件的其余部分会正确显示,但照片不是,只有 alt 文本。对此问题的任何帮助将不胜感激。

【问题讨论】:

    标签: java spring jsp spring-mvc


    【解决方案1】:

    好的,我知道我哪里出错了。这篇 SO 帖子为我指明了正确的方向:

    Can't display images in JSP

    所以基本上,我试图从 web 服务器的根目录而不是我的 webapp 的根目录加载资源。因此,为了引用 webapp 的根目录,我包含了这两行:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    

    ...

    <img src="<c:url value='/resources/old.jpeg'/>" alt="Photo of Youthful William" id="pic" />
    

    为了使用这个 JSTL 标签,我必须包含这个 Maven 依赖项:

    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    

    对于可能过早发布此问题,我深表歉意,但我将保留它,希望它可以帮助其他人。

    【讨论】:

      猜你喜欢
      • 2013-12-20
      • 2018-01-02
      • 2011-10-21
      • 2018-12-06
      • 2013-02-24
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多