0

Posting to a servlet with javascript

 I needed to figure out how to post and receive info from a javascript to/from a java servlet. Below is the script and the servlet code in case anyone else has the same problem.

Mho

//this function is from an article by Justin Dupree  at https://support.tropo.com/hc/en-us/articles/206241213-REST-POST-and-GET-in-each-Scripting-language

function post(url, options) { 
if(options.query) {
url += "?";
var delimiter = "";
for(var propName in (options.query||{})) {
url += (delimiter + (propName + "=" + escape(options.query[propName])));
delimiter = "&";
}
}
log("Fetching " + url);
var code;
if(options.body === null) {throw {message:"Body is required"};}

try {
connection = new java.net.URL(url).openConnection();// Open Connection
var timeout = options.timeout ? options.timeout : 10000;// Set timeout
connection.setReadTimeout(timeout);
connection.setConnectTimeout(timeout);
connection.setRequestMethod("POST");// Method == POST
var contentType = options.contentType !== null ? options.contentType : "text/plain";// Set Content Type
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Content-Length", options.body.length);// Set Content Length
connection.setUseCaches (false);// Silly Java Stuff
connection.setDoInput(true);
connection.setDoOutput(true);
bodyWriter = new java.io.DataOutputStream(connection.getOutputStream());//Send Post Data
bodyWriter.writeBytes(options.body);
bodyWriter.flush ();
bodyWriter.close ();
code = connection.getResponseCode();
}
catch(e) { throw {message:("Socket Exception or Server Timeout: " + e), code:0}; }
if(code < 200 || code > 299) {throw {message:("Received non-2XX response: " + code), code:code}; }
var is = null;
try {
is = connection.getInputStream();
return org.apache.commons.io.IOUtils.toString(is);
}
catch(e) { throw {message:("Failed to read server response"), code:0};}
finally {try {if(is !== null)is.close();} catch (err){}}
}

 

//below is the script that calls the function that Justin posted
var options={
query:{
first:"first parameter",
next: "next parameter"
},
body : "body of data"
};
var myservlet="http://mydomain/test1";
log("*************starting");
say(post(myservlet, options));
log("*************Ended");

 

// Here is the servlet code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.*;
import javax.servlet.http.*;

public class test1 extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = params(request);
text += " and body is "+body(request);
replyText(response,"Tropo says "+text);
}
private String params(HttpServletRequest request){
Map<String, String[]> map = request.getParameterMap();
String out="";
for(String paramName:map.keySet()) {
String[] paramValues = map.get(paramName);
for(String valueOfParam:paramValues) {
if (out.length()>0) out += " and ";
out += "value of "+paramName+" is "+valueOfParam;
}
}
return out;
}
private String body(HttpServletRequest request)throws IOException{
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
}
private void replyText(HttpServletResponse resp, String text)throws IOException {
resp.setContentType("text/plain");
resp.setHeader("Cache-Control", "no-cache");
PrintWriter out = resp.getWriter();
resp.setContentLength(text.length());
out.print(text);
out.close();
}
}

3 comments

Please sign in to leave a comment.