码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-12-16 15:40:49      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:

 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可以进行头部处理,把两者结合起来

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

标签:

原文地址:http://www.cnblogs.com/wangorg/p/5051107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!