Skip to main content

EE Serlvet 3 Generating HTML output in Servlet

EE Serlvet 3 Generating HTML output in Servlet


If you just need to handle a handful of requests URI in your EE web module, then it might be easier to generate your own HTML response in your Servlet code instead of using a full blown template library. As part of my examples, I tried out a very simple Java DSL that generate html output when writing your own Serlvet. The code looks like this:

package zemian.servlet3example.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/index")
public class IndexServlet extends HtmlWriterServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HtmlWriter html = createHtmlWriter(req, resp);
        String message = getMessage(req, html);
       
        html.header()
            .h(1, "Welcome to Servlet 3 Example")
            .p("Lets explore Java Servlet 3.x Features.")
            .p(message)
            .ul(
                html.link("Index", "/index"),
                html.link("Hello", "/hello"),

                html.link("Sys Props", "/sys-props")
            )
            .footer();
    }

}

I wrote a base HtmlWriterServlet class that provide a method where you can get an instance of a HtmlWriter builder. The benefit of wrapping the HTML like builder is that its more easier to read and helps generate correct well form tags. For example the "ul" and "table" accepts Java List or Map object, and it generates the correct html tags.

Here is another example how I generate a table view of Java System Properties page with few lines of code:

package zemian.servlet3example.web;

import java.io.IOException;
import java.util.TreeMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/sys-props")
public class SysPropsServlet extends HtmlWriterServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HtmlWriter html = createHtmlWriter(req, resp);
        TreeMap sysProps = new TreeMap(System.getProperties());
        html.header()
            .h(1, "Java System Properties")
            .table(sysProps)
            .footer();
    }
}



The simple HtmlWriter class provide few html builder methods and it can help generate HTML links with relative context paths. You can easily further improve it to help generate more HTML code such as form tags etc.

Also, note that ServletResponse object let you have full control on writing custom responses, so you are not restricted to only returing HTML. You can write binary output such as PDF or even MP3 files. You simply need to control the Response Writer and the correct corresponding content mime type and size that will return.


You can get these code at servlet3-example

download file now

Popular posts from this blog

ElasticSearch query with AND and OR criteria

ElasticSearch query with AND and OR criteria Frequently when we will need to construct query to elasticsearch which bear AND and OR criteria similar to the following SQL statements: Statement 1: SELECT * FROM tblOrder WHERE orderDate=2015-01-01 14:00:00 AND customerID=29439; Statement 2: SELECT * FROM tblOrder WHERE orderDate=2015-01-01 14:00:00 OR customerID=29439; Statement 3: SELECT * FROM tblOrder WHERE orderDate <= 2015-01-01 14:00:00 AND customerID=29439; Statement 4: SELECT * FROM tblOrder WHERE (orderDate=2015-01-01 14:00:00 AND customerID=29439) OR customerID = 20991; Statement 5: SELECT * FROM tblOrder WHERE orderDate=2015-01-01 14:00:00 AND (customerID=29439 OR customerID = 20991); In ElasticSearch, we use "must" and "should" in place of AND and OR and "bool" in place of WHERE. Suppose in our ElasticSearch (at 179.168.0.1:9200), we have indexed documents having the following structures at index myOrder/myOrder: { "orderID" : xxxxx, ...

Endomondo Sports Tracker PRO v10 2 4 Full APK

Endomondo Sports Tracker PRO v10 2 4 Full APK ? Endomondo Sports Tracker PRO v10.2.4 Full APK. They mock fitness with this personal trainer and social fitness partner . Endomondo is the first application of its kind on Android and is ideal for running, cycling , hiking and other activities on the basis of distance. Join 10 million users and begin to free your endorphins ! This is the PRO version of the popular Endomondo Sports Tracker ! Please see What's New in Google Play for latest updates . PRO features : * Go programs : choose from three audio programs or create your own and let the coach guide * Graphics Card: graphics display your lap times , heart rate , speed and altitude throughout the workout * Beat you: Set a previous workout as target and the audio coach will help you perform better this time * The low power mode : Increase the battery timeout using this function for long workouts * Final goal : Choose a duration for your workout and the audio coach session will help...

Eclipse Android on Linux Mint 13 Maya

Eclipse Android on Linux Mint 13 Maya So far, my previous blogs on Linux Mint 13 has described how to install Java and the Android SDK. If you have followed the blogs, you will now be ready for the next step towards Android software development and that is to install a Java programming environment called Eclipse. Of course, first we have to install this (if it has not been installed yet). The install process is very simple - you can use either Synaptic or the command line to carry out this job. To use Synaptic, start Synaptic, enter your password, then type eclipse into the search box. The entry for Eclipse will appear - mark it for installation, and the rest of the additional items, and then click on the Apply button. Wait for download and install process to finish, close Synaptic and you are done! To use the command line, start a terminal, and type: sudo apt-get install eclipse Type Enter when prompted, wait for the packages to be downloaded and installed, close the terminal and you ...