2015-01-08 4 views
0

웹 페이지에서 JQuery를 사용하여 Ajax 호출을 내 서블릿에 보냅니다.Servlet request.getParameter return null

protected void doPost(HttpServletRequest request, 
     HttpServletResponse response) throws ServletException, IOException { 
    // TODO Auto-generated method stub 
    String name = request.getParameter("name"); 
    if (name == null) 
     System.out.println("null"); 

    /* 
    response.setContentType("application/json"); 
    response.setCharacterEncoding("UTF-8"); 
    response.getWriter().write(new Integer(1).toString()); 
    response.getWriter().close(); 
    */ 

} 

내가 매개 변수가 성공적으로 "널 (null)"인쇄 콘솔로 서블릿에서 전송 및 수신 볼 수있는 다음 AddOrUpdateServlet의의 doPost에서

function sendAjax() { 
      $.ajax({ 
       url: "/AddOrUpdateServlet", 
       type: 'POST', 
       dataType: 'json', 
       data: {"name": "hello world"}, 
       contentType: 'application/json', 
       mimeType: 'application/json', 

       success: function (data) { 

       }, 
       error:function(data,status,er) { 
        alert("error: "+data+" status: "+status+" er:"+er); 
       } 
      });   
     } 

, 나는 다음과 같은 코드가 있습니다. 하지만 서블릿이 왜 "이름"매개 변수를 얻을 수 없었습니까?

+0

가 왜'MIME 타입 설정하는? – epascarello

답변

0

"name" 매개 변수를 request body of POST에 전달 했으므로 그 이상은 JSON 유형입니다.

그냥 그것을 GET 요청을하고 다음 줄을 제거

`contentType: 'application/json',mimeType: 'application/json', 

편집 : - 서블릿 코드의 라인 아래 쓰기, 당신의 데이터를 구문 분석, JSON 라이브러리를 사용해야 할 것이다 서블릿 (GSON or Jackson) 참조 : - :, '응용 프로그램/JSON을`Stack overflow answer

StringBuffer jb = new StringBuffer(); 
    String line = null; 
    try { 
    BufferedReader reader = request.getReader(); 
    while ((line = reader.readLine()) != null) 
     jb.append(line); 
    } catch (Exception e) { /*report an error*/ } 

    try { 
    JSONObject jsonObject = JSONObject.fromObject(jb.toString()); 
    } catch (ParseException e) { 
    // crash and burn 
    throw new IOException("Error parsing JSON request string"); 
    } 
+0

하지만 GET 대신 POST를 사용하고 싶습니다. 방법? – alextc

+0

이 http://stackoverflow.com/questions/3831680/httpservletrequest-get-post-data를 참조하여 내 대답을 업데이트 했으므로이 경우에는 메서드를 변경할 필요가 없습니다. – RE350

+0

감사합니다. RE350. 나는 거의 거기에 있다고 생각한다. 하지만 문제는 JQuery가 원래 JSON 데이터 { "name": "hello world"} 대신 "name = hello + world"를 전송한다는 것입니다. 자동으로 변환 된 것 같습니다. – alextc