DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Approach Java, Databases, and SQL [Video]
  • Embed a Spreadsheet Into Your Web App
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Handling Embedded Data in NoSQL With Java

Trending

  • Start Coding With Google Cloud Workstations
  • Segmentation Violation and How Rust Helps Overcome It
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  1. DZone
  2. Coding
  3. Languages
  4. Java HTML Report in a Few Lines of Code

Java HTML Report in a Few Lines of Code

A practical example of how to build real-world applications in Java and create a simple but useful front-end with basic HTML.

By 
Pavel Ponec user avatar
Pavel Ponec
·
Updated May. 12, 21 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
9.6K Views

Join the DZone community and get the full member experience.

Join For Free

Today I’d like to show you a simple table HTML report created with only thirteen lines of source code, written in a single command line using the Java programming language. Let’s pretend the data provision service already exists. If we wanted to offer our users some simple (sequential) content filtering for a table with column sorting, our implementation will have to add a few extra lines of code. To optimize this filtering, we’ll need to dig deeper into the backend. The web component takes its data from an object of type Stream, and so the maximum volume of presented data is limited only by the capabilities of our web browser. For my data source I used a freely available list of hotels in CSV format and it shouldn’t matter that some of the information it contains isn’t up to date. Let’s take a look at the body of the doGet() method of our trusty old Java servlet for those thirteen lines of code we mentioned. We’ll assemble the model of our table using the ReportBuilder class from the Ujorm framework.

Java
 




xxxxxxxxxx
1
14


 
1
new ReportBuilder<Hotel>("Simple Hotel Report")
2
        .add(hotel -> hotel.getName(), "Hotel", NAME).sortable(true)
3
        .add(hotel -> hotel.getCity().getName(), "City", CITY).sortable()
4
        .add(hotel -> hotel.getStreet(), "Street").sortable()
5
        .add(hotel -> hotel.getPrice(), "Price").sortable()
6
        .add(hotel -> hotel.getCurrency(), "Currency")
7
        .add(hotel -> hotel.getPhone(), "Phone")
8
        .add(hotel -> hotel.getStars(), "Stars").sortable()
9
        .setFooter(e -> e.addText("Data source: ").addLinkedText(HOTELBASE, HOTELBASE))
10
        .build(input, output, builder -> selectHotels(builder,
11
                        DEFAULT_ROW_LIMIT,
12
                        NAME.of(input),
13
                        CITY.of(input)));


Each call to the add() method adds another column to our table. The first argument of this method contains the code for getting the contents of a table cell, the second contains the name of the column header. If we want to filter the column, we also pass a constant representing the HTTP parameter of the web page. To support sorting, we add a call to the sortable() method, whose (optional) parameter determines the direction of sorting, but this is only for graphical representation of the data, the following method takes care of the actual sorting of the data. Due to licensing terms and conditions, we have to add a link to the original data project, inserted in the footer using the setFooter() method. The title of the HTML page is generated implicitly from the text provided in the constructor of the builder, however, using the setHeader() method, we can replace it with our own implementation. The build() method then calls the data source method, with the attached code:

Java
 




xxxxxxxxxx
1
12


 
1
private Stream<Hotel> selectHotels(GridBuilder<Hotel> builder,
2
        int limit,
3
        @Nonnull String namePattern,
4
        @Nonnull String cityPattern) {
5
    final String nameUp = namePattern.toUpperCase();
6
    final String cityUp = cityPattern.toUpperCase();
7
    return service.loadHotelStream()
8
            .filter(t -> nameUp.isEmpty() || t.getName().toUpperCase().contains(nameUp))
9
            .filter(t -> cityUp.isEmpty() || t.getCityName().toUpperCase().contains(cityUp))
10
            .sorted(builder.getSortedColumn().getComparator(Hotel::getName))
11
            .limit(Math.max(0, limit));
12
}


To ignore character case, we start by converting the values of the parameters to capital letters, but how we go about implementing an appropriate filter is up to us. If the data type of the column implements the Sortable interface, we can sort using a comparer provided by the GridBuilder object, otherwise we have to write the implementation ourselves. And, finally, we limit the number of rows to return only the top amount. With large amounts of data, it would be more appropriate to switch the last two lines, so as to sort only a smaller number of records. I’d also like to point out, that all our HTTP POST requests should be directed toward the servlet’s doGet() method. That should be everything important, after running the project we should get a result similar to the one in the following image:

As the screenshot indicates, the table is automatically redrawn on any change of the text filter, and although the page also works in browsers without JavaScript support, we’ll have to confirm our filter values by pressing the Enter key. The AJAX behavior can also be suppressed programmatically – using the method setAjaxEnabled(false). All the parameters of the page’s form can be set using URL parameters, the ReportBuilder object doesn’t save any values to the Session.

Conclusion

It’s true that the ReportBuilder provides more than just the rendering of the table, instead it takes care of the whole page. The table itself is rendered using the GridBuilder class, in this example we can see how such components could be assembled into a greater whole. The solution relies on objects from the Element class, as was mentioned in the last blog post.

To run the project, you’ll need JDK version 8 and a web browser with support for JavaScript Vanilla ES6, but the JavaScript used here doesn’t require any further libraries. The whole project is now freely available on GitHub. The project can be run in Windows using the run.cmd script (on Linux using the run.sh script). On first execution, the necessary libraries will be downloaded. Next time we’ll take a look at the possibility for cell formatting in this table.

Useful Links

  • Project on GitHub
  • JavaDoc for ReportBuilder a Element classes
  • A Simple AJAX Website in Java (an Element class introduction)
HTML Database Java (programming language)

Published at DZone with permission of Pavel Ponec. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Approach Java, Databases, and SQL [Video]
  • Embed a Spreadsheet Into Your Web App
  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Handling Embedded Data in NoSQL With Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!