将值从javascript传递到Servlet

将值从javascript传递到Servlet,java,jquery,servlets,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) {

我是一个新手,正在将以下数据从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请求字符串时出错

我恳请任何人在这方面帮助我。我被卡住了,无法继续

试试这个

$.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); 
    } 
});
建议 如果您在解析JSON字符串时遇到问题,那么我可以帮助您使用下面的示例代码将JSON字符串解析为Java对象

请注意,id应为字符串,否则将导致空id值的NumberFormatException

示例代码:

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字段的类型,则可以尝试根据需要对其进行反序列化

请看一下我的另一篇文章和JsonDeserializer。

请看以下三行:

    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数组。但是,然后将其映射到不支持JSON数组的SetvilJsonAttributes。您可以使用以下方法将此json转换为SetvilJsonAttributes列表:


我用过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();
        }
}
    ObjectMapper mapper = new ObjectMapper();
    ArrayList<SetvilJsonAttributes> setvilatt = mapper.readValue(json, new TypeReference<ArrayList<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");
        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();
        }
}