在 Java Servlet 中获取通过 jquery ajax 发送的参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19374345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get parameter sent via jquery ajax in Java Servlet
提问by gae
I search this topic on web but I can't get a example that worked. I will be gladed with someone could give me a help.
我在网上搜索了这个主题,但我找不到一个有效的例子。我会很高兴有人能给我帮助。
this is what I testing.
这是我测试的。
$.ajax({
url: 'GetJson',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: {id: 'idTest'},
success: function(data) {
console.log(data);
}
});
in Sevlet
在塞夫莱特
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String id2[] = request.getParameterValues("id");
String id3 = request.getHeader("id");
}
I'm getting null in everything.
我的一切都变得空洞了。
采纳答案by Nikos Paraskevopoulos
The sort answer is that this data is hidden in the request InputStream
.
排序答案是该数据隐藏在请求中InputStream
。
The following servlet is a demo of how you can use this (I am running it on a JBoss 7.1.1):
以下 servlet 是如何使用它的演示(我在 JBoss 7.1.1 上运行它):
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="fooServlet", urlPatterns="/foo")
public class FooServlet extends HttpServlet
{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = req.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buf = new byte[32];
int r=0;
while( r >= 0 ) {
r = is.read(buf);
if( r >= 0 ) os.write(buf, 0, r);
}
String s = new String(os.toByteArray(), "UTF-8");
String decoded = URLDecoder.decode(s, "UTF-8");
System.err.println(">>>>>>>>>>>>> DECODED: " + decoded);
System.err.println("================================");
Enumeration<String> e = req.getParameterNames();
while( e.hasMoreElements() ) {
String ss = (String) e.nextElement();
System.err.println(" >>>>>>>>> " + ss);
}
System.err.println("================================");
Map<String,String> map = makeQueryMap(s);
System.err.println(map);
//////////////////////////////////////////////////////////////////
//// HERE YOU CAN DO map.get("id") AND THE SENT VALUE WILL BE ////
//// RETURNED AS EXPECTED WITH request.getParameter("id") ////
//////////////////////////////////////////////////////////////////
System.err.println("================================");
resp.setContentType("application/json; charset=UTF-8");
resp.getWriter().println("{'result':true}");
}
// Based on code from: http://www.coderanch.com/t/383310/java/java/parse-url-query-string-parameter
private static Map<String, String> makeQueryMap(String query) throws UnsupportedEncodingException {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for( String param : params ) {
String[] split = param.split("=");
map.put(URLDecoder.decode(split[0], "UTF-8"), URLDecoder.decode(split[1], "UTF-8"));
}
return map;
}
}
With the request:
随着请求:
$.post("foo",{id:5,name:"Nikos",address:{city:"Athens"}})
The output is:
输出是:
>>>>>>>>>>>>> DECODED: id=5&name=Nikos&address[city]=Athens
================================
================================
{address[city]=Athens, id=5, name=Nikos}
================================
(NOTE: req.getParameterNames()
does not work. The map printed in the 4th line contains all the data normally accessible using request.getParameter()
. Note also the nested object notation, {address:{city:"Athens"}}
→ address[city]=Athens
)
(注意:req.getParameterNames()
不起作用。第 4 行打印的地图包含通常使用 访问的所有数据request.getParameter()
。还要注意嵌套的对象符号,{address:{city:"Athens"}}
→ address[city]=Athens
)
Slightly unrelated to your question, but for the sake of completeness:
与您的问题略有关系,但为了完整起见:
If you want to use a server-side JSON parser, you should use JSON.stringify
for the data:
如果您想使用服务器端 JSON 解析器,您应该JSON.stringify
对数据使用:
$.post("foo",JSON.stringify({id:5,name:"Nikos",address:{city:"Athens"}}))
In my opinion the best way to communicate JSON with the server is using JAX-RS (or the Spring equivalent). It is dead simple on modern servers and solves these problems.
在我看来,与服务器通信 JSON 的最佳方式是使用 JAX-RS(或 Spring 等价物)。它在现代服务器上非常简单并解决了这些问题。
回答by Aviral
I had the same issue with getParameter("foo") returning null in the servlet. Found a simple solution which might be useful to people here. Use the default value
我在 getParameter("foo") 在 servlet 中返回 null 时遇到了同样的问题。找到了一个简单的解决方案,可能对这里的人有用。使用默认值
contentType='application/x-www-form-urlencoded; charset=UTF-8'
or leave it out. This will automatically encode the request with the data in parameters.
或将其排除在外。这将使用参数中的数据自动对请求进行编码。
Hope this helps...
希望这可以帮助...