1

I have a Java string containing HTML/JS/CSS code like this (very simple example):

<div>Welcome</div>
<style type="text/css">
.title{
color:red
}
</style>
<script type="text/javascript">
var i=0;
for (i=0;i < 5;i++){
document.writeln("<div class='title'>" + i + "</div>");
}
</script>

I receive that string on the Java side.

What I want is to "render" that string as it will be displayed on the browser.

So, I want to obtain the following result on my Java side :

Welcome
0
1
2
3
4

Is there a method like this ?

String renderedHTMLJS = therenderingmethod(htmljsString);

How can I do this ?

Thank you

4
  • 3
    What do you mean by Java to evaluate that string ? What op you want? Commented Jan 4, 2012 at 8:50
  • You can try and use rhino (I use it for the regex engine), but it won't affect document (I think) Commented Jan 4, 2012 at 8:53
  • I mean to generate the output on the Java side. I don't know, maybe a function like this : if (generate(htmljsString).isEmpty){ System.out.println("the htmljsString won't generate something on the client browser");} Commented Jan 4, 2012 at 8:53
  • @RanRag I edited the post for more clarity. Commented Jan 4, 2012 at 9:04

1 Answer 1

3

Try using Rhino from Mozilla and using its integration libraries or by using the JDK 1.6 ScriptEngine facility.

For ScriptEngine Example take a look here- http://metoojava.wordpress.com/2010/06/20/execute-javascript-from-java/

Sign up to request clarification or add additional context in comments.

7 Comments

AFAIK, ScriptEngine is for scripting only. It cannot "renders" the HTML part.
Should be fine, but a document object will have to injected into the context, doesn't have to be a DOM, just a mock object to capture data passed to writeln (and any other methods).
@vickirk In my example (ex : "<div>Welcome</div>" at the very top), some parts of the DOM are "static". Can ScriptEngine renders them ?
I agree with vickirk a DOM or any other object has to be introduced to pass the data to the methods.
@RanRag How do you inject static DOM to a JavaScript Engine ? it's like your are writing the following code : <script type="text/javascript"><b>Welcome</b></script> which is totally wrong. May be am I missing something? can you show us some code ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.