jersey post提交到 ContainerRequestFilter 而HttpServletRequest获取不到数据(转)

 jersey post提交到 ContainerRequestFilter 而HttpServletRequest获取不到数据

问题:在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前面即可

总结:jersey和servlet 中request各自封装不一样,建议servlet request进行参数的处理,而jersey request可以进行头部处理,把两者结合起来
上一篇:web socket RFC6455 frame 打包、解包


下一篇:操作native window的QxtWindowSystem (好像是一个IM的一部分)