在JSP中显示图像(Spring 3 java配置)

时间:2014-05-08 14:04:28

标签: java spring jsp spring-mvc

我现在正在学习Spring java配置,我想在我的.jsp页面中显示一个图像。我搜索了很多。这个问题很受欢迎,但仍然没有答案帮助我。图像仍然没有出现。如果有人可以帮助我,我会很高兴。

我的目录树:

-src
--main
---java
----com
-----app
------controller
-------MainController.java
------springconfig
-------WebConfig.java
--webapp
---resources
----images
-----11706.jpg
----styles
---WEB-INF
----view
-----home.jsp
----web.xml
---index.jsp

MainController.java

@Controller
@RequestMapping("/home")
public class MainController {

  @RequestMapping(method = RequestMethod.GET)
  public String loadHomePage(Model m) {
    m.addAttribute("name", "CodeTutr");
    return "home";
  }
}

WebConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.app.controller")
public class WebConfig extends WebMvcConfigurerAdapter {

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

  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
      configurer.enable();
  }

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

}

针对home.jsp

<!DOCTYPE HTML>
<html>
<head>
<title>Sample Application</title>
</head>
<body>
    <h1>Hello, ${name}!!!</h1>
    <img src="/resources/images/11706.jpg" />
</body>
</html>

的web.xml

<servlet>
        <servlet-name>sample</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.app.springconfig</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>sample</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

很抱歉这么多代码段。希望它能帮助解决问题

2 个答案:

答案 0 :(得分:1)

作为另一种解决方案,Spring拥有自己的标记库,允许您输出相对于应用程序路径的URL。

在JSP文件的开头,您必须包括:

<%@ taglib prefix="s" uri="http://www.springframework.org/tags" %>

然后使用标记创建图片网址:

<img src="<s:url value="/resources/images/11706.jpg" />" />

答案 1 :(得分:0)

也许您应该尝试使用<c:url var="imageUrl" value="/resources/images/11706.jpg">模式。然后你会<img src="${imageUrl}"></img>。或者,使用div来保存图像,并使用css将其加载到div中。您还需要使用页面顶部的<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>导入jstl taglib,并且您需要确保将jstl作为模块依赖项才能使其正常工作。