Java servlet - Forwarding/Redirecting from subpage - java

I am working on a project where I have running servlets packaged in a war that listen for requests and populate a foreign div on a separate page. An initial request is made to servlet (a) and if there is data to display, it renders that HTML. If there is NO data, it passes a query string to another servlet to handle the request and then renders a page with options to choose.
I am running Tomcat 6 with Windows Server 2008.
But I run into two problems:
When I use redirect, I get no response from the servlet being
redirected to. I have some javascript alerts up that are never called by the (b)
servlet. I AM using relative paths and confirm the link is
correct in logs.
When I copy that link in step 1 in a new window, I see
the results. Just not when it's embedded in another page that makes
the request. Why would that be? Is it possibly a limitation from the host page and not being able to render the response?
When I use a forward, I see the servlet response,
but then a new window opens. Thus taking the person away from the
original page. This would be great if the results render in the same page.
What's the best practice to assure that I can "redirect" from an initial servlet call to another servlet using the response object from that first servlet?

A redirect returns a HTTP 302 response with the new URL in Location header which the client needs to deal with. Basically, your JS code must check the response status code if it's 302 and then extract the Location header and then re-send a new request on it. Repeat this until the response status code is 200.
That it works when pasting the URL in browser's address bar is because the browser already knows how to deal with 3nn responses properly. If you open up the network traffic tracker in browser's webdeveloper toolset, then you'll see that a second GET request is been fired on the new URL.
Another way, if the servlets run in the same container, is to just use RequestDispatcher#forward() instead of HttpServletResponse#sendRedirect().

Related

How to intercept web url from chrome and add headers to the request?

given: my chrome browser hits the following url that renders a single page application web view (index.jsp).
url: http://server/dostuff?stuff=123
however, what I want to do is somehow intercept that GET request and tack on a header to it (i.e. X-HIDE-MAIN-FOOTER). if this header is present the code simply hides the footer.
doing so would allow me to see the output per chrome (and verify the footer is hidden.
I have tried sending a raw GET request through postman and other api-rest test tools with that header included in the GET request but the payload comes back with a lot of javascript tags (the same ones as a regular request so I can't tell if the header is hidden or not) and won't render the page in preview mode per postman nor can I save the file locally as .html to see what gets rendered.
any ideas here how to achieve something like this?
This worked very well
https://chrome.google.com/webstore/detail/modheader/idgpnmonknjnojddfkpgkljpfnnfcklj?hl=en
credit to #Allahbaksh Asadullah

Set cookie in java, read in javascript

I'm trying something similar to this: Detect when browser receives file download
I'm using Chromes Developer Tools to monitor my cookies and my problem is that the cookies I set in my server side code (java in my case) are only visible on the request. Not when I check the Resources tab in Chrome Dev Tools.
I think it might have something to do with the fact that my request is submitted by constructing a hidden form and submitting this (I'm using ExtJS 4.2.2).
All I can see in my Resources tab is the JSESSIONID cookie from Tomcat.
Can anyone help me set cookies from java that I can read in JavaScript after the request completes?
Screenshots:
There are lots of ways to do this but heres one that would allow you to drop the cookie approach. You really should be setting your cookies to HttpOnly for security reasons unless you have a use case that requires it.
Expose your submit button in some sort of Iframe so users can submit
the file while still remaining on the primary page.
Detect when a click occurs in the iFrame and start polling through
AJAX at some URL such as "/FileUploadStatus".
On the server side once the file is completed upload set a session
attribute such as
HttpSession session = request.getSession(false);
session.setAttribute("fileUploadStatus",true);
When the AJAX request hits the servlet at /FileUploadStatus, check the session variable to see if the the file upload servlet has changed the value of fileUploadStatus to true. If so then return an indication to the client to stop polling and update
the page and clear the session attribute on the server.
NOTE: Detecting a click in an iFrame is hairy stuff across various browsers. You might have to just start polling the second they access your "Upload Page" and simply wait.
Alternate Solution: You could also form a direct connection using the new WebSocket API. THis approach runs the fastest but not all browsers support websockets.

Redirecting html page

Here is my problem :
I have to perform post from java code to some page , get the data and parse it.
The problem is that only my country ip can post to this page. Requests from another ip's are rejected.
I want to find workaround.
I have added my html page on server in my country (this server accessible from all ips) . Now I am sending a get request (in open to all server) to this page from Java code.
What I want to do is to redirect my html page to post to the original page.
I tried to use redirection , but it doesn't work - from Java code I get my html page and not redirected one.
Is there any solution or my problem ?
Thanks
I tried to use redirection , but it doesn't work - from Java code I
get my html page and not redirected one.
Yes it wont work because redirection works on client side. You perform a request to your HTML page which sends back a redirect header and your Java implementation doesnt know what to do with it. Even if it did, it had to make a new request to redirected page, which means that the request to the redirected page would still be from a denied IP.
Another option is that your redirection HTML uses JavaScript window.location.assign or something like that. The point remains the same, beacause this also is a client side solution.
You have to use some kind of server side language on the host where you placed your HTML and in that server side script you have to perform a (post or get as you wish) request to only-your-country URL. This way this only-your-country URL will see that the request came from the host where the script was, not the client itself.
For example if you can use java as your server side language on the place where currently your redirection html is, then you can check out this thread: How to send simple http post request with post parameters in java
You need a reverse proxy installed on a server located in your country. If you make a request to this reverse proxy, it will make a request to the only-your-country server and when it gets a response it will forward it to you.
So the only-your-country server will receive the same request as you make to the reverse proxy, but with a source IP address changed to the IP of the reverse proxy server.

Hide querystring parameters from url in response.sendRedirect

I have a java servlet that is redirecting to a web application on a different server.
I was wondering if there is a way to hide the querystring parameters, so they are not visible to the client in the address bar.
response.sendRedirect("http://www.mywebapp.com/login.html?parameter1=value1&parameter2=value2");
Is there a way to force the sendRedirect to POST to the page and hide the querystring?
Edit: use case.
A user goes to http://www.mywebapp.com
They are automatically redirected to my servlet filter
The servlet handles SSO to an Identity provider using SAML
Once it recieves the SAML response back, I redirect the now authenticated user back to mywebapp.com
I want to pass some parameters back to the webapp. Parameters from the SAML response. But I don't want the user to see them in the URL
Clearly, sendRedirect() is not what I want. What would be the best way to handle this?
No, you can't use POST in this scenario. When calling sendRedirect() this is what you send back to the client:
HTTP/1.1 302 Found
Location: http://www.mywebapp.com/login.html?parameter1=value1&parameter2=value2
Browser interprets this and points user to that location.
Something tells me (maybe login.html name and two parameters) that you want to automatically login user on some web site). Don't go this way, sending username/password (both using GET parameters and inside POST) is really insecure.
Without knowing much about your use case it's probably the best solution to call http://www.mywebapp.com/login.html from your servlet, parse the response and return it to the user (so he will never really see mywebapp in his browser.
You could connect to the other server from your servlet (HttpConnection) and copy the returned data. The user will only see your server.
An alternative is returning an HTML page that does send a POST form automatically after loading. The user will need to allow JS.
You can forward the request from server side and then at the end redirect to some other page
I found a way for hiding any string from Java or Android project with concept of inner classes using proguard to hide them a class is my server side processing

ajax problem - 200 OK in firebug but red message with no response body

I have small ajax problem related to cross domain as i see it.
On localmachine i created html example with some ajax:
in registration text field user types 'username',
on every keystroke ajax sends it to
local Tomcat, where servlet checks if that username is already used
and sends 'taken' reponse back.
No problem on localhost at all.
As soon as i type used 'username' servlet sends 'taken' response
and browser displays it.
But, when i put test html page with ajax
on remote machine (some free hosting on remote network)
that sends validation request on my localhost Tomcat,
connection is made,
in Tomcat console i see request comming,
and in firebug in Mozzila this is Console ouput:
GET http://89.216.182.25:8080/Dinamicki1/UsernameServlet?username=zik 200 OK
...but in response tab
there is not servlet response 'taken'
and message in firebug is in red color
So servers communicate well, no firewall problems, response is 200 OK
But response body is empty.
Any ideas what this red messages in firebugs are?
Thank you very much in advance.
And if anyone can recommend a some serious ajax tutorial for java
it will be highly appreciated :)
You need to use a domain-relative URL in your Ajax request:
/Dinamicki1/UsernameServlet?username=zik
Or a context-relative URL (assuming that the page is served from /Dinamicki1):
UsernameServlet?username=zik
With regard to "Ajax tutorial for Java", start here: How to use Servlets and Ajax?
You cannot use AJAX to read replies from other domains.
Your HTML must be on the same server (and same domain, port, and protocol) as the AJAX servlet.
The 200 status reported in Firebug does not indicate the validity of the cross-domain ajax call, be it successful or not.
You might want to try using a proxy method to perform the call.
E.g. JavaScript: Use a Web Proxy for Cross-Domain XMLHttpRequest Calls
I figured out how to solve it from this site:
"To allow directory browsing via Apache Tomcat change the parameter "listings" in the file conf/web.xml from false to true."
Call your page not as C:/Documents and Settings/.../page.html but as localhost:8080/your_servlet_name (page is better named index.html).
This way, you will be able to make AJAX requests to localhost:8080/your_servlet_name/something_else.
A solution that worked for me was that I had to add "www" to the url! I was using URL Rewrite, so every URL that I had (image, js, get, load, post), I needed to use full url, but it was missing "www"!
For me, It was web api(c# .NET) request and cors was not enabled.
Added header for cors on controller and it solved the problem.
[EnableCors(origins: "*", headers: "*", methods: "*")]

Categories