PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

java web中如何添加图片

angryTom
angryTom 原创
2020-02-10 11:16:33 7679浏览

java web中如何添加图片

对于java可视化界面插入背景图片只需要background-image:url(图片路径)就行,而对于web项目中,并非如此

<div class=&#39;ban&#39;  style="max-width:90%">

效果如下:

1.png

我们就需要在jsp页面中写Java代码,让Java来获取项目的根路径,通过绝对路径的方式引入这些图片文件。我们则需要在jsp文件的开头写入下面的代码。

<%
String path = request.getContextPath();
String basePath=null;
basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
int port=request.getServerPort();
if(port==80){
    basePath=request.getScheme()+"://"+request.getServerName()+path;
}else{
    basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
}
request.setAttribute("basePath", basePath);
%>

这几段代码只是获取基本的路径,而request就是我们常说的JSP九大隐式对象之一,JSP就是Servlet,request.setAttribute("basePath", basePath) 表示将得到的basePath(项目根路径)存放到request作用域中,但是到这里我们还是不能把图片显示出来,我们需要在图片路径前面加入这行代码$。如下:

<div class=&#39;ban&#39; style="height:100%;background-image:url(&#39;${basePath}/img/qx.jpg&#39;)">

2.png

(相关视频教程分享:java视频教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。