Skip to content

Instantly share code, notes, and snippets.

@Elyorbe
Created October 26, 2022 09:13
Show Gist options
  • Save Elyorbe/6684c976ee6a1d8d891314aeaccb2df5 to your computer and use it in GitHub Desktop.
Save Elyorbe/6684c976ee6a1d8d891314aeaccb2df5 to your computer and use it in GitHub Desktop.
Useful for adding query params
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* Provides a way to add query parameters to a request
* */
public class ModifiableHttpServletRequestWrapper extends HttpServletRequestWrapper {
private Map<String, String[]> params;
public ModifiableHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
this.params = new HashMap<>(request.getParameterMap());
}
@Override
public String getParameter(String name) {
String returnValue = null;
String[] paramArray = getParameterValues(name);
if (paramArray != null && paramArray.length > 0) {
returnValue = paramArray[0];
}
return returnValue;
}
@Override
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(params);
}
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(params.keySet());
}
@Override
public String[] getParameterValues(String name) {
String[] result = null;
String[] temp = params.get(name);
if (temp != null) {
result = new String[temp.length];
System.arraycopy(temp, 0, result, 0, temp.length);
}
return result;
}
public void addParameter(String name, String value) {
String[] oneParam = { value };
addParameter(name, oneParam);
}
public void addParameter(String name, String[] value) {
params.put(name, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment