问题:在serverfilter request获取不到post提交的参数,而get请求可以
@Provider public class ReqFilter implements ContainerRequestFilter {
@Context HttpServletRequest request;
@Context private HttpServletResponse response;
@Override public void filter(ContainerRequestContext crc) throws IOException {
问题:在serverfilter request获取不到post提交的参数,而get请求可以
@Provider public class ReqFilter implements ContainerRequestFilter {
@Context HttpServletRequest request;
@Context private HttpServletResponse response;
@Override public void filter(ContainerRequestContext crc) throws IOException {
request.getParameter("name"); // 前端如果通过get提交可以获取,而通过post提交永远获取不到name
}
}
答案一:通过请求流,获取请求参数
@Override
public void filter(ContainerRequestContext crc) throws IOException {
String requestStr = this.inputStreamToString(crc.getEntityStream());
String[] arrs = requestStr.split("&");
for (String strs : arrs) {
String[] strs2 = strs.split("=");
for (int i = 0; i < strs2.length; i++) {
if (strs2[0].equals("name")) {
if (strs2[1] != null &&!strs2[1].equals("")) {
System.out.println("test=" + strs2[1]);
}
}
}
}
}
public String inputStreamToString(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
以上方案简介获取到name这个请求参数的值
public class MyFilter implements Filter{
@Override public void init(FilterConfig fc) throws ServletException { }
@Override public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException { System.out.println("test=" + sr.getParameter("agentId")); fc.doFilter(sr, sr1); }
@Override public void destroy() { } }
该适配器一定要配置在org.glassfish.jersey.servlet.ServletContainer前面即可