XmlHttpRequest status=0 - java

I have this ajax call from a javascript file and I want to pass as a parameter the id of the user that I want to delete:
function eliminaUtente(id,nome){
if (confirm("Sei sicuro di voler eliminare l'utente "
+ nome
+ "?")) {
var xmlHttp2 = new XMLHttpRequest();
xmlHttp2.open("POST", "EliminaUtente", true);
xmlHttp2.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
var params2 = "id=" + id;
xmlHttp2.send(params2);
xmlHttp2.onreadystatechange = function() {
if (xmlHttp2.readyState == 4)
{
alert(xmlHttp2.status); <-----------this prints always 0!
if (xmlHttp2.status == 200) //
{
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
}
};
}
}
in the correspondant Servlet called EliminaUtente i have this code:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");
System.out.println(id);
String query = "delete from utente where idutente=" + id;
System.out.println(query);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager
.getConnection("jdbc:mysql://localhost/Spinning?user=root");
PreparedStatement prest = con.prepareStatement(query);
prest.executeUpdate();
response.setContentType("text/plain");
PrintWriter ajaxWriter = response.getWriter();
ajaxWriter.print("ok");
ajaxWriter.flush();
ajaxWriter.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
response.setContentType("text/plain");
PrintWriter ajaxWriter = response.getWriter();
ajaxWriter.print("ko");
ajaxWriter.flush();
ajaxWriter.close();
}
}
}
I can't understand where is the problem...can you help me please? ;)

I try your code and change a little bit i want to explain what did i and what i learn from it.I read some source. First i read XMLHttpRequest object and onreadyState event.
I implement your example both PUT and GET action method.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.test.testServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
</web-app>
testServlet.java
package com.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class testServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
/*super.doPost(req, resp);*/
String strId = req.getParameter("id");
System.out.println(strId);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);
String strId = req.getParameter("id");
System.out.println(strId);
}
}
and main part NewFile.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="Submit" onclick="eliminaUtente('1')" width="100%" />
</body>
<script language="javascript" type="text/javascript">
function eliminaUtente(id) {
var xmlHttp = new XMLHttpRequest();
var url = "test/NewFile.jsp?id=" + id;
xmlHttp.open("POST", url, true);
xmlHttp.send(url);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
};
}
</script>
</html>
with this way i write the parameter 1(i hardcode it in jsp file method invoke) and write it to console, the first thing in here the difference your code and mine i remove the xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); because if the method type is POST default encryption is this.
enctype = content-type [CI]
This attribute specifies the content type used to submit the form to the server (when the value of method is "post"). The default value for this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" should be used in combination with the INPUT element, type="file".
So no need to enctype default is OK for POST.
And this is open method signature open(method, url, async, user, password) here async is the parameter which means if it is false don't wait a response from server implement the other line when response is come it will run. If it is true wait until response is come. Actually i try bot of them and it is worked.
Lastly i try it with GET. If you want use it with GET you should add xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); code for encryption and remove the url parameter from send() method.
function eliminaUtente(id) {
var xmlHttp = new XMLHttpRequest();
var url = "test/NewFile.jsp?id=" + id;
xmlHttp.open("GET", url, true);
xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
};
}
Note: I try this code in firefox, i create xmlHttpRequest object. For all browser(include IE6) sure you know use:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

typo?
alert(xmlHttp2.status); <-----------this prints always 0! Now has "2'

The problem was that I have to put false in this line:
xmlHttp2.open("POST", "EliminaUtente", FALSE);

Related

JSTL: How do I account for HTML escape sequences on <C:OUT>?

I have a Java Dynamic Web Project where one of the Servlets does the following:
/**
* Servlet implementation class DataAPIServlet
*/
#WebServlet(name = "data", urlPatterns = { "/data" })
public class DataAPIServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String format;
/**
* #see HttpServlet#HttpServlet()
*/
public DataAPIServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
format = request.getParameter("format").replaceAll("\"", "");
// create data model and add to request object
RequestDispatcher requestDispatcher = null;
if (format.equals(null)) {
requestDispatcher = jsonDispatcher(request);
response.setContentType("text/json");
} else {
System.out.println("SERVING FORMATTED DATA : " + format);
String returnString;
switch (format.toLowerCase()) {
case "xml":
returnString = Films.getFilmsXML();
request.setAttribute("data", returnString);
requestDispatcher = xmlDispatcher(request);
response.setContentType("text/xml;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
break;
case "csv":
returnString = Films.getFilmsCSV();
request.setAttribute("data",returnString);
requestDispatcher = csvDispatcher(request);
response.setContentType("text");
break;
case "json":
returnString = Films.getFilmsJSON();
request.setAttribute("data", returnString);
requestDispatcher = jsonDispatcher(request);
response.setContentType("text/json");
response.setContentType("text/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
break;
}
}
// Forward the request to the view
requestDispatcher.forward(request, response);
}
private RequestDispatcher xmlDispatcher(HttpServletRequest request){
return request.getRequestDispatcher("xml.jsp");
}
private RequestDispatcher jsonDispatcher(HttpServletRequest request) {
return request.getRequestDispatcher("json.jsp");
}
private RequestDispatcher csvDispatcher(HttpServletRequest request){
return request.getRequestDispatcher("csv.jsp");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
doGet(request, response);
}
}
One of the servlets spits out the data in xml/json/csv format based on the url query (for exmaple /data?format=json will return json data for all the films in databse).
Through debug I have found that my JAXB/GSON methods are properly creating a data set from my model however when viewed in the response to the browser something is going wrong which likely looks like the HTML escape sequences for special characters such as "<" on xml tags.
This narrows it down to something to do with the "" method in JSTL.
My XML is displayed by the following jsp:
<%#page contentType="application/xml" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page trimDirectiveWhitespaces="true"%>
<c:set var="data" value="${data}"></c:set>
<c:out value="${data}" />
I can tell the data being passed by the response to the JSP is correct by debug :
Unless the issue with what I'm doing would be resolved by some better mechanism for serving the xml/json/csv data than simply serving it to a jsp file? suggestions welcome.
In the tag of JSTL set escapeXML to false in order to maintain the original characters. Otherwise escapeXML true will do the opposite.
<c:out value='${foo(someParameter)}' escapeXml="false"/>

Session parameter is aways null

I am trying to pass a string from one servlet to another but I always get a null value in the second servlet. I've banged my head against this one for almost 2 weeks to no avail and I've run out of ideas. I've read all the similar question posted on here and I still get a null value.
This is the first servlet
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");
int userId = DBConnect.getIdByName(name);
int lobbyId = DBConnect.insertInLobby(userId);
request.setAttribute("lobbyId", lobbyId);
request.getRequestDispatcher("PlatformPairsLobby.jsp").forward(request, response);
}
catch (ServletException | IOException e)
{
logger.error("Error " + e);
}
}
This is the second servlet with the name string that always is null.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");
int id = DBConnect.getIdByName(name);
request.setAttribute("id", id);
String lobbyId = request.getParameter("lobbyId");
request.setAttribute("lobbyId", lobbyId);
response.setContentType("application/x-java-jnlp-file");
try
{
request.getRequestDispatcher("PairsJnlp.jsp").include(request, response);
}
catch (ServletException | IOException e)
{
logger.error("Error " + e);
}
}
To access the second servlet, I use a button in this JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.awt.List"%>
<%#page import="java.util.*"%>
<%#page import="database.DBConnect"%>
<%# taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html>
<head>
<%
ArrayList<String> list = (ArrayList<String>)
request.getAttribute("lobbyList");
Integer lobbyId = (Integer) request.getAttribute("lobbyId");
%>
------------------
window.location.href =
"http://192.168.100.154:8080/GamePlatformCore/SecondServlet?lobbyId=<%=lobbyId%>";
The name is set in a different servlet.
request.setAttribute("verificare", verificare);
HttpSession session = request.getSession();
session.setAttribute("name", name);
if(request.getServletContext().getAttribute("userMessages")==null)
{
request.getServletContext().setAttribute("userMessages",new ArrayList<String>());
}
request.getRequestDispatcher(WELCOME_PAGE).forward(request, response);
You are using request scope attribute to get String value, use following code to get Session value:
<% String lobbyId = (String)request.getSession().getAttribute(lobbyId); %>

AJAX call is not reaching Servlet

