Java – Detecting Firefox Browser

The post shows you the way how to detect if a browser is Firefox or not using Java.

 

1. Implementation

The code looks simple as this.

Browser.java
package com.bytenota;

import javax.servlet.http.HttpServletRequest;

public class Browser {
    
    public static boolean detectFirefox(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent").toLowerCase();
        return userAgent.contains("firefox");
    } 
}

In the above code, we simply look at User-Agent data (request.getHeader("User-Agent")). if it contains firefox string, the browser is Firefox. Otherwise, the browser is something else, it can be Chrome, Edge, IE, Safari, or whatever.


 

2. Usage and Example

Let’s create a jsp file in your web application with the following content.

index.jsp
<%@page import="com.bytenota.Browser"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Java - Detecting Firefox Browser</title>
    </head>
    <body>
        <%
            if (Browser.detectFirefox(request)) {
                out.write("The browser is Firefox");
            } else {
                out.write("The browser is not Firefox");
            }
        %>
    </body>
</html>

Assuming that you have opened this jsp webpage in the Firefox browser. And the output you will get is:

The browser is Firefox

0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x