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...

download Lotto Heaven HD Lottery Game for free

download Lotto Heaven HD Lottery Game for free Lotto Heaven HD: Lottery Game Cards & Casino Download .apk Tired of the same old free card games? Try Lotto Heaven, the fun new lottery scratch-off card game. Its ridiculously addicting! While it wont make you lottery numbers luckier, it is a great way to wait for your powerball or megamillions lottery results to come in. Youre a scratch card millionaire waiting to happen! Download .apk If you live in Boston, Los Angeles, Philadelphia, Chicago, Seattle, New York, Kansas City, Toronto, San Francisco or London , you want to read this. However, we have the kick ass new poster for The Dark Knight debuted as part of the ongoing viral marketing game download Lotto Heaven HD: Lottery Game 1.101 apk . The site where it was discovered is on whysoserious.com / itsallpartoftheplan /. However, the website indicated that more would come and now its been updated. A new viral hunt is on Monday, said the 28th April in cities before and this time ...