views:

326

answers:

2

i Want to import a given css or javascript file depending os some conditions, in my Servlet i have:


protected void doPost(...)
{
   if(condition)
   {
     //import some javascript or css file here
   }

}

I need this behavior since i have too many files to import and the files name may vary according to the condition. Is it possible?

+1  A: 

Are you trying to insert Javascript and CSS into the dom? I would do that from the client side. I mean, it is possible to do it by explicitly writing out the code for <script...> or <link...>. A better way to do it is to send something back to the client that tells it to add a stylesheet or Javascript.

Then you can add it dynamically like so:

If this doesn't need to be done dynamically, then it is even easier. Simply set a flag and in your JSP or ASP, check the state of the flag. Within the conditional tag, you will add the code for your CSS and Javascript. However, I am assuming from your question that it is the former.

Vivin Paliath
+2  A: 

Sort of, yes.

boolean condition = evaluateItSomehow();
request.setAttribute("condition", condition);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

Then in page.jsp using JSTL c:if:

<head>
    <c:if test="${condition}">
        <link rel="stylesheet" type="text/css" href="style.css">
        <script type="text/javascript" src="script.js"></script>
    </c:if>
    ...
</head>

Update: since you seem to have more than one files for this, you can even make it more flexible by just setting the desired filename suffix (or prefix, or even the entire name, what you like):

String suffix = evaluateItSomehow();
request.setAttribute("suffix", suffix);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

and

<head>
    <link rel="stylesheet" type="text/css" href="style_${suffix}.css">
    <script type="text/javascript" src="script_${suffix}.js"></script>
    ...
</head>

If you set suffix to for example "foo", this will load style_foo.css and script_foo.js. I think this gives enough new insights.

BalusC