Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether HttpServletRequest contains the key in Java (Using spring boot)

HttpServletRequest httpReq = (HttpServletRequest) request;

if (httpReq.getHeader("device").equals("web1")) {
    chain.doFilter(request, response);
}

I want to know how can I check whether the key "device" exists in the request header?

Note : Don't want to use getHeaderName which returns an enumeration of all the header names this request contains and iterate through it.

getParameterMap().containsKey("device") is not working here.

like image 350
Fida Avatar asked Jan 29 '23 23:01

Fida


2 Answers

From the JavaDoc for HttpServletRequest.getHeader(String name):

If the request did not include a header of the specified name, this method returns null.

So a basic null check is sufficient:

boolean deviceHeaderExists = httpReq.getHeader("device") != null;
like image 117
Robby Cornelissen Avatar answered Feb 07 '23 17:02

Robby Cornelissen


Reading between the lines a little, if you're looking to accept a mandatory device header then you can code that up with annotations in your REST call. Example:

@GetMapping("/something")
public void doSomething(@RequestHeader("device") @NotNull String deviceName) {
  // your logic here
}
like image 43
Andy Brown Avatar answered Feb 07 '23 19:02

Andy Brown