• About Us
  • Blog
  • Basket
  • Account
  • Sign In
  •  

Enable device detection by extending BaseServelet

Introduction

This guide explains how to deploy device detection using BaseServlet class supplied by 51Degrees instead of the HttpServlet default servlet class. If you wish to implement device detection using HttpServlet please visit the Standard Servlet page. This guide contains detailed instructions and takes you through the process of creating Java web project, adding servlets, editing servlet content and finally integrating 51Degrees BaseServlet. If you have an existing web project and want to learn how to integrate the detector feel free to skip first sections and jump directly to Integrating BaseServlet. For this example we will use NetBeans IDE 8.0 with Glassfish Server and Java EE Version 7.

Sections on this page:

  • Setting Up New Project: explains how to set up a new web project using NetBeans IDE.
  • Adding Servlet: explains how to add a servlet to your Java web project.
  • Adding Content: in this section some content is added to the website for future demonstration of mobile detection.
  • Integrating BaseServlet: this section describes changes that have to be made to an existing servlet in order to integrate 51Degrees device detection by extending BaseServlet instead of HttpServlet.
  • Results: shows how the same content looks when accessed from mobile and desktop browser after device detection has been integrated in to the servlet.

Setting Up New Project

  1. Create new project in NetBeans by clicking File -> New Project. In Categories select Java Web and in Projects select Web Application. Click Next.

    NetBeans window displaying new project options

  2. Set Project Name to MyApp. We do not alter Project Location or Project Folder for this example. Click Next.

    NetBeans window displaying Name and Location options

  3. Choose Server, Java EE Version and Context Path. In this example we use GlassFish Server, Java EE 7 and default context path: /MyApp. Click Next.

    NetBeans window displaying Server and Settings options

  4. Do not include any Frameworks, unless you know you need them for your project. For the purpose of this example we do not need any frameworks. Click Finish.

    NetBeans window displaying Framework options

Adding Servlet

Now, that the project is ready it's time to add a Java Servlet and create a Desktop version of the example website.

  1. (Step 1 and 2 are optional) First, rename the package to my.app.com. To do so: expand the Source Packages folder, right-click on the "default package" and select New -> Java Package.

    NetBeans window displaying new project options

  2. In the window that opens set Package Name to my.app.com. Do not alter Project, Location or Created Folder.

    NetBeans window displaying new project options

  3. Now, right click on my.app.com package and select New -> Servlet.

    NetBeans window displaying new project options

  4. In the new Servlet window set Class Name to MyServlet. Class Name can be different, it is the name of the Java class that will implement the servlet and does not affect the URL servlet is accessed at. For the purpose of this application we do not change Project, Location, Package or Created File options. Click Next.

    NetBeans window displaying new project options

  5. Next window gives you the options that influence how Servlet is accessed. Make sure you tick the "Add information to deployment descriptor (web.xml)" box. Set URL Pattern field to /My or any other value you want. the URL Pattern(s) field influences the URL at which your servlet can be accessed. Click Finish.

    NetBeans window displaying new project options

The Servlet is now ready for deployment by clicking Run Project (Large green 'play' button). If you have been following this tutorial, then your Servlet will be accessible via the following URL: http://localhost:8080/MyApp/My as shown below:

Java servlet deployment example

At the moment it does not do much apart from displaying Servlet name. In the next section directly below we will add a CSS file and some lorem ipsum content.

Tip: while working on your servlet you do not need to stop and re-start your server. Any changes will be deployed to the running server once you save the changes.

Adding Content

Now it is time to add some content to the website and a Cascading Style Sheet (CSS) file to tell browser how we want to display the content.

  1. Create a new folder for our CSS files by right-clicking the Web Pages folder and selecting New -> Folder.

    NetBeans print screen showing new folder created

  2. In the dialog window set Folder Name to 'css'. Click Finish.

    Important Note: You can choose a different location for your CSS file and directory, but keep in mind that folders and files inside WEB-INF directory are not publicly accessible.

    NetBeans new css folder settings

  3. Now add a new CSS file to the folder you have just created by right-clicking the 'css' folder and selecting New -> Cascading Style Sheet. Set file name to 'desktop'. Click Finish.

    NetBeans adding css file to folder

  4. Place the following code in to the desktop.css file:

    body {
        width: 100%;
        margin: 0;
        text-align: center;
    }
    
    .article {
        width: 49%;
        float: left;
    }
    

  5. Now that the CSS file is set up, let's modify MyServlet.java file we created earlier.
    For the purpose of this example we will create two String variables: article_1 and article_2 that contain an h3 tag and some lorem ipsum text (line 17 to 31). In a real project these variables could be some dynamic content loaded from the database. Then we add two div elements to the default servlet output and print the content from article_1 and article_2 in between the corresponding div tags (line 54 to 59). Finally we need to link the CSS file to our servlet response through the tag (line 50). MyServlet.java file should look something like this:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    package my.app.com;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     *
     * @author nerru
     */
    public class MyServlet extends HttpServlet {
    
        /* Site Content */
        String article_1 = "<h3>Article 1</h3><p>This is article one. It contains "
            + "some important info. Lorem ipsum dolor sit amet, consectetur "
            + "adipisicing elit, sed do eiusmod tempor incididunt ut labore "
            + "et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud "
            + "exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. "
            + "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum "
            + "dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non "
            + "proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>";
        String article_2 = "<h3>Article 2</h3><p>This is article two. It contains some more "
            + "important info. Lorem ipsum dolor sit amet, consectetur adipisicing elit, "
            + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad "
            + "minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea "
            + "commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit "
            + "esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
            + "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>";
        
        /**
         * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
         * methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            try (PrintWriter out = response.getWriter()) {
                out.println("<!DOCTYPE html>");
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet MyServlet</title>");    
                out.println("<link rel='stylesheet' type='text/css' href='css/desktop.css'>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet MyServlet at " + request.getContextPath() + "</h1>");
                out.println("<div class='article'>");
                out.println(article_1);
                out.println("</div>");
                out.println("<div class='article'>");
                out.println(article_2);
                out.println("</div>");
                out.println("</body>");
                out.println("</html>");
            }
        }
    /* Http Servlet Methods. Not including here to save space. */
    }
    

Integrating BaseServlet

This section explains how to use 51Degrees device detection solution by extending BaseServlet from 51Degrees Java distribution. BaseServlet itself extends HttpServlet therefore you get the functionality of HttpServlet with added functionality of 51Degrees device detection.

  1. Download 51Degrees device detector from sourceforge if you have not done so already. Extract files from the archive. Add 51Degrees JAR files to your project by right clicking on Libraries -> Add JAR/Folder. Add all files from the 'dist' folder and all files from the 'lib/webapp' folder.

    NetBeans adding JAR fles to project

  2. Add the following line to your list of imports:

    import fiftyone.mobile.detection.webapp.BaseServlet;
    

  3. Change the following line:

    public class MyServlet extends HttpServlet {
    

    to:

    public class MyServlet extends BaseServlet {
    

  4. You can gain access to the properties via getProperty() method as follows:

    getProperty(request,"PropertyName");
    

    Where 'request' is the object representing current request and 'PropertyName' is the name of the property to be retrieved. Full list of supported properties can be found in our PropertyDictionary.

    Important Note: All properties are returned as Strings by default. You can convert them to other types when needed. For example to use the IsMobile property as a boolean:

    boolean isMobile = Boolean.parseBoolean(getProperty(request,"IsMobile"));
    

    If you remember from the previous sections we have a two column website layout which is not practical for small screens of mobile devices. We can now use device detector that we have just integrated in order to supply the same content but link a different CSS file to alter the way content is displayed. Or if you did not follow the tutorial but simply want to integrate device detection in to your servlet the following code snippets should provide adequate example to achieve this.

  5. Create a new Cascading Style Sheet file in the css directory we created earlier and call it 'mobile'. The content of this CSS file should look something like this:

    body {
        width: 100%;
        margin: 0;
        text-align: center;
    }
    
    .article {
        width: 100%;
    }
    

    The difference here is that articles now take 100% of page's width, essentially transforming website in to single-column layout.

  6. Final step is to introduce some server side logic based on detected device. We will need to introduce a new string variable called css_file with default value set to "desktop" and an if statement that will change css_file value to mobile if requesting device was identified as mobile:

            /* Various variables. */
            String css_file = "desktop";
            
            /* 51Degrees properties and logic. */
            boolean isMobile = Boolean.parseBoolean(getProperty(request,"IsMobile"));
            if (isMobile)
                css_file = "mobile";
    

    Now we need to substitute the correct css_file string in the link tag as follows:

    out.println("<link rel='stylesheet' type='text/css' href='css/"+css_file+".css'>");
    

    What happens in the above snippets is: a device is detected as either mobile or non-mobile. If the device is mobile then css_file variable is set to "mobile" otherwise it keeps the value "desktop". In the link tag the value held in css_file variable is substituted and either mobile.css or desktop.css file is supplied to the client.

The final version of our servlet looks something like this:

package my.app.com;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fiftyone.mobile.detection.webapp.BaseServlet;

/**
 *
 * @author nerru
 */
public class MyServlet extends BaseServlet {

    /* Site Content */
    String article_1 = "<h3>Article 1</h3><p>This is article one. It contains "
        + "some important info. Lorem ipsum dolor sit amet, consectetur "
        + "adipisicing elit, sed do eiusmod tempor incididunt ut labore "
        + "et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud "
        + "exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. "
        + "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum "
        + "dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non "
        + "proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>";
    String article_2 = "<h3>Article 2</h3><p>This is article two. It contains some more "
        + "important info. Lorem ipsum dolor sit amet, consectetur adipisicing elit, "
        + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad "
        + "minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea "
        + "commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit "
        + "esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
        + "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>";
    
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        /* Various variables. */
        String css_file = "desktop";
        
        /* 51Degrees properties and logic. */
        boolean isMobile = Boolean.parseBoolean(getProperty(request,"IsMobile"));
        if (isMobile)
            css_file = "mobile";
        
        response.setContentType("text/html;charset=UTF-8");
        
        try (PrintWriter out = response.getWriter()) {
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MyServlet</title>");    
            out.println("<link rel='stylesheet' type='text/css' href='css/"+css_file+".css'>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet MyServlet at " + request.getContextPath() + "</h1>");
            out.println("<div class='article'>");
            out.println(article_1);
            out.println("</div>");
            out.println("<div class='article'>");
            out.println(article_2);
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
        }
    }

Results

The above example allowed us to detect mobile devices and supply them with a different CSS file in order to change the way information is presented. Below are the print screens of resulting pages for desktop and mobile browsers.

Desktop browser:


Servlet view on desktop browser

Mobile browser:


Servlet view on mobile browser

Need Help?