Question

css

.myStyle {
height: 10px;
background-image: url(../myImage.png);
}

jsp

<img class=myStyle src=<% imageurl != null ? imageurl: (bacground-image property from my css)%> >

Is there any way to achieve this? I don't want to hardcode the default url in my code, to allow change of default image by just changing the css property.

Was it helpful?

Solution

What you really want is a property file - for example like this http://www.easywayserver.com/blog/java-resourcebundle-properties-file-jsp/

# image default
myimage.default=../myImage.png

and

<%@ page language="java" import="java.util.*" %>
<%
ResourceBundle resource = ResourceBundle.getBundle("commonVariable");
/// commonVariable.properties file will be in WEB-INF/classess  folder

String defaultImage=resource.getString("myimage.default");
.
.
.
if (imageurl==null) imageurl=defaultImage;

%>

<img class="myStyle" src="<%= imageurl  %>" />

Alternative if you must

https://stackoverflow.com/a/2104580/295783

function setImageFromBG(img) {
  var style = img.currentStyle || window.getComputedStyle(img, false),
  img.src = style.backgroundImage.slice(4, -1);
}

<img class="myStyle" src="<%= imageurl %>" onerror="setImageFromBG(this)" />

May loop if the bgimage code fails to give a good image too

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top