I am trying to make a simple textbox which initiate a suggestive feedback based on the characters entered by the user. I am trying to fetch a JSON object from a Servlet but my AJAX call is somehow not reaching the servlet. On checking the status of AJAX request using this.status I am getting error code 404. Can anyone suggest me a solution:
[![enter image description here][1]][1]
Here's my servlet: FetchServ.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
Connection con;
ResultSet rs;
java.sql.PreparedStatement pst;
String ch = request.getParameter("q");
String data;
ArrayList<String> list = new ArrayList();
response.setContentType("application/JSON");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("drivers registered");
con = DriverManager.getConnection(con_url, userID, password);
System.out.println("connection created");
pst = con.prepareStatement("SELECT * FROM candidates where FirstName LIKE ?");
pst.setString(1, ch + "%");
rs = pst.executeQuery();
System.out.println("query executed");
while(rs.next())
{
data = rs.getString("FirstName");
list.add(data);
}
String json = new Gson().toJson(list);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
response.getWriter().append("Served at: ").append(request.getContextPath());
} catch (SQLException | ClassNotFoundException e) {
System.err.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
the jsp code:
<script>
function suggest(str){
if(str.length == 0){
return;
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
document.getElementById("sugg").innerHTML = this.status;
if(this.readyState == 4 && this.status == 200){
//var res = JSON.parse(this.responseText);
document.getElementById("sugg").innerHTML = this.responseText;
}
};
try{
xmlhttp.open("GET", "com.test.java/FetchServ", true);
xmlhttp.send();
}catch(e)
{
alert("unable to connect ");
}
}
}
</script>
</head>
<body>
<form>
Search:<input type="text" onkeyup = "suggest(this.value)">
</form>
<p id = "sugg"></p>
</body>
</html>
and this is the result I am getting:
[![enter image description here][2]][2]
<display-name>ACtxtbox</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.test.java/FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/FetchServ</url-pattern>
</servlet-mapping>
</web-app>
your Web.xml entries are not proper, check the url which you are using in urlbar and the form submitted using xmlhttp.open("GET", "fetch", true); you can debugg the actual url passed as a request to the server by opening developer tools and navigating to the network tab it will look something like below.
also your <servlet-class>ACtxtbox/FetchServ</servlet-class> is not correct, it should be with package path like <servlet-class>sompackagepath.FetchServ</servlet-class>
EDIT
As per your images, I can see you have declare index.jsp which will be accesible by giving url: http://localhost:<port_number>/ACtxtbox/index.jsp.
Now you should note below points:
As you are calling servlet using ajax call where you have given
parameters as fetch in this line of code in you javascript
xmlhttp.open("GET", "fetch", true); hence it is now changing your
url to http://localhost:<port_number>/ACtxtbox/fetch
your web.xml entry should be like this
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.rishal.test.FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/fetch</url-pattern>
</servlet-mapping>
How come your url pattern is coming like
http://localhost:<port_number>/ACtxtbox/com.test.java/fetch ? is
it you have modified the web.xml entries. Please read the tutorials
and google about web application,jsp,servlets and ajax calls. you
should also note that you have to create your servlet class under
some package as i have given in the web.xml entry
com.rishal.test its package path and class is inside this package
path.
package com.rishal.test;
public class FetchServ extends HttpServlet {
----------------------
---------------------------
}

JAVA - get response from system to the UI

I'm new to java and I have servlet which connect to some system and get data, while debug the code I see that I was able to connect and get the data, ( I dont get any error) . I use the following code :
try {
urlConnection.connect();
} catch (IOException e) {
String messagePrefix = "Connection error: ";
LOGGER.error(messagePrefix, e);
}
OutputStream clientOutStream = responseToClient.getOutputStream();
copyStream(backendInStream, clientOutStream);
responseToClient.setStatus(backendResponseCode);
int backendResponseCode = urlConnection.getResponseCode();
InputStream backendInStream = null;
try {
if (backendResponseCode < 400) {
backendInStream = urlConnection.getInputStream();
}
} catch (IOException e) {
String messagePrefix = "Input stream error: ";
LOGGER.error(messagePrefix, e);
}
Now I have this simple index.html and my question how should I print the data back to the browser ?
( I wasnt able to copy the html file as code :(
Any idea how to pass the response to the UI , I try to add response tag and put the variable as global without success...
Yes you can send the response using dispatcher or httpsession and use jsp to get the response in UI
in your back end simply use
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("backendresponse",backendresponse))
}
and in your jsp you can get and store that data in an arraylist as
<%
ArrayList<> list=(ArrayList<>)session.getAttribute("backendresponse");
%>
Now you can use this list to populate data in any tag using <%= %> as this is equivalent to a print statement as any expression say
<%for(int i=0;i<list.size();i++)
{%>
<%=list.get(i).getData() %>
<%}%>
will print the response in your browser
UPDATE
in your servlet you can get the parameters as
String url=request.getParameter("url")
Class obj=new Class(url)
session.setAttribute("obj",obj);
response.sendredirect("disp.jsp")
in your disp.jsp
<%
ArrayList<> list=(ArrayList<>)session.getAttribute("backendresponse");
%>
<html>
<head>
</head>
<body>
<%for(int i=0;i<list.size();i++)
{%>
<h1> <%=list.get(i).getData() %></h1>
<%}%>
</body>
</html>
You should have doGet method which has PrintWriter taking each line of the HTML:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
.
.
.
}

