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);
}
Related
The problem
I'm creating a web app where the user is served a login page, login.html, and has to enter his credentials. The servlet class grabs the information using ajax in the form of a POST request, generated by the user clicking the submit button. After checking the correctness of the credentials, i wish to serve the user with a new HTML page, a welcome page, where the response of the servlet is transferred. The problem i'm facing is how to transfer the response from a starting LoginServlet class to a WelcomeServlet all the meanwhile, the client is projecting a new HTML page, welcome.html, and catch the response of the WelcomeServlet in an ajax call made by a js script in the new HTML page.
Background
I'm just starting to delve into the development of web-apps, so if i'm mistaken in any part of my logic and understanding of the whole frontend-to-backend process, please say so. I'm aware of the redirect() and forward() functions but i'm not understanding the way these functions can be used in conjunction, or the complete difference, with the client side of things.
I have the following servlets:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("welcomeservlet");
dispatcher.forward(request, response);
}
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//parse request and send response
}
In the login.html file i've included the following js code:
function loadNewPage() {
// retrieve data and store them in a js Object
$.ajax({
url: "loginservlet",
type: 'POST',
dataType: 'json',
data: JSON.stringify(jsObject),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
window.location.href = "welcome.html";
},
error: function (data, status, er) {
alert("error: " + data.text + " status: " + status + " er:" + er);
}
});
}
I'm not including another js script which would be placed inside the welcome.html purposely since i don't know what would i have to add in there to catch the response of the new servlet. A possible reason why this whole thing isn't working could be that i'm missing something in the functionality of the forward() function but couldn't find an example online that does the exact thing that i want to do.
(Image credit w3schools)
The fact is you can't jump to another servlet. Ajax response will be sent back to the same webpage from which request was generated.
For your requirement what you can do is, Check whether login is success or not in LoginServlet. If yes create a token, save it in database along with the username and send the same token as response to the client.
Now in client save the token in localStorage and redirect to welcome.html.
On welcome.html page loading check whether token saved in localStorage exists or not. If yes, check whether it's valid or not. If valid the call WelcomeServlet . Else display login screen.
It's called token based authentication. You can read more about it here
I want to download a file from the front end. The file is generated in the TestFlow.generateReport method.
My code runs until the end but it doesn't download anything. It just prints the data to the console.log.
What am I missing here?
My backend controller:
#RequestMapping(value = "/flow/generate-report" , method = RequestMethod.GET)
public #ResponseBody void generateFlowReport(#RequestParam("flowName") String flowName, HttpServletResponse response) {
InputStream resource = TestFlow.generateReport(flowName);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition","attachment; filename=report-" + flowName + ".xlsx");
try {
IOUtils.copy(resource,response.getOutputStream());
response.flushBuffer();
resource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My frontend code:
$('.generateReport').click(function () {
var flowName = $(this).attr('name');
$.ajax({
url: '/flow/generate-report',
type: 'get',
data: {flowName: flowName},
success: function (data) {
console.log(data);
}
})
});
I get HTTP status 200
HTTP/1.1 200
Content-Disposition: attachment; filename=report-tellerFlow.xlsx
Content-Type: application/xlsx
Transfer-Encoding: chunked
Content-Type: application/force-download header might not always work because some browsers/web clients might not support the attachment download.
Try changing to Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet which is the correct XLSX type and then check the documentation for your browser/web client. As per this answer using Ajax to download a file might not won't work in your web client.
I'm not sure that an XHR request can trigger a download dialog on the browser. You might want to spawn a new window instead with the download URL - the browser should detect the content disposition and handle the download accordingly.
If you still want to do it with XHR, you need to use Blobs instead - JavaScript blob filename without link
How do I obtain the response from google volley? I'm able to display the response in my logcat using System.out.println("Volley"+response);
I cant figure out how to pull it out of the google volley function. Heres my code:
final String url = MAIN_URL;
// prepare the Request
StringRequest sr = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Volley"+response);
//I want to be able to get this response and use it in other functions.
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error"+error);
}
});
// add it to the RequestQueue
sr.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(sr);
I always put queue into singleton - Application and request can be called and received wherewer in the code, fom example:
android volley caching asynchronous requests - How te get url of the request in ResponseListener
So you just create your own response listener in the class where you need it
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://.
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.