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:

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() {
type: 'PUT',
url: "/Courses/Software",
processData : true,
data: { Module: $('#Module').val(), Software: $('#Software').val() } ,
error: function(data) {
alert('Error in put.'+data);
success: function(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:


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++){

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

1 comment:

  1. Perfect breasts

    A guy walking down the street sees a woman with perfect breasts.

    He says to her "Hey Miss, would you let me bite your breasts for 100

    "Are you nuts?", she replies. And keeps walking away.

    He turns around, runs around the block and gets to the corner before she
    does. "Would you let me bite your breasts for 1,000 dollars?" he asks

    "Listen sir, I'm not that kind of woman. Got it?"

    So the guy runs again around the next block and faces her again: "Would
    you let me bite your breasts just once for 10,000 dollars?"

    She thinks about it for a while and "Hmmm 10,000 dollars, eh? OK, just
    once, but not here. Let's go to that dark alley over there".

    So they went to that alley and she takes off the blouse to reveal the
    most perfect breasts in the world. As soon as he sees them he jumps on them
    and starts caressing them, fondling them, kissing them, burying his face in
    them...but not biting.

    In the end the woman gets all annoyed and asks: "Are you gonna bite them
    or what?"

    "Nah", he replies. "Costs too much."

    Classic Dresses
    Classic Bridesmaid Dresses
    Wedding Dresses with Sleeves