0

I am sending json data:

{
    "username":"abc@gmail.com",
    "password":"abc"
}

And in my custom filter i want to access username and password

My filter is :

@Override
public void doFilter(ServletRequest request, ServletResponse response, 
        FilterChain chain) throws IOException, ServletException {
    //code to get parameters from json
}
Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
Qasim
  • 9,058
  • 8
  • 36
  • 50

2 Answers2

0

Using apache IO utils, get JSON string from input stream and convert JSON string to map:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>${commons-io.version}</version>
</dependency>

@Override

public void doFilter(ServletRequest request, ServletResponse
 response, FilterChain chain) throws IOException, ServletException {
        try {
            String jsonBody = IOUtils.toString(request.getInputStream());
            //convert json string to HashMap
            //using http://stackoverflow.com/a/22011887/1358551
        } catch (Exception e) {
            logger.warn("", e);
            return new ResponseEntity<String>(e.getMessage(),
                    HttpStatus.BAD_REQUEST);
        }
    }
charybr
  • 1,888
  • 24
  • 29
0

I'd suggest using the google Gson parser

Map<String, String> extractLoginRequest(final ServletRequest request) throws IOException {
    final StringBuffer sb = new StringBuffer();
    String line = null;
    final BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    // as far as I know, gson might not be 100% threadsave
    return new Gson().fromJson(sb.toString(), HashMap.class);
}

now you can access your parameter with

Map<String, String> loginRequest = extractLoginRequest(request);
loginRequest.get("username") 

In case you are using Maven, this is the dependency you might use:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.3.1</version>
</dependency>
jaecktec
  • 440
  • 4
  • 15