Html 在 thymeleaf spring 框架中插入本地目录中的图像(使用 maven)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29460618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:47:13  来源:igfitidea点击:

Inserting an image from local directory in thymeleaf spring framework (with maven)

htmlspringmaventhymeleaf

提问by undefined

I have developed a project using this link: https://spring.io/guides/gs/serving-web-content/I used maven to develop above project.

我使用此链接开发了一个项目:https: //spring.io/guides/gs/serving-web-content/我使用 maven 开发了上述项目。

I have two html files under this. abc.html and xyz.html. To insert images in the html page, I have used the url like this:

我在这个下面有两个 html 文件。abc.html 和 xyz.html。要在 html 页面中插入图像,我使用了这样的 url:

<img src="https://example.com/pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px">

But I want to use an image file located in my server instead. I tried placing the file in the same directory of html file but its not working. I even tried giving full path but of no use. This is an ubuntu OS. Please help me out here. Is there any place where I can configure the base path or basically how to put an image from my local folder.

但我想改用位于我的服务器中的图像文件。我尝试将文件放在 html 文件的同一目录中,但它不起作用。我什至尝试给出完整路径但没有用。这是一个 ubuntu 操作系统。请帮帮我。有什么地方可以配置基本路径或基本上如何从本地文件夹中放置图像。

回答by Lucky

I want you to look into the Thymeleaf's documentation of Standard URL Syntaxand specifically the context-relative and server-relative url patterns.

我希望您查看 Thymeleaf 的标准 URL 语法文档,特别是上下文相关和服务器相关的 url 模式。

Context-relative URL:

上下文相关 URL:

If you want to link resources inside your webapp then you should use context relative urls. These are URLs which are supposed to be relative to the web application root once it is installed on the server. For example, if we deploy a myapp.war file into a Tomcat server, our application will probably be accessible as http://localhost:8080/myapp, and myappwill be the context name.

如果你想在你的 webapp 中链接资源,那么你应该使用上下文相关的 url。一旦 Web 应用程序安装在服务器上,这些 URL 就应该是相对于 Web 应用程序根目录的。例如,如果我们将 myapp.war 文件部署到 Tomcat 服务器中,我们的应用程序可能可以通过 http://localhost:8080/myapp 访问,而myapp将是上下文名称。

As JB Nizet the following will work for you as I have used thymeleaf personally in a webapp project,

作为 JB Nizet,以下内容对您有用,因为我在 webapp 项目中亲自使用了百里香叶,

<img th:src="@{/images/test.png}"/>

and the test.png should be under your project root inside the webapp folder. Something navigated through roughly like,

并且 test.png 应该在 webapp 文件夹内的项目根目录下。一些东西大致通过,

Myapp->webapp->images->test.png

Eg:

例如:

<img th:src="@{/resources/images/Picture.png}" />

Output as:

输出为:

<img src="/resources/image/Picture.png" />

When you hit http://localhost:8080/myapp/resources/images/Picture.pngin you browser then you should be able to access the image for the above syntax to work. And your resources folder will probably under webapp folder of your application.

当您http://localhost:8080/myapp/resources/images/Picture.png在浏览器中点击时,您应该能够访问图像以使上述语法起作用。您的资源文件夹可能位于您的应用程序的 webapp 文件夹下。

Server-relative URL:

服务器相对 URL:

Server-relative URLs are very similar to context-relative URLs, except they do not assume you want your URL to be linking to a resource inside your application's context, and therefore allow you to link to a different context in the same server

服务器相关 URL 与上下文相关 URL 非常相似,不同之处在于它们不假设您希望您的 URL 链接到应用程序上下文中的资源,因此允许您链接到同一服务器中的不同上下文

Syntax:

句法:

<img th:src="@{~/billing-app/images/Invoice.png}">

Output as:

输出为:

<a href="/billing-app/showDetails.htm">

The above image will be loaded from an application different from your context and if an application named billing-appis present in your server.

上面的图像将从与您的上下文不同的应用程序加载,并且如果billing-app您的服务器中存在名为应用程序的应用程序。

Sourced from: Thymeleaf documentation

来源:Thymeleaf 文档

回答by JB Nizet

You need to understand how HTTP works. When the browser loads a page at URL

您需要了解 HTTP 的工作原理。当浏览器在 URL 加载页面时

http://some.host/myWebApp/foo/bar.html

and the HTML page contains

并且 HTML 页面包含

<img src="images/test.png"/>

the browser will send a second HTTP request to the server to load the image. The URL of the image, since the path is relative, will be http://some.host/myWebApp/foo/images/test.png. Note that the absolute path is composed from the current "directory" of the page, concatenated with the relative path of the image. The path of the server-side JSP or thymeleaf template is completely irrelevant here. What matters is the URL of the page, as displayed in the address bar of the browser. This URL is, in a typical Spring MVC application, the URL of the controller where the initial request was sent.

