Василий Пупкин Василий Пупкин - 3 years ago 182
Ajax Question

Spring HttpRequestHandler + XMLHttpRequest

i have a problem HttpRequestHandler does not receive any data when i send post data by javascript. i want to receive value of content, but it does not work.
Here is javascript code:

function utils_saveElementAndGetId(url,content) {
var xhr = new XMLHttpRequest()

xhr.open("post", url, false);
xhr.send(content);

if (xhr.status != 200) {
alert(xhr.status + ': ' + xhr.statusText)
} else {
return xhr.responseText
}
}


here is code of HttpRequestHandler:

public class HeaderServlet implements HttpRequestHandler {
private static final Logger log = LoggerFactory.getLogger(HeaderServlet.class);

TemplateDao templateDao;
HeaderElementDao headerElementDao;
CheckboxElementDao checkboxElementDao;

@Autowired
public HeaderServlet(TemplateDao templateDao, HeaderElementDao headerElementDao, CheckboxElementDao checkboxElementDao) {
this.templateDao = templateDao;
this.headerElementDao = headerElementDao;
this.checkboxElementDao = checkboxElementDao;
}

public void handleRequest(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {

String content = req.getParameter("content");
HeaderElement headerElement = new HeaderElement(content);

Long templateId = (Long) req.getSession().getAttribute("id");
Template template = templateDao.get(templateId);
headerElement.template = template;
headerElementDao.create(headerElement);

template.headerElements.add(headerElement);
templateDao.saveOrUpdate(template);


resp.setStatus(200);
resp.setContentType("text/plain");
resp.getOutputStream().println(headerElement.getId());
resp.flushBuffer();
}
}

Answer Source

I have solved the problem , the problem was in javascript side , i have just forgot to add xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download