如何在图像源是servlet时显示默认图像?

时间:2021-11-21 11:50:11

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.

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

Sevlet does below things upon receiving an image request,

Sevlet在收到图片请求时会做以下事情,

  1. It gets the image from database in BLOB format
  2. 它以BLOB格式从数据库中获取图像

  3. Prepares image from the byte[] and
  4. 从字节[]和。准备图像

  5. returns the image in response object with appropriate headers.
  6. 使用适当的标头返回响应对象中的图像。

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 ?

我的问题是,因为注册页面没有图像上传选项,所以新用户没有他们的图像在数据库,即所以BLOB是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.

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

1 个解决方案

#1


1  

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.

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

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

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

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

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

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

通过这种方式,servlet只发送用户图像,如果用户没有,则不会执行任何特殊逻辑。

#1


1  

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.

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

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

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

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

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

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

通过这种方式,servlet只发送用户图像,如果用户没有,则不会执行任何特殊逻辑。