2

Using Spring, I want to know in my @Controller whether the request comes from the browser or not. If so, then put a particular treatment. I thought of using @RequestHeader (value = "User-Agent") like this:

    @RequestMapping(value = "/user-agent-test")
        public String hello(@RequestHeader(value="User-Agent") String userAgent)
             //toDo                  
             if(browser){
               //Make something 
             }else{
               // Make something else
             }
          return "home";
        }

But I do not know what condition I have to put. thank you in advance.

  • You may find this link informative https://stackoverflow.com/questions/28323058/how-to-get-the-exact-client-browser-name-and-version-in-spring-mvc – Perry Aug 03 '17 at 23:36

1 Answers1

3

You actually can not guarantee that the presence of the http-header "User-Agent" assures this is coming from a browser. This could also be any other script/library/program setting it. On the opposite, a missing header is not a sign that it is not a browser. You will be just doing an "educated guess".

Anyways, if you still want to follow your approach, you should use also "required=false" on the RequestHeader annotation, so the parameter is null when the header is not set instead of failing altogether. Then you just check if your parameter is null or not.

Like this:

@RequestMapping(value = "/user-agent-test")
public String hello(@RequestHeader(value="User-Agent", required=false) String userAgent)
   if (null != userAgent) {
      // could be a browser
   } else {
      // could be something else
   }
   return "home";

}

See springs javadoc on the annotation. Also see this answer on the presence of the "User-Agent" header

  • By reading this article: https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent , it says that most browsers use user-agent – TOUZENE Mohamed Wassim Aug 03 '17 at 23:58