浏览器将向服务器发送第二个 HTTP 请求以加载图像。由于路径是相对的,图像的 URL 将为http://some.host/myWebApp/foo/images/test.png. 请注意,绝对路径由页面的当前“目录”组成,并与图像的相对路径连接。服务器端 JSP 或 thymeleaf 模板的路径在这里完全无关。重要的是页面的 URL,显示在浏览器的地址栏中。在典型的 Spring MVC 应用程序中,此 URL 是发送初始请求的控制器的 URL。

If the path of the image is absolute:

如果图像的路径是绝对路径:

<img src="/myWebApp/images/test.png"/>

then the browser will send a second request to the URL http://some.host/myWebApp/images/test.png. The browser starts from the root of the web server, and concatenates the absolute path.

然后浏览器将向 URL 发送第二个请求http://some.host/myWebApp/images/test.png。浏览器从 Web 服务器的根开始,并连接绝对路径。

To be able to reference an image, whetever the URL of the page is, an absolute path is thus preferrable and easier to use.

为了能够引用图像,无论页面的 URL 是什么,绝对路径是首选且更易于使用。

In the above example, /myWebAppis the context path of the application, that you typically don't want to hard-code in the path, because it might change. Thankfully, according to the thymeleaf documentation, thymeleaf understands that and provides a syntax for context-relative paths, which thus transforms paths like /images/test.pnginto /myWebApp/images/test.png. So your image should look like

在上面的示例中,/myWebApp是应用程序的上下文路径,您通常不希望在路径中进行硬编码,因为它可能会更改。值得庆幸的是,根据thymeleaf 文档,thymeleaf 理解这一点并提供了上下文相关路径的语法,从而将路径/images/test.png转换为/myWebApp/images/test.png. 所以你的图像应该看起来像

<img th:src="@{/images/test.png}"/>

(I've never used thymeleaf, but that's what I deduce from the documentation).

(我从未使用过百里香叶,但这是我从文档中推断出来的)。

And the test.pngimage should thus be in a folder imageslocated under the root of the webapp.

test.png因此,图像应该images位于 webapp 根目录下的文件夹中。

回答by Minato

Get link on Internet:

在互联网上获取链接:

String src = "https://example.com/image.jpg";

HTML: <img th:src="@{${src}}"/>

HTML: <img th:src="@{${src}}"/>

回答by Enamul Haque

I have used bellow like..

我用过波纹管就像..

My image path is like bellow..

我的图像路径如下所示..

enter image description here

在此处输入图片说明

I have used bellow code for loading image

我使用了波纹管代码来加载图像

 <img th:src="@{imges/photo_male_6.jpg}" >

It is working fine for me.

它对我来说很好。

回答by Dosto

Recently I had similar issue, but in my case, the spring security was making a problem. As mentioned in other answers and documentation:

最近我遇到了类似的问题,但就我而言,弹簧安全性出了问题。如其他答案和文档中所述:

<img th:src="@{/img/values.png}" alt="Media Resource"/>

should be enough. But since the spring security has been added to my project, I had to all /img/** for get Requests and add addResourceHandlers. Here is the code:

应该够了。但是由于 spring 安全性已添加到我的项目中,我不得不将所有/img/** 用于 get Requests 并添加addResourceHandlers。这是代码:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(
                "/webjars/**",
                "/img/**",
                "/css/**",
                "/js/**")
                .addResourceLocations(
                        "classpath:/META-INF/resources/webjars/",
                        "classpath:/static/img/",
                        "classpath:/static/css/",
                        "classpath:/static/js/");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);

        http.authorizeRequests().antMatchers(HttpMethod.GET, "/js/**", "/css/**", "/img/**" ,"/pressiplus", "/public/**", "/index", "/", "/login").permitAll();
        http.authorizeRequests()
                .antMatchers("/secure/admin/**").hasAnyRole("ADMIN","USER")
                .antMatchers("/secure/admin/**").hasAnyRole("ADMIN")
                .and()
                .formLogin()  //login configuration
                    .loginPage("/login")
                    .failureUrl("/login-error")
                    .loginProcessingUrl("/login")
                    .usernameParameter("email")
                    .passwordParameter("password")
                    .successHandler(myAuthenticationSuccessHandler())
                .and()
                .logout()    //logout configuration
                .logoutUrl("/logout")
                .logoutSuccessHandler(myLogoutSuccessHandler)
                .and()
                    .rememberMe()
                        .tokenRepository(persistentTokenRepository())
                        .tokenValiditySeconds(7 * 24 * 60 * 60) // expires in 7 days
                .and()
                    .exceptionHandling() //exception handling configuration
                .accessDeniedHandler(accessDeniedHandler());
    }

}

I hope this helps someone in the future

我希望这对未来的人有所帮助