I can't retrieve responseText from servlet using AJAX

I have a servlet file called NewServlet.java. This servlet is called by my AJAX script to retrieve the response.
I have verified the servlet by testing it in a browser.
But when I call it from my AJAX script it gives me a blank responseText and an error that says
XMLHttpRequest cannot load
http://localhost:8084/WebApplication1/NewServlet.
Origin null is not allowed by
Access-Control-Allow-Origin
NewServlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<option value='1'>one</option>");
out.println("<option value='2'>two</option>");
out.println("<option value='3'>three</option>");
out.println("<option value='4'>four</option>");
out.println("<option value='5'>five</option>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
test.html
<html>
<head>
<script language = "javascript">
var xmlDoc = 0;
var xhttp = 0;
function reciveData()
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = redirectUser;
xhttp.open("GET","http://localhost:8084/WebApplication1/NewServlet",true);
xhttp.send();
}
function redirectUser()
{
if (xhttp.readyState == 4)
{
log = 0;
xmlDoc = xhttp.responseText;
alert(xmlDoc);
}
}
</script>
</head>
<body onload="reciveData()">
</body>
</html>
Can some one point me in a right direction ?
Thanks.
That's on the browser side...the security model only allows AJAX requests to the same host/port that you fetched the page from. Make sure that you've fetched your page via the server (e.g. http://localhost:8084/test.html) and not loaded it via the filesystem. Then you should be good to go...or at least continue debugging. ;)
This can indeed happen when the servlet runs on a different port than where the ajax request is coming from. This violates the Same Origin Policy for ajax requests and thus the browser won't process the ajax response. Apart from hosting the servlet behind the same port, other solutions are to return JSONP instead or to let the servlet set the HTTP Access-Control headers.
response.setHeader("Access-Control-Allow-Origin", "*");
You however need to keep in mind that this way your servlet is by Ajax accessible to everyone. If the servlet returns sensitive information, then this is a security hole. But if it does not and it is supposed to be a public webservice, then it's safe.
in my experience, if you want to load data with ajax, send your request to a jsp file, and get your response text from that jsp file. it is a lot easier to handel. see this example if you like
EDITED<<
==========================
ajax_load.js :
var xmlhttp;
function loadAdminRight(category){
xmlhttp = GetXmlHttpObject();
if (xmlhttp == null) {
alert("Your browser does not support Ajax HTTP");
return;
}
var url = "load.jsp";
url = url + "?category="+category;
xmlhttp.onreadystatechange = getLoad;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function getLoad(){
if (xmlhttp.readyState == 4) {
document.getElementById("right_content").innerHTML = xmlhttp.responseText;
//or what you want to do
}
}
===========================
load.jsp :
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String l_category = request.getParameter("category");
if(l_category.equals("article")){
out.write("You have choosen article category");
out.write("<br/>");
}
}else if(l_category.equals("news")){
out.write("You have choosen article category");
out.write("<br/>");
}
%>
and to make the ajax going you just need to call the .js function from where you want, for example on a button click action :
onClick="loadAdminRight("article");"
and you can import your java classes in a jsp file with adding <%page import="" %> to the top of your jsp page for example :
<%#page import="com.omicc.classes.Article"%>
write your own load.jsp file which handles the response, then use out.write in your jsp file to write the response text.
i wish it helps you
This will solve your issue..
// Ajax response
res.setContentType("text/javascript");
res.setCharacterEncoding("UTF-8");
res.setHeader("Cache-Control", "no-cache");
PrintWriter out = res.getWriter();
out.print("GRANTED");
out.close();

Categories