当图像源是servlet时如何显示默认图像? [英] How to display a default image when image source is a servlet?

查看:65
本文介绍了当图像源是servlet时如何显示默认图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的JSP/Servlet设置中,为了显示用户概要文件图像,我通过在src标记中指定servlet URL,然后指示img标记从servlet获取图像,然后返回图像以响应servlet.

In my JSP/ Servlet setup, for displaying user profile images I am directing the img tag to get the image from servlet by specifying servlet URL in src tag and then returning image in response from servlet.

Sevlet在收到图像请求后会执行以下操作,

Sevlet does below things upon receiving an image request,

  1. 它以BLOB格式从数据库获取图像
  2. byte []和
  3. 准备图像
  4. 使用适当的标题返回response对象中的图像.
  1. It gets the image from database in BLOB format
  2. Prepares image from the byte[] and
  3. returns the image in response object with appropriate headers.

我的问题是,因为注册"页面没有图像上传选项,所以新用户的数据库中没有图像,即BLOBNULL. 如何为所有此类用户显示默认图像?

My problem is since Signup page doesn't has image upload option so new users don't have their image in database i.e. so the BLOB is NULL. How can I display a default image for all such users ?

编辑 根据收到的评论,我只想指出这一点.我知道解决方案,我们在数据库中(创建用户时)设置默认值,或者在数据库中存在NULL时返回默认图像数组. 我已经在使用后一种情况.这个问题,我只想讨论任何其他可能的解决方案.

EDIT Based on comments received I just wanted to note that. I am aware of the solutions where we set the default value either in database (while creating the user) or return the default image array when there is NULL in database. I am already using the later case. By this question I just wanted to discuss about any other possible solutions.

推荐答案

一个选项可能是当用户没有图像时返回HTTP错误404未找到".对我来说,这很合逻辑,因为用户确实没有图像.

One option could be to return HTTP error 404 "Not found" when the user don't have an image. It seems quite logical to me, since there really is no image for the user.

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

然后,您可以在HTML中使用 onerror事件来设置这种情况默认图片:

Then in your HTML you can handle this case using the onerror Event to set the default image:

<img src="servletUrl" onerror="this.src='default.png'" width="150" height="150" />

这样,servlet仅发送用户图像,如果用户没有图像,则不执行任何特殊逻辑.

In this way the servlet only sends user images and does not do any special logic if the user doesn't have one.

这篇关于当图像源是servlet时如何显示默认图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