How to get response form servlet using XMLHttpRequest - javascript

I have a jetty server running which responds to get requests. If I make the request using a browser:
localhost:8080/sp or 127.0.0.1:8080/sp
I get the correct data back.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.println("{foobar: true"});
response.flushBuffer();
out.flush();
out.close();
}
but when I try to access the same url using JS the response body is empty.
I've tried serving the webpage using both the OS X webserver(port 80) and python SimpleHTTPServer (port 3000).
In both cases the response is empty.
<h1>Single Test Page</h1>
<script>
var httpReq = null;
var url = "http://127.0.0.1:8080/sp";
window.onload = function(){
var myRequest = new XMLHttpRequest();
myRequest.open('get', url);
myRequest.onreadystatechange = function(){
if ((myRequest.readyState == 4) || (myRequest.status == 200)){
alert(myRequest.responseText);
}
}
myRequest.send(null);
}
</script>
Could it be an issue with xss attack prevention?
How can I change my setup to use JS to talk to my servlet?
Is there any other way I can make the HTTP get request from JS?
I even added an entry into my /etc/hosts file:
127.0.0.1 foo.com
and changed the JS url to no avail.

Yes, the problem is that it's a cross domain request.
2 possible solutions :
use JSONP
set CORS headers so that the browser knows it may embed your servlet answer
Both are easy but the second one has the advantage that you just have to set the headers in the servlet code. For example :
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Request-Method", "GET");
Another thing : be careful to open your html file in http:// and not file://.

Related

sending images from java webserver to client

i'm new to java web App i was trying to create simple chat webapp that send images to webserver then the server will send them to other client at first i had problem that the websocket wont send large data so i send my images using
http request
after encoding them to base64 then after i was able to decode it and store it,i was trying to seend it from the server to the other client
i did not find any solution the only way to send it to the other client is using websocket
this is the third day of searching and i'm thinking of given up since there is no resources for noobies
i saw alot of code but they was in high level i hope if some one have the answer of
How can i send the image to the client ?
please Try to explain it in a simple way
the javascript function responsible for sending the img
send=function () {
var file =document.getElementById("image").files[0];
var content_type ={
headers:{
"content-type" : "multipart/form-data"
}
};
var formdata = new FormData();
formdata.append('image',file);
axios.post('AddImage',formdata,content_type)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
the post method that send the file
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part file=request.getPart("image");
InputStream in = file.getInputStream();
byte[] Byte_file = new byte[in.available()];
in.read(Byte_file);
String encodedString = "{encodedString : "+"data:image/png;base64,"+new String(Byte_file)+"}";
//sending the String to the other client via his session
socket.session.getAsyncRemote().sendText(encodedString);
}

Requests to a localhost server running SparkJava work using postman, but not with javascript in a browser

I have this simple server running from eclipse using the SparkJava API:
public static void main(String[] args) {
BasicConfigurator.configure();
staticFileLocation("/public");
port(5678);
enableCORS("*", "*", "*");
get("/hello", (request, response) -> "Hello World!");
post("/hello", (request, response) ->
"Hello World: " + request.body()
);
}
private static void enableCORS(final String origin, final String methods, final String headers) {
options("/*", (request, response) -> {
String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}
String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if (accessControlRequestMethod != null) {
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});
before((request, response) -> {
response.header("Access-Control-Allow-Origin", origin);
response.header("Access-Control-Request-Method", methods);
response.header("Access-Control-Allow-Headers", headers);
// Note: this may or may not be necessary in your particular application
response.type("application/json");
});
}
And I have this Javascript running from a webpage:
var oReq = new XMLHttpRequest();
oReq.open("POST", "localhost:5678/hello", true);
var test = oReq.send("TESTING");
document.getElementById("TEST").innerHTML = test;
I can send requests and get a response when I send them through the Postman chrome app, but when I run this script in chrome, I get the following error:
XMLHttpRequest cannot load localhost:5678/hello. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
I've tried running the script in Firefox and Edge as well, but I still get a network error. Why would the requests work in Postman but not when running a script from any browsers?
It works through Postman because you are directly calling the server. There is no CORS involved here. But when you do it through javascript CORS comes into play. I see you have added the respective headers. That should solve the problem. But the req url doesn't contain http scheme. You need to change localhost:5678/hello to http://localhost:5678/hello

Passing web browser client input to server Java source code

