将值从javascript传递给Servlet

时间:2014-06-21 06:34:07

标签: java jquery servlets

我是新的蜜蜂正致力于将数据从jquery传递到Servlet。以下是我的文件

的javascript:

<script type="text/javascript"> 
function getData(tableName) 
{
    var tableId =tableName+"Table";
    jsonObj = [];
    $(\'#' + tableId + '\').find(\'tbody>tr\').each(function (i) { 
        var $tds = $(this).find('td'), setvilId = $tds.eq(1).text(),setvilNotes = $tds.eq(8).text(); 
        item = {};
        item["id"] = setvilId;
        item["notes"] = setvilNotes;
        jsonObj.push(item); 
    });
    console.log(jsonObj);
    var jsonString =JSON.stringify(jsonObj);
    request(jsonString);
};
</script>

<script type=\"text/javascript\">
function updateNotes () { 
    var editable = true; 
    var editables = $('td[id*=notestd], td[id*=eta]');
    editables.attr('contentEditable', editable);
} 
function request(jsonString) {
    $.ajax({ 
        url: "/updatesetvil", 
        type: "POST",
        data: jsonString, 
        dataType: "text", 
        success: function(){ 
            alert(\"success\");
        }, 
        error:function(){ 
            alert(\"failure\"); 
        } 
    });
};
</script>


Servlet:

public class UpdateSetvil extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

     List<SetvilJsonAttributes> setvilAttrs = new LinkedList<SetvilJsonAttributes>();
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("Inside servlet");

        // 1. get received JSON data from request
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String json = "";
        if(br != null){
            json = br.readLine();
        }
        System.out.println(json.toString()); // [{"id":"","notes":""},{"id":"18001","notes":"fdafd"},{"id":"8350","notes":"daggda"},{"id":"8056","notes":"gfdagdfa"}]
        // 2. initiate jackson mapper
         ObjectMapper mapper = new ObjectMapper();

         // 3. Convert received JSON to Class
        SetvilJsonAttributes setvilatt = mapper.readValue(json, SetvilJsonAttributes.class);

        // 4. Set response type to JSON
        response.setContentType("application/json");

        setvilAttrs.add(setvilatt);

        for (int i=0;i< setvilatt.size(); i++) {
            System.out.println(setvilatt.get(i).getId());
        }
    }
    private class SetvilJsonAttributes {
        Integer id;
        String notes;
        String eta;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getNotes() {
            return notes;
        }

        public void setNotes(String notes) {
            this.notes = notes;
        }

        public String getEta() {
            return eta;
        }

        public void setEta(String eta) {
            this.eta = eta;
        }

    }
}

错误:java.io.IOException:解析JSON请求字符串时出错

我请求任何人帮我解决这个问题。我被困住了,无法继续前进。

4 个答案:

答案 0 :(得分:0)

试试这个,

$.ajax({ 
    url: "/updatesetvil", 
    type: "POST",
    // The key needs to match your method's input parameter (case-sensitive).
    data: { jsonString: jsonString},
    contentType: "application/json; charset=utf-8"      
    dataType: "text", 
    success: function(data){ 
        alert(\"success\"+data);
    }, 
    error:function(){ 
        alert(\"failure\"+data); 
    } 
});

答案 1 :(得分:0)

建议

如果在解析JSON字符串时遇到问题,那么我可以帮助您使用GSON library将JSON字符串解析为Java对象,如下面的示例代码所示。

请注意id应为String,否则会导致NumberFormatException空ID值。

示例代码:

class SetvilJsonAttributes {
    private String id;
    private String notes;
    // getter & setter
}

String jsonString="[{\"id\":\"\",\"notes\":\"\"},{\"id\":\"18001\",\"notes\":\"fdafd\"},{\"id\":\"8350\",\"notes\":\"daggda\"},{\"id\":\"8056\",\"notes\":\"gfdagdfa\"}]";

Type type = new TypeToken<ArrayList<SetvilJsonAttributes>>() {}.getType();
ArrayList<SetvilJsonAttributes> data = new Gson().fromJson(jsonString,type);

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

输出:

[
  {
    "id": "",
    "notes": ""
  },
  {
    "id": "18001",
    "notes": "fdafd"
  },
  {
    "id": "8350",
    "notes": "daggda"
  },
  {
    "id": "8056",
    "notes": "gfdagdfa"
  }
]

如果您不想更改id字段的类型,则可以尝试使用JsonDeserializer根据需要对其进行反序列化。

请查看JsonDeserializer的其他帖子herehere

答案 2 :(得分:0)

见这三行:

    System.out.println(json.toString()); // [{"id":"","notes":""},{"id":"18001","notes":"fdafd"},{"id":"8350","notes":"daggda"},{"id":"8056","notes":"gfdagdfa"}]
    ObjectMapper mapper = new ObjectMapper();
    SetvilJsonAttributes setvilatt = mapper.readValue(json, SetvilJsonAttributes.class);

json的值是JSON数组。但是,然后将其映射到SetvilJsonAttributes,它不支持JSON数组。您可以使用以下代码将json转换为List SetvilJsonAttributes

    ObjectMapper mapper = new ObjectMapper();
    ArrayList<SetvilJsonAttributes> setvilatt = mapper.readValue(json, new TypeReference<ArrayList<SetvilJsonAttributes>>(){});

答案 3 :(得分:0)

我已经使用了JSONArray并且它已经解决了

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("Inside servlet");
        Connection connector = MysqlConnector.getDBCon();
        StringBuffer sb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            json = sb.toString();
        } catch (Exception e) {
            System.out.println("Exception while reading JSON String");
            e.printStackTrace();
        }
        System.out.println("String is " + json);
        try {
            JSONArray inputArray = new JSONArray(json);
            for (int i=0; i < inputArray.length(); i++) {
                JSONObject c = inputArray.getJSONObject(i);
                String id = c.getString("id");
                String notes = c.getString("notes");
                System.out.println(id + "--> " + notes);
        } catch (JSONException e) {
            // crash and burn
            System.out.println("Parse exeception for array");
            e.printStackTrace();
        }
}