問題:在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前面即可