5

I have a jsp file ,like this :

<html>
<head>
     <script type="text/javascript">
       var type=<bean:write name="class" property="type" />  
     </script> 

     <style type="text/css">
        .td-type1
        {
            width: 10mm;
        }
        .td-type2
        {
            width: 20mm;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <td class="td-type1">
            </td>
        </tr>
    </table>
</body>
</html>

My question is: How to change css dynamically base on type value? For example, if type equal 2, then the css class of td-type2 should be used for td tag. should I use .properties file to save all config or multi css files or ...?

Mina
  • 139
  • 1
  • 4
  • 19

1 Answers1

9

You can append the request attribute's value to the class attribute in the JSP :

<td class="td-type<%=type%>">

As a side note, the use of scriptlets (java code in JSP's) is strongly discouraged. Use JSTL and EL instead. In this question you'll find out Why and how to avoid Java Code in JSP files.

<td class="td-type${type}">

Or, if you wanted to implement an if-else like construct, for instance :

<c:choose>
    <c:when test="${type eq "2"}">
        <c:set var="varclass" value="td-type2"/>
    </c:when>
    <c:otherwise>
        <c:set var="varclass" value="td-type1"/>
    </c:otherwise>
</c:choose>
<td class="${varClass}">
Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • I use struts to get type variable,does it make any difference to ur answer? – Mina Feb 08 '13 at 16:42
  • @Mina It's been a long time since I've last used it, but if I remember correctly, you'll have some kind of form bean available as a request attribute. It should be the same, accessing the bean's property in the EL expression. – Xavi López Feb 08 '13 at 17:38