When I try to call Jena using AJAX in my servlet I get this error:
java.lang.ClassNotFoundException: com.hp.hpl.jena.sparql.core.Prologue
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
at fr.objective.blogomatic.semantic.web.ServletAjax.doGet(ServletAjax.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
This is my Jena code:
class classUsingJena {
public void execute(){
String queryString = PREFIXES
+ " Select ?label "
+ " where {"
+ " ?description j.5:entity-label ?label ." + " } ";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out,results, query);
qe.close();}
}
It's running fine, but when I call this function using servlet I get the error described previously.
This is my servlet code:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String service = req.getParameter("service");
classUsingJena jena= new classUsingJena() //bug
return;}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
#Override
public void init() throws ServletException {
ServletConfig config = getServletConfig();
urlAjax = config.getInitParameter("urlAjax");
}
My java script code that runs fine:
$("#Analyser").click(function(){
var article = $("#TxtArea").val();
ajaxFunction("acteur",article);
console.log(article);
});
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction(valeur,txt) {
if(xmlhttp) {
xmlhttp.open("GET","ajax?service=ajax&valeur="+valeur+"&text="+txt,true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
$("#J").text("");
parseXml(xmlhttp.responseXML);
}
else {
//alert("Error during AJAX call. Please try again");
}
}
}
function parseXml(xml)
{
$(xml).find("nom").each(function()
{
$("#J").append($(this).text() + "<br />");
});
}
In the pom I had declared the old version of Arq 1.8.7 instead of 2.8.7. Now it's running fine.
Related
I am currently making a small program using AJAX. I want to send a JSON String to a Servlet, but it doesn't work. In my browser I get the error "Uncaught TypeError: Cannot read property 'open' of undefined"
I'm guessing that this means, that it can't find the Servlet in the following line:
xmlHttp.open("POST", "../JSONServlet", true);
However, I have made similar programs before and never had this problem, so I don't know what to do to make it work.
My html and js files are in Web Pages/ex06 and my Servlet is in Source Packages/servlets/JSONServlet, however I've tried moving it somewhere else (even though I have made programs that worked like this), but it didn't help.
This is the html and javascript:
var xmlHttp;
window.onload = initAjax();
function initAjax() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE6 or older
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (ex) { // noch ältere MS Produkte
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (ex) {
}
}
}
}
function doJSON1() {
var car = new Car("Mercedes", "SLK", 2012); // car erstellen
var carAsJSON = JSON.stringify(car); // json-String machen
alert("Car object as JSON:\n " + carAsJSON);
xmlHttp.open("POST", "../JSONServlet", true); // here is the problem
xmlHttp.onreadystatechange = handleObjectRequest;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(carAsJSON); // json-String senden
}
function handleObjectRequest() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
jsontext = xmlHttp.responseText;
alert(jsontext);
var benz = JSON.parse(jsontext);
var output = benz.brand + " " + benz.model;
document.getElementById("serverResponse").innerHTML = output;
}else{
alert("nope");
}
}else{
alert("...");
}
alert("state change");
}
function Car(brand, model, year, color) {
this.brand = brand;
this.model = model;
this.year = year;
this.color = color;
}
<input type="button" value="JSON-Object senden&empfangen" onclick="doJSON1();"/>
This is the method in my Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStreamReader isr = new InputStreamReader(request.getInputStream());
try {
Gson gson = new Gson();
// auto aus request erstellen
Car car = gson.fromJson(isr, Car.class);
// anderes auto schreiben
Car car2 = new Car("audi", "tt", 2014);
gson.toJson(car2, out);
} catch (JsonSyntaxException e) {
Gson gson = new Gson();
String[] winter = gson.fromJson(isr, String[].class);
String[] summer = {"Jun", "Jul", "Aug"};
out.println(gson.toJson(summer));
}
out.flush();
out.close();
}
My Car class is a simple data class with getters and setters, a default constructor, a custom constructor, and a toString.
You need to have an instance of the XMLHttpRequest() to use the open() method, so add the following line of code:
var xmlHttp = new XMLHttpRequest();
Before you use the open() method like so:
xmlHttp.open("POST", "../JSONServlet", true);
EDIT: - You also have a typo as pointed out by #james before i did, in you're initAjax function you have a variable xmlhttp were as you're global variable is xmlHttp , both are not the same.
I am trying to add parameter and redirect to a page that only accepts request in post method. I am using this code in my servlet and it is not forwarding me to the url.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "http://www.thisone.com";
InputStream in = null;
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//Add any parameter if u want to send it with Post req.
method.addParameter("User", "xyz");
method.addParameter("Name", "abc");
int statusCode = client.executeMethod(method);
System.out.println(statusCode);
if (statusCode != -1) {
response.sendRedirect(response.encodeRedirectURL(url));
in = method.getResponseBodyAsStream();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I don't think it's possible to redirect with post method using this approach. what you can do is get the response to the client and therefore set the location header in response. Implementation for the same is given below:
Once your condition is satisfied:
response.setStatus(307);
response.addHeader("Location", "<url>");
also check out the significance of 307 status code.
Here is the javascript code, which starts with an ajax request and hit a servlet to fetch the desired URL, once it receives the URL, creates a HTML form object, sets values and submits the form...
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callURL(this.responseText);
}
};
xhttp.open("GET", "TestServlet", true);
xhttp.send();
function callURL(url){
var form = document.createElement("form");
form.setAttribute('method', 'POST');
form.setAttribute('action', url);
form.setAttribute('id', 'frmProduct');
form.style.display = 'none';
var i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'name');
i.setAttribute('value', 'Neeraj');
form.appendChild(i);
document.getElementsByTagName('body')[0].appendChild(form);
form.submit();
}
</script>
Below is the implementation of my Testservlet
#WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "http://www.thisone.com";
PrintWriter out = response.getWriter();
out.print(url);
}
}
You can make use of automatic form submit using POST method to do the same.
Please find below sample code:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
private void sendPOSTRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
String postURL = "url to send data";
String value1 = "value for name1";
String value2 = "value for name2";
String content = "<html><body onload='document.forms[0].submit()'><form action=\"" + postURL + "\" method=\"POST\">"
+ "<INPUT TYPE=\"hidden\" NAME=\"name1\" VALUE=\"" + value1 + "\"/>"
+ "<INPUT TYPE=\"hidden\" NAME=\"name2\" VALUE=\"" + value2 + "\"/>"
+ "</form></body></html>";
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.write(content);
}
I have a jsp file with google map, place autocomplete and few buttons. The submit Button click calls a method in Javascript which inturn passes the jsp page 'input' data to callServlet() method as 'params'. I want to call a servlet page MyServlet and pass the params to it. However my callServlet() executes perfectly but doesn't pass on the control/params to MyServlet.
Also How to read params in MyServlet?
Please help me solve it.
JS code:
function callServlet(params) {
var xmlhttp = new XMLHttpRequest();
var url = "./mapServlet";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
console.log(url);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
console.log("Its perfect");
} else {
alert(xmlhttp.status);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
// params is of json format with key value pairs
xmlhttp.send(params);
}
Servlet code: (Made no changes to this page. Its a simple servlet template)
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.print("aaas");
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
web.xml
<servlet>
<servlet-name>mapServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mapServlet</servlet-name>
<url-pattern>/mapServlet</url-pattern>
</servlet-mapping>
Is there a specific reason you're not using jQuery for that?
Basically, xmlhttp.send(params) expects to receive key=value string, not a Json. If you intend to use bare XMLHttpRequest, you'll need to create this string on your own.
Also, this mapping: var url = "./mapServlet"; may be wrong, as usually you serve code from root, and your JS files are served from resource directory such as /js. Using `var url = "/mapServlet" would be better.
Finally, after you reach your servlet, you can read your parameters using request.getParameter("parameter_name")
To call your server using jQuery start with using jQuery.post() method:
https://api.jquery.com/jquery.post/
$.post( "./mapServlet", params)
.done(function( data ) {
console.log("Got ", data);
});
I have a JSP page which I use to submit some data to a HTTPServelet. I need to show an alert after successfully completing task in servlet so I have a JavaScript AJAX function which executes in onSubmit event of JSP Page. but when I click submit button AJAX function does not execute with it.
Here is my Javascript function:
function alerts(servlet) {
var xhr = new XMLHttpRequest();
xhr.open("POST", servlet, true);
console.log("connected to "+servlet);
xhr.send(null);
xhr.onreadystatechange = function() { //this function does not execute
if (xhr.readyState === 4) {
if (xhr.status === 200) {
content = xhr.responseText;
var objects = JSON.parse(content);
console.log(objects);
var elemant = document.getElementById("tblObjects");
var child = elemant.children;
var childLength = child.length;
if (0 < child.length) {
for (i = 0; i < childLength; i++) {
deleteElamant("tblObj");
}
}
}
}
};
}
And my Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
//Do somethings inside Servlet
response.getWriter().write("my alert messege to JavaScript");
RequestDispatcher rd = request.getRequestDispatcher("/NextServlet");
rd.forward(request, response);
} catch (Exception ex) {
}
}
I am completely new to AJAX hence this question. I want to send some information from my javascript code to my servlet.
function getDetails() {
vals = document.getElementById("name").value;//works: vals does get inputted value
request = createRequest();
if (request == null) {
alert("Unable to create request");
return;
}
var url= "ValidateUser.do";
request.open("POST", url, true);
request.onreadystatechange = displayDetails;
//How do I send the value of "vals" to my servlet?
request.send("name="+vals);
}
When I run req.getParameter("name") on my servlet, I always get no value even though "vals" does contain the inputted value. So my question is- how do I access this value from my servlet?
EDIT:
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
return request;
}
FURTHER EDIT:
Servlet code: I want the println statement to print out the name.
//shortened: this method is called by a ControllerServlet
public Object perform(HttpServletRequest req, HttpServletResponse resp) {
//retrieve customer from database
model = SeekerCustomer.getCustomer(req.getParameter("name"));
System.out.println(req.getParameter("name"));
}
function ajaxRequest(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
return new XMLHttpRequest()
else
return false
}
function postReq(){
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("my_Result_tag").innerHTML=mypostrequest.responseText //this is where the results will be put!
}
else{
alert("An error has occured making the request")
}
}
}
var vals = document.getElementById("name").value
var parameters="name="+vals
mypostrequest.open("POST", "ValidateUser.do", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(parameters)
}
In the servlet access vals using:
request.getParameter("name");