Monday, July 5, 2010

HTTP PUT, jquery and Java Servlets

If you are trying to create a RESTFULL interface then you need to implement the HTTP Put method to allow updates. Now , all browsers will not allow PUT (or DELETE) in a form method so the the easiest thing to do is use AJAX (xmlHttpRequest actually) to send over the data. Now you could handrole the xmlHttpRequest, but thats reinventing the wheel. Instead we can use JQUERY:

http://api.jquery.com/jQuery.ajax/

So a post can be down as follows (Module and Software are the ids of Input fields in our HTML), $("a") is attaching this to a "a href" statement:

$(document).ready(function() {
// do stuff when DOM is ready

$("a").click(function() {
$.ajax({
type: 'PUT',
url: "/Courses/Software",
processData : true,
data: { Module: $('#Module').val(), Software: $('#Software').val() } ,
error: function(data) {
$('.result').html(data);
alert('Error in put.'+data);
},
success: function(data) {
$('.result').html(data);
alert('Load was performed with '+data);
}
});
alert($('#Module').val()+" : "+ $('#Software').val());
});

});


The problem is how to handle this is the Java Servlet. You are probably aware that you can use a doPut(HttpServletRequest request, HttpServletResponse response) method in the servlet to handle the HTTP Post. The problem is how to get at the data. My first attempt was to just get the parameters:

System.out.println("Software:doPut"+request.getParameter("Module"));
System.out.println("Software:doPut"+request.getParameter("name"));

But that doesn't work. For PUT the data is in the body of the request. You can see this by looking at the content length:

System.out.println("Content length "+request.getContentLength());

So we need to read the body in our servlet (doPut) like this (simple example):

InputStream is = request.getInputStream();
char ch;
for (int i=0; i < request.getContentLength();i++){
ch=(char)is.read();
System.out.print(ch);
}

I'll leave decoding this into name, value pairs until next time

No comments:

Post a Comment