ssm云服务器如何访问图片
ssm(spring springmvc mybatis)作为目前比较流行的java web开发框架,已经被广泛应用到各种项目中。有时我们需在ssm项目中加载展示图片,那么如何访问图片呢?
一、将图片上传到服务器
在ssm项目中,我们一般将图片上传到服务器。服务器上的文件夹可以通过apache-tomcat(应用服务器)或ftp服务器来实现。以tomcat为例:
1.在tomcat安装目录下的webapps文件夹中新建一个文件夹,例如“images”,用于存放图片。
2.在web.xml文件中配置servlet-mapping。配置servlet-mapping来对所有请求到该servlet进行拦截,对输入的uri进行解析,然后输出指定的文件。
“`
imageservlet
com.xxx.imageservlet
imageservlet
/images/*
“`
3.编写imageservlet类,通过response.getoutputstream()将图片写入response输出流。
“`
file imagefile = new file(imagepath);
fileinputstream fileinputstream = new fileinputstream(imagefile);
bufferedinputstream buffinputstream = new bufferedinputstream(fileinputstream);
byte[] buffer = new byte[buffinputstream.available()];
buffinputstream.read(buffer);
buffinputstream.close();
response.getoutputstream().write(buffer);
response.getoutputstream().flush();
response.getoutputstream().close();
“`
以上步骤完成后,就可以将图片上传到服务器中了。
二、前台代码引入图片
在前台引入图片的方式:
“`
“`
其中,“${pagecontext.request.contextpath}”代表了当前应用在服务器上的根路径。如上面的tomcat配置,图片放在“images”文件夹中,即可通过“/images/图片名”访问到图片。
三、图片的封装
在实际开发中,我们往往会将图片封装成一个类,通过类的方法进行加载。
“`
public class imageutil {
/
* 获得图片流
*
* @param imagepath 图片路径
* @return inputstream
*/
public static inputstream getinputstream(string imagepath) {
file imagefile = new file(imagepath);
if (!imagefile.exists()) {
return null;
}
try {
return new fileinputstream(imagefile);
} catch (filenotfoundexception e) {
e.printstacktrace();
}
return null;
}
/
* 获得图片展示的url
*
* @param imagename
* @return
*/
public static string getimageurl(string imagename) {
string urlpath = \”/images/\”;
string realpath = imageutil.class.getresource(\”/\”).getpath() urlpath imagename;
return realpath.replaceall(\”\\\\\\\\\”, \”/\”);
}
}
“`
四、图片的缓存
我们加载图片时,往往会将图片缓存到本地。图片的缓存有利于网络传输、加快页面加载速度。
下面是一个简单的图片缓存代码:
“`
private static concurrenthashmap<string, softreference> cache = new concurrenthashmap<string, softreference>();
public static bufferedimage getimage(string imagename) {
softreference reference = cache.get(imagename);
bufferedimage image = null;
if (reference != null) {
image = reference.get();
}
if (image == null) {
image = loadimage(imageutil.getimageurl(imagename));
if (image != null) {
cache.put(imagename, new softreference(image));
}
}
return image;
}
“`
以上就是ssm云服务器如何访问图片的方法,同时也让我们更深一步地了解了java web开发的一些基础知识。
以上就是小编关于“ssm云服务器怎么访问图片”的分享和介绍
个人.com注册域名需要身份证吗 个人一次最多可以注册多少个.com域名cc域名是什么?双拼cc域名价值怎么样?创建域名邮箱的流程有哪些 域名邮箱特色功能是什么这个域名解析没问题但网站打不开云计算容量管理的重要性及其实现方法百度云服务器怎么远程如何在腾讯云服务器上建网站网站模板模板怎么建设 b2c商城网站模板介绍