阅读JSON值的servlet [英] Reading JSON values in servlet

查看:157
本文介绍了阅读JSON值的servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我张贴一个jQuery AJAX POST到一个servlet,数据是JSON字符串的形式。 我不知道数据是否被越来越帐。另外,我想从JSON对象获取它来验证用户名和密码。

继承人的code片断:

 <脚本SRC =HTTP://$c$c.jquery.com/jquery-latest.min.js>< / SCRIPT>
    <脚本类型=文/ JavaScript的SRC =htt​​p://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js>< / SCRIPT>

    <脚本类型=文/ JavaScript的>
    功能doajax(){

    VAR全称= $(#全称)VAL。
    VAR mobileno = $(#mobileno)VAL。


      $阿贾克斯({
         网址:dvsds,
         键入:POST,
         数据类型:JSON,
         数据:{mobileno:mobileno,全称:全名},
          错误:函数(){
              警报(发生错误!);
          },
          成功:功能(数据){
               警报(data.message);
         }
       });
      }
< / SCRIPT>
 

我的servlet侧code:

 公共无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{

    response.setContentType(应用/ JSON);
    PrintWriter的输出= response.getWriter();
    尝试 {
        字符串消息= NULL;

        JSONObject的jObj =新的JSONObject(的request.getParameter(jsondata));
        迭代器<字符串>它= jObj.keys(); //得到所有的钥匙

        字符串名称= NULL;
        字符串mobileno = NULL;

        而(it.hasNext())
        {
            字符串键=(字符串)it.next(); //获取密钥

            如果(key.equals(全名))
                 NAME =(字符串)jObj.get(密钥);
            否则如果(key.equals(mobileno))
                mobileno =(字符串)jObj.get(密钥);
        }


        如果(名称==ABC和安培;&安培; mobileno ==123)
            消息=成功;
        其他
            消息=不及格;

        的JSONObject的JSONObject =新的JSONObject();
        jsonObject.put(消息,消息);
        通过out.println(的JSONObject);
 

解决方案

您不必字符串化的数据...只是把它作为一个普通的旧JavaScript对象......通过指定的数据类型为JSON ... jQuery将弄清楚如何打包数据请求

没有必要在服务器端进行任何更改

所以,如果您的AJAX调用就变成了:

  $。阿贾克斯({
     网址:dvsds,
     键入:POST,
     数据类型:JSON,
     数据:jsondata,
      错误:函数(){
          警报(发生错误!);
      },
      成功:功能(数据){
           警报(data.message);
     }
   });
 

在servlet检索它们作为

 字符串FNAME =的request.getParameter(全名);
串mobileno =的request.getParameter(mobileno);
 

我想你需要小心区分大小写

EDITED

我看到你,你可以改变你的脚本如下。

 <脚本类型=文/ JavaScript的>
功能doajax(){

VAR全称= $(#全称)VAL。
VAR mobileno = $(#mobileno)VAL。

变种postReqData = {}; //创建一个空的对象
postReqData ['mobileno'] = mobileno;
postreqData ['全名'] =全名;


  $阿贾克斯({
     网址:dvsds,
     键入:POST,
     数据类型:JSON,
     数据:postReqData,
      错误:函数(){
          警报(发生错误!);
      },
      成功:功能(数据){
           警报(data.message);
     }
   });
  }
 

I am posting a jQuery AJAX POST to a servlet and the data is in the form of JSON String. I am not sure whether data is getting posted or not. Also, I want to verify login and password by fetching it from json object.

Heres the code snippet:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>

    <script type="text/javascript">            
    function doajax(){

    var fullname=$("#fullname").val;
    var mobileno=$("#mobileno").val;


      $.ajax({
         url: 'dvsds',
         type: 'POST',
         dataType: 'json',
         data:{ "mobileno":mobileno, "fullname":fullname},
          error:function(){
              alert("error occured!!!");
          },
          success:function(data){
               alert(data.message);
         }
       });
      }
</script>

My servlet side code:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    try {
        String message=null;

        JSONObject jObj = new JSONObject(request.getParameter("jsondata"));
        Iterator<String> it = jObj.keys(); //gets all the keys

        String Name=null;
        String mobileno=null;

        while(it.hasNext())
        {
            String key = (String) it.next(); // get key

            if(key.equals("fullname"))
                 Name = (String)jObj.get(key);
            else if(key.equals("mobileno"))
                mobileno=(String)jObj.get(key);
        }


        if(Name=="abc" &&  mobileno=="123" )
            message="success";
        else
            message="fail";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", message);
        out.println(jsonObject);

解决方案

You do not need to stringify the data ... just send it as a plain old javascript object ... by specifying datatype as json ... jquery will figure out how to pack the data in the request

No need to change anything on server side

So if your AJAX call becomes:

  $.ajax({
     url: 'dvsds',
     type: 'POST',
     dataType: 'json',
     data: jsondata,
      error:function(){
          alert("error occured!!!");
      },
      success:function(data){
           alert(data.message);
     }
   });

Retrieve them in the servlet as

String fname = request.getParameter("fullname");
String mobileno = request.getParameter("mobileno");

I think you will need to be careful about case sensitivity

EDITED

I see that you Can you change your script to be as follows.

<script type="text/javascript">            
function doajax(){

var fullname=$("#fullname").val;
var mobileno=$("#mobileno").val;

var postReqData = {}; // Create an empty object
postReqData['mobileno'] = mobileno;
postreqData['fullname'] = fullname;


  $.ajax({
     url: 'dvsds',
     type: 'POST',
     dataType: 'json',
     data: postReqData,
      error:function(){
          alert("error occured!!!");
      },
      success:function(data){
           alert(data.message);
     }
   });
  }

这篇关于阅读JSON值的servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