1
我對我在代碼中面臨的這個奇怪的錯誤感到十分困惑。所以,我試圖將數據從我的jQuery腳本發送到帶有AJAX的servlet。現在,我注意到了一些奇怪的部分,當我將contentType設置爲application/json
時,我注意到服務器端的所有值都是null,但是當我將它刪除時,我在servlet中獲得了正確的數據。現在,我想知道爲什麼我面臨這樣的錯誤?在Java中發送JSON數據從Ajax到Servlet?
這裏是我的jsp -
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var apiname=$("#apiname").val();
var apiendpoint=$("#apiendpoint").val();
var apiversion=$("#apiversion").val();
var source=$("#source").val();
$.ajax({
type: "POST",
url: "HomeServlet",
contentType: "application/json",
dataType:'json',
data:{"apiname":apiname,"apiendpoint":apiendpoint,"apiversion":apiversion,"source":source},
success: function(status){
console.log("Entered",status);
},
error:function(error){
console.log("error",error);
},
});
});
</script>
servlet代碼 -
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<String, String> job = new LinkedHashMap<>();
//doGet(request, response);
JSONArray jArray = new JSONArray();
// response.setContentType("text/html");
PrintWriter out= response.getWriter();
String n = request.getParameter("apiname");
String p = request.getParameter("apiendpoint");
String e = request.getParameter("apiversion");
String c = request.getParameter("source");
String status ="091";
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
System.out.println("Connection created");
PreparedStatement ps= ((java.sql.Connection) con).prepareStatement("insert into apiinfo(apiname,apiendpoint,apiversion,accessibility) values (?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3, e);
ps.setString(4,c);
ps.execute();
out.close();
status ="000";
con.close();
System.out.println("Inserted");
}
catch(Exception e1)
{
System.out.println(e1);
}
job.put("status",status);
jArray.put(job);
System.out.println(jArray.toString());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jArray.toString());
}
您可以看看[從HttpServletRequest中檢索JSON對象文字](https://stackoverflow.com/questions/1548782/retrieving-json-object-literal-from-httpservletrequest) – gaetanoM
您可以打開瀏覽器,按F12 ,運行這兩個版本並檢查與content-type:'application/json'和'application/x-www-form-urlencoded'的區別。另外,請閱讀http://docs.oracle.com/javaee/6/api/javax /servlet/ServletRequest.html#getParameter(java.lang.String)特別是對於HTTP Servlet,參數包含在查詢字符串或發佈的表單數據中 – user1516873