I am developing a web application in Java that takes a string containing a website URL, parses the website HTML to gather information, then uses that information to query a postgresql database. This is already written using Java, HTML, JS and CSS.
In my HTML I have a text input box where the user can paste a URL and submit it using a button. What I would like to do, is get this URL as the String I mentioned above in my Java code, versus hard coding it myself. Eventually, after parsing that URL HTML file and running whatever queries I need on my database, I will return the query results back to the browser for the user to see.
I understand that JavaScript runs in the browser while my Java source code is server side at different times. I've gathered that a possible solution is to submit a HTTPServletRequest in my Java source code that communicates with my JavaScript; however I am unsure of the right steps to accomplish this. XmlHTTPRequest is something else I've seen being used.
Edit - After further reading I am deciding between programming a Java servlet, or a JSP to handle this. I am leaning towards a servlet as I am more familiar with Java than HTML, and will be using more logic (HTML parsing, RDBMS querying using jdbc, returning data).
Does this seem to be the correct decision?
I hope I worded this clearly and that this is a valid question! Thank you!
UPDATE/EDIT
Here is my code I've done so far after thinking about Mois44's answer. I am unsure what to put for the URL in my xmlHttp.send() request. In the browser, there is a text box, and submit button for the user as I said.
Error:
url.html:91 POST http://localhost:8080/myapplication/GetURL?url=http://mywebsite.com/category/123986/webpage/ 404 (Not Found)
This is the project structure for these files:
src/main/
|
|----java/
| |
| |----path/to/java/servlet/myServlet.java
|
|----webapp/
|
|----META-INF/
| |----web.xml
|
|----pages/
|----url.html
|
index.html
web.xml:
<servlet>
<servlet-name>GetURL</servlet-name>
<servlet-class>path.to.java.servlet.myServlet</servlet-class>
<init-param>
<param-name>url</param-name>
<param-value>www.testurl.com</param-value> // don't I set this in my url.html from user?
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/myServlet/*</url-pattern> // not sure about this...
</servlet-mapping>
url.html:
<div class="url-input">
<input type="text" id="txtUrl" class="text-box" value="Paste recipe website URL here" align="middle">
<button onclick="urlRequest()" id="myid" value="myvalue">Go!</button>
<script>
function getURL(xmlHttp) {
document.getElementById("myid").value = xmlHttp.responseText;
return document.getElementById("txtUrl").value
}
</script>
<script>
function urlRequest() {
var xmlHttp = new XMLHttpRequest();
var url = getURL(xmlHttp);
xmlHttp.open('POST', 'http://localhost:8080/myapplication/GetURL?url='+url, true);
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState = 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
};
xmlHttp.send(url);
}
</script>
</div>
myServlet.java:
public class Servlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
handleRequest(request, response);
}
protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String p = request.getParameter("url");
System.out.println("test");
System.out.println(p);
}
}
If you want to use the tools you already know, use JSF.
You also could create a simple HTTP Endpoint in your Java Server and use JavaScript to communicate with it. (You send the String as http payload to the Server with an XmlHTTPRequest and then receive the response in XML, JSON or whatever format you like (raw string?). JSON would be a good choice, because JavaScript supports it very well. For JSON in Java i recommend the Jackson Project)
Edit: JavaScript part example:
// get user input from input field..
var userInput = document.getElementById("#my-input").value;
xmlHttp = new XMLHttpRequest();
// HTTP Method, URL, async
xmlHttp.open('POST', '/myJavaEndPoint', true);
// create onreadystatechange callback function,
// it gets called everytime the readyState changes..
xmlHttp.onreadystatechange = function () {
// readyState 4 means "DONE" - request is complete, responseText now contains the full response..
if (xmlHttp.readyState == 4) {
alert(xmlHttp.responseText); // Show the result to the user.
}
};
xmlHttp.send(userInput); // Start Request, send the user input as post-payload

javascript - Handling redirect from http response

I am trying to build a html page that when I enter it, it will redirect me to another page, depending on an attribute in the session.
If there is an attribute named "username" in the session, it will not redirect me, and otherwise it will.
In order to do so, I wrote a javascript function that calles a java servlet that checks whether or not the attribute exists.
<script type="text/javascript">
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
var data = req.responseText;
}
document.write(req.readyState);
}
req.open('POST','sessionCheck',true);
req.send(null);
</script>
The code in the servlet is:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession hs = request.getSession();
String username = (String) hs.getAttribute("username");
if (username == null)
response.sendRedirect("/login.html");
}
I know that the resonse did send the redirect but the webpage was not redirected.
*Note: I am using Eclipse Java EE for Web Developers.
Thanks!
Javascript AJAX requests follow redirects. It is likely that your javascript code ended up requesting the page that you wished to redirect the browser to.
Try returning the page to redirect to as your response and then getting the browser to navigate to that page.
You can see that the XMLHttpRequest standard states that redirects will be followed:
HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

How to perform Ajax call from Javascript to JSP?

I have a JavaScript from which I am making an Ajax Call to a JSP. Both JavaScript and JSP are deployed in the same web server. From JSP I am forwarding the request to one of the service (servlet) available in other web server using HttpURLConnection. I got the response in JSP, but now I need to pass the response back to JavaScript which made an Ajax Call. How I can do it?
My ultimate goal is to make an Ajax request from JavaScript to a JSP and from that JSP to one of the services and return the response back to JavaScript.
JSP is the wrong tool for the job. The output would be corrupted with template text. Replace it by a Servlet. You just need to stream URLConnection#getInputStream() to HttpServletResponse#getOutputStream() the usual Java IO way.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
URLConnection connection = new URL("http://other.service.com").openConnection();
// Set necessary connection headers, parameters, etc here.
InputStream input = connection.getInputStream();
OutputStream output = response.getOutputStream();
// Set necessary response headers (content type, character encoding, etc) here.
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
That's all. Map this servlet in web.xml on a certain url-pattern and have your ajax stuff call that servlet URL instead.

Categories

Resources