cancel
Showing results for 
Search instead for 
Did you mean: 

java API handle form submit as json content type

thinhnk
Champ on-the-rise
Champ on-the-rise
Hi friends,
I have a form:

<div id="${el}-body" class="password">
   <form id="${el}-form" action="${url.context}/service/formhandle" method="post">
  
      <div class="header-bar">${msg("label.title")}</div>
      <div class="row">
         <span class="label"><label for="${el}-username">${msg("label.username")}:</label></span>
         <span class="input"><input type="text" maxlength="255" size="30" id="${el}-username" /></span>
      </div>
     <div class="row">
         <span class="label"><label for="${el}-password">${msg("label.password")}:</label></span>
         <span class="input"><input type="password" maxlength="255" size="30" id="${el}-password" /></span>
      </div>
   <form>
</div>

And I have a java-backend webscript class.

public class SimpleWebScript extends AbstractWebScript
{
    public void execute(WebScriptRequest req, WebScriptResponse res)
        throws IOException
    {
       try
       {
         String[] params = req.getParameterNames();
         String errormsg = "";
         String mess = "fail";
         for(int i = 0; i < params.length; i++){
            errormsg += params;
            errormsg += "*";            
         }
         // build a json object
          JSONObject obj = new JSONObject();
          
          // put some data on it
          obj.put("success", false);
         if(params.length == 0)
            obj.put("message", fail);
         else
            obj.put("message", errormsg);          
          // build a JSON string and send it back
          String jsonString = obj.toString();
          res.getWriter().write(jsonString);
       }
       catch(JSONException e)
       {
          throw new WebScriptException("Unable to serialize JSON");
       }
    }   
}



I submit the form with content type "application/json" and use java backend to handle it. But I cannot get the parameters as I want be cause req.getParameterNames() not work. It returns an empty string array. Smiley Sad How can I get the form field? Please help me.Thanks for any help.
2 REPLIES 2

muralidharand
Star Contributor
Star Contributor
Hi,
In HTTP Post, the post data will be in the body and it will not present in the URL.
So, req.getParameterNames will be null and you've to use req.getContent to get the data and convert them into JSON.

http://www.springsurf.org/sites/1.0.0.M3/spring-webscripts/spring-webscripts/apidocs/org/springframe...()


Can you please try the below one ?


@Override
   protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache)
   {

      Map<String,Object> model = new HashMap<String, Object>();
      Content c = req.getContent();
      if (c == null)
      {
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing POST body.");
      }
     

      // Process the JSON      
      JSONParser parser = new JSONParser();
      JSONObject json = null;
      try
      {
         Reader reader = req.getContent().getReader();
         Object jsonO = null;
         if (reader.ready())
         {
            jsonO = parser.parse(req.getContent().getReader());
         }
         
          if (jsonO instanceof JSONObject && jsonO != null)
          {
              json = (JSONObject)jsonO;
          }
          else
          {
              throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Wrong JSON type found " + jsonO);
          }
      }
      catch(ParseException pe)
      {
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Invalid JSON data received", pe);
      }
      catch(IOException ioe)
      {
          throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Error while reading JSON data", ioe);
      }
///…………………… Your code goes here …………………….
}

Hi Murali,
Thank you very much.
Based on you help, now I can solve the problem. WebScriptRequest also provides method parseContent() to parse body it as a object. I can downcast it to json object.

        JSONObject json = null;
   Object jsonO = req.parseContent();
   if (jsonO instanceof JSONObject && jsonO != null)
   {
      json = (JSONObject)jsonO;
   }

And it works.