gpt4 book ai didi

java - 如何使用 JSP 使用 Spring MVC 显示图像

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:13:37 26 4
gpt4 key购买 nike

我很难使用带有 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 类:

@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 文件,它在我每次构建它时将生成的 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 文件的其余部分会正确显示,但照片不是,只有替代文本。对此问题的任何帮助将不胜感激。

最佳答案

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

Can't display images in JSP

基本上,我试图从 Web 服务器的根目录而不是我的 Web 应用程序的根目录加载资源。因此,为了引用 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>

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

关于java - 如何使用 JSP 使用 Spring MVC 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40025556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com