Java – how to use dynamic CSS in JSP files based on param values

I have a JSP file as follows:

<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 do I dynamically change CSS based on type values? For example, if type equals 2, then the CSS class of TD - type 2 should be used for the TD tag I should use it Properties file to save all configurations or multiple CSS files, or?

Solution

You can attach the value of the request attribute to the class attribute in the jsp:

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

As a side note, it is strongly recommended not to use scriptlets (Java code in JSPS) Use JSTL and El instead In this question, you will find why and how to avoid java code in JSP files

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

Or, if you want to implement an if else like construct, for example:

<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}">
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>