Skip to content

Instantly share code, notes, and snippets.

@jayeshcp
Created June 3, 2019 12:25
Show Gist options
  • Save jayeshcp/cd84e071bf193e3a8db9730251392444 to your computer and use it in GitHub Desktop.
Save jayeshcp/cd84e071bf193e3a8db9730251392444 to your computer and use it in GitHub Desktop.
Spring Custom Annotation to process request body
package hello;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@UpperCase(value="name") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
@PostMapping("/save")
@ResponseBody
public Object save(@UpperCase("req") Object req) {
return ((Map<String, String>) req).get("decoded");
}
}
package hello;
import java.lang.annotation.*;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UpperCase {
String value();
}
package hello;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public final class UpperCaseResolver implements HandlerMethodArgumentResolver {
private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(UpperCase.class) != null;
}
@Override
public Object resolveArgument(
MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory
) {
String body = getRequestBody(webRequest);
Map<String, String> resultMap = new HashMap<>();
StringBuilder sb = new StringBuilder();
sb.append("decoded: ");
sb.append(body);
resultMap.put("decoded", sb.toString());
resultMap.put("someotherfield", "yes");
return resultMap;
}
private String getRequestBody(NativeWebRequest webRequest){
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
String jsonBody = (String) servletRequest.getAttribute(JSONBODYATTRIBUTE);
if (jsonBody==null){
try {
String body = IOUtils.toString(servletRequest.getInputStream());
servletRequest.setAttribute(JSONBODYATTRIBUTE, body);
return body;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment