从redis获取图片展示到jsp

本文介绍了如何创建Redis数据库连接,并在Struts框架中配置,实现从Redis获取图片数据并展示在JSP页面上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


创建redis数据库的连接

package com.gmt.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
 * xutengteng
 * 2017.3.24
 * */
public class RedisUtil {

	  
    //Redis服务器IP
    private static String ADDR = "192.168.1.108";
    
    //Redis的端口号
    private static int PORT = 6379;
    
    //访问密码
    private static String AUTH = "admin";
    
    //可用连接实例的最大数目,默认值为8;
    //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
    private static int MAX_ACTIVE = 1024;
    
    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
    private static int MAX_IDLE = 200;
    
    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
    private static int MAX_WAIT = 10000;
    
    private static int TIMEOUT = 10000;
    
    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
    private static boolean TEST_ON_BORROW = true;
    
    private static JedisPool jedisPool = null;
    
    
    /**
     * 初始化Redis连接池
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxActive(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWait(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }
}


package com.gmt.redis;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化和反序列化工具类
 * xutengteng
 * 2017.3.24
 * */
public class SerializeUtil {
	
	
	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			// 序列化
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			byte[] bytes = baos.toByteArray();
			return bytes;
		} catch (Exception e) {

		}
		return null;
	}

	
	public static Object unserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		try {
			// 反序列化
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {

		}
		return null;
	}
}

创建mysql数据库连接并且从数据库中获取图片的信息

package com.gmt.redis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UploadImage {

	public static void updateShoopingState(long roleId, long time, int goodsId) {

		// 声明Connection对象
		PreparedStatement psql = null;
		Connection con = null;
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/gameserver";
		String user = "root";
		String password = "123456";
		try {
			Class.forName(driver);
			con = DriverManager.getConnection(url, user, password);
			String sql = "UPDATE shooping_kind set state=1 WHERE goods_id=? and role_id=? and time=? and state=0";
			psql = con.prepareStatement(sql);
			psql.setInt(1, goodsId);
			psql.setLong(2, roleId);
			psql.setLong(3, time);
			psql.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (con != null) {
					con.close();
				}
				if (psql != null) {
					psql.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

从redis数据库中获取图片

package com.gmt.redis;

import redis.clients.jedis.Jedis;

public class UploadRedisManager {

	/**上传图片*/
	public static final String UPLOAD = "UPLOAD_IMAGE";
	
	/**添加图片信息到redis
	 * imgSrc  上传的路径
	 * */
	public static void addUploadImage(String imageName,byte [] byteArray){
		// -----添加数据----------
		if(byteArray == null){
			return;
		}
		try {
			Jedis jedis = RedisUtil.getJedis();
			jedis.set(imageName.getBytes(), byteArray);
			jedis.save();
			RedisUtil.returnResource(jedis);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void deleteUploadImage(String imageName){
		// -----删除数据----------
		try {

			Jedis jedis = RedisUtil.getJedis();
			jedis.del(imageName);
			jedis.save();
			RedisUtil.returnResource(jedis);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取redis自制关卡图片数据
	 * */
	public static byte[] getUpLoadIMG(String imageName) {
		byte[] back = null;
		try {
			Jedis jedis = RedisUtil.getJedis();
			back = jedis.get(imageName.getBytes());
			RedisUtil.returnResource(jedis);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return back;
	}
	
	/**
	 * 获取redis自制关卡图片数据
	 * */
	public static byte[] getUpLoadIMG(int id) {
		StringBuffer sb = new StringBuffer();
		sb.append("UPLOADIMG");
		sb.append(id);
		byte[] back = null;
		try {
			Jedis jedis = RedisUtil.getJedis();
			back = jedis.get(sb.toString().getBytes());
			RedisUtil.returnResource(jedis);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return back;

	}
}


获取redis中的图片
package com.gmt.action;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.gmt.redis.UploadRedisManager;
import com.opensymphony.xwork2.ActionSupport;

public class ShowUploadAction extends ActionSupport{

	private static final long serialVersionUID = 1L;
	
	private int id ; //图片的id
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	/**查询自制关卡*/
	public String showUpload(){
		ServletOutputStream output = null;
        try {
        	HttpServletResponse response = ServletActionContext.getResponse();
            output = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte [] uploadImageArray = UploadRedisManager.getUpLoadIMG(id);
			output.write(uploadImageArray);
			output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	try {
        		if (output != null) {
                	output.close();
        		}
        	} catch (Exception e) {
        		e.printStackTrace();
        	}
        }
		return null;
	}
	
}


struts.xml中配置

 <action name="showUploadAction" class="com.gmt.action.ShowUploadAction" method="showUpload">

在jsp中配置

<img src="showUploadAction.action?id=<%=id%> & response=<%=response%>"
						alt="<%=uploadName%>" width="100" height="118" align="middle" >
注:id, response, 都是传的参数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值