开发者

Avoid writing HTML by coding in Java

开发者 https://www.devze.com 2023-01-25 16:20 出处:网络
I want to avoid writing <table></table> and other stuff like that, by writing Java (or Python) classes. Example:

I want to avoid writing <table></table> and other stuff like that, by writing Java (or Python) classes. Example:

Html html = new 开发者_Python百科Html(); obj.setCoordinates(120,50); html.add(obj);

Which API is the best for this ?

Update

I'm currently trying Vaadin, a Java web framework which extends GWT. It offers web functionality with a coding style similar to a desktop API.


You might try something like GWT. It's a widget library where you code in Java and it is compiled into Javascript, with the DOM/HTML being created when you load the page.

I'm not sure I'd recommend it for content that is relatively static from an interaction standpoint (not using Javascript after loading, not using AJAX, etc). It's primarily meant to be a Web app platform, not a way to use Java as your presentation layer.


There was Jakarta ECS, but its retired now. Alternatively you can use a Java based template engine: Apache velocity


Ditto to Mr Garrison's comment.

I presently work on a system that's filled with functions that write HTML. So instead of writing, say,

out.println("<input name=x size=10 value='foo'>")

by the clever use of a set of HTML tag objects, they simply write:

InputTag x=new InputTag();
x.setName("x");
x.setSize(10);
x.setValue("foo");
out.println(x.toHtml());

Yeah, that saves so much work!


I might be misunderstanding your question. Like others say, it's an extremely bad idea to move all of the HTML generation into your code in terms of printing out HTML elements. A better approach is to create a template for the HTML you're trying to create, leaving holes into which you insert your dynamic content (e.g. you have a place where the rows of your tables will be inserted. I use StringTemplate and it sounds good for what you're trying to do. See the Fill A Table example in this introductory page


I actually wrote some classes & code for doing the type of thing you're thinking of, in Python. I'd really recommend using Python over Java for this. And as to some of the comments, yes it WAS easier. I didn't have to worry about escaping, quoting or matching the closing so much, as the code was constructed to look for an objects members and format them as attributes in the html output. Python's introspection is great for this.

0

精彩评论

暂无评论...
验证码 换一张
取 消