java web中如何添加图片

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

效果如下:

我们就需要在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作用域中,但是到这里我们还是不能把图片显示出来,我们需要在图片路径前面加入这行代码$。如下:

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

更多推荐

java web工程中如何添加图片_java web中如何添加图片