Reading whole url from servlet - java

I would like to read from a servlet the exact URL that was set in the HTTP request. That is together with any URL rewritten parts (;jsessionid=…).
Is it possible?

You can get the request URL (the part before ; and ?) as follows:
StringBuffer requestURL = request.getRequestURL();
You can check as follows if the session ID was attached as URL path fragment:
if (request.isRequestedSessionIdFromURL()) {
requestURL.append(";jsessionid=").append(request.getSession().getId());
}
You can get and append the query string as follows, if any:
if (request.getQueryString() != null) {
requestURL.append('?').append(request.getQueryString());
}
Finally, get the full URL as follows:
String fullURL = requestURL.toString();

Related

Android java split string via special character fails

I would like to attach a platform parameter to a url with ? if the url has no query string and using & if url has a query string
SO i have added the following
String api_url;
//costructor next to assign apiurl value
//method to extract url and process request
processData(){
String apiUrl = "";
String[] urlParams = this.api_url.split("\\?");
if (urlParams.length > 0){
apiUrl = this.api_url+"&platform="+tokenService.getToken(AppDetailsHelpers.AppSettingsKeys.PLATFORM);
}else {
apiUrl = this.api_url+"?platform="+tokenService.getToken(AppDetailsHelpers.AppSettingsKeys.PLATFORM);
}
}
The above always evaluates the urlParams to a an array even when a url doesnt contain the ?
Example for a url
http://test.com
is resolved with the above code as
http://test.com&platform=12
But i expected it to be as http://test.com?platform=12
I have tried adding
String[] urlParams = this.api_url.split("?");
But it throws an error of Dangling metacharacter. What am i missing out on this. Why does this fail.
This is expected behaviour for String#split. Running "http://test.com".split("\\?") returns an array with one element, "http://test.com". So, just update your condition to if(uriParams.length > 1).
You could also consider parsing your String to a Uri, as you may not need this check and could possibly instead use:
Uri.parse(api_url)
.buildUpon()
.appendQuery("platform", tokenService.getToken(AppSettingsKeys.PLATFORM))
.build().toString();

How to build an absolute URL from a relative URL using Java?

I have a relative url string, know host and protocol. How can I build an absolute url string?
Seems easy? Yes at first look, but until escaped characters coming. I have to build absolute url from 302 code http(s) response Location header.
lets consider an example
protocol: http
host: example.com
location: /path/path?param1=param1Data&param2= "
First I tried to build url string like:
Sting urlString = protocol+host+location
Constructor of URL class not escapes spaces and double quotes:
new URL(urlString)
Constructors of URI class fail with exception:
new URI(urlString)
URI.resolve method also fails with exception
Then I found URI can escape params in query string, but only with few constructors like for example:
URI uri = new URI("http", "example.com",
"/path/path", "param1=param1Data&param2= \"", null);
This constructor needs path and query be a separate arguments, but I have a relative URL, and it not split by path and query parts.
I could consider to check if relative URL contains "?" question sign and think everything before it is path, and everything after it is query, but what if relative url not contain path, but query only, and query contains "?" sign? Then this will not works because part of query will be considered as path.
Now I cannot get how to build absolute url from relative url.
These accepted answers seems just wrong:
how to get URL using relative path
Append relative URL to java.net.URL
Building an absolute URL from a relative URL in Java
It could be nice to consider scenario when relative url was given in relation to url with both host and some path part:
initial url http://example.com/...some path...
relative /home?...query here ...
It would be great to get java core solution, though it still possible to use a good lib.
The first ? indicates where the query string begins:
3.4. Query
[...] The query component is indicated by the first question mark (?) character and terminated by a number sign (#) character or by the end of the URI.
A simple approach (that won't handle fragments and assumes that the query string is always present) is as simple as:
String protocol = "http";
String host = "example.com";
String location = "/path/path?key1=value1&key2=value2";
String path = location.substring(0, location.indexOf("?"));
String query = location.substring(location.indexOf("?") + 1);
URI uri = new URI(protocol, host, path, query, null);
A better approach that can also handle fragments could be :
String protocol = "http";
String host = "example.com";
String location = "/path/path?key1=value1&key2=value2#fragment";
// Split the location without removing the delimiters
String[] parts = location.split("(?=\\?)|(?=#)");
String path = null;
String query = null;
String fragment = null;
// Iterate over the parts to find path, query and fragment
for (String part : parts) {
// The query string starts with ?
if (part.startsWith("?")) {
query = part.substring(1);
continue;
}
// The fragment starts with #
if (part.startsWith("#")) {
fragment = part.substring(1);
continue;
}
// Path is what's left
path = part;
}
URI uri = new URI(protocol, host, path, query, fragment);
The best way seems to be to create a URI object with the multi piece constructors, and then convert it to a URL like so:
URI uri = new URI("https", "sitename.domain.tld", "/path/goes/here", "param1=value&param2=otherValue");
URL url = uri.toURL();

unable to change URL by using getRequestDispatcher

The code i use for this is
request.getRequestDispatcher("jsp/caseconference.jsp").forward(request, response);
The code above works fine when i use send Redirect but in that part, I can't use request and response which gives an error.
Based on your comment above, I don't think you're getting an error, but rather, you want the last part of your url to go from LoginServlet to caseconference. You would have to create a url pattern for caseconference like this:
#WebServlet(
name = "LoginServlet",
description = "This is optional but helpful",
urlPatterns = "/caseconference"
)
public class LoginServlet extends HttpServlet {
....
}
Then create a variable in your doPost method to keep track of every path the user is on, for example:
String path = request.getServletPath();
Whenever the time comes for the user to redirect to roswellpark/caseconference set the path to caseconference:
path = "/caseconference";
Then, build your url like this, provided you have a folder in your directory named roswellpark or you make a url pattern for it:
String url = "roswellpark/" + path + ".jsp";
And lastly, forward the url using try/catch statements for best practice:
try{
request.getRequestDispatcher(url).forward(request,response);
}catch(Exception ex){
....
}

Get url parameters after # in java

I am trying to get the access_token from facebook. First I redirect to facebook using an url as the following
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=7316713919&redirect_uri=http://whomakescoffee.com:8080/app/welcome.jsf&scope=publish_stream
Then I have a listener that gets the url.
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request =
(HttpServletRequest) fc.getExternalContext().getRequest();
String url = request.getRequestURL().toString();
if (url.contains("access_token")) {
int indexOfEqualsSign = url.indexOf("=");
int indexOfAndSign = url.indexOf("&");
accessToken = url.substring(indexOfEqualsSign + 1, indexOfAndSign);
handleFacebookLogin(accessToken, fc);
}
But it never gets inside the if..
How do I retrieve the parameter when it comes after a # instead of a usual parameter after ?.
The url looks something like
http://benbiddington.wordpress.com/#access_token=
116122545078207|
2.1vGZASUSFMHeMVgQ_9P60Q__.3600.1272535200-500880518|
QXlU1XfJR1mMagHLPtaMjJzFZp4
The URL is incorrectly encoded. It's XML-escaped instead of URL-encoded. The # is a reserved character in URL's which represents the client-side fragment which is never sent back to the server side.
The URL should more look like this:
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=7316713919&redirect_uri=http%3a%2f%2fwhomakescoffee.com%3a8080%2fapp%2fwelcome.jsf%26scope%3dpublish_stream
You can use java.net.URLEncoder for this.

How can you get the original REQUEST_URI from within a Struts 2 Action reached via an apache ErrorDocument redirection?

How can you access the REQUEST_URI from within a Struts 2 Action? In perl/php/ruby it is readily available via ENV["REQUEST_URI"] and the like. In java it seems that the PageContext.getErrorData().getRequestURI() is what I'm looking for, but sadly, the PageContext does not appear to be defined within the action, either because the ErrorDocument redirection makes the request not look like an error, or because it is defined later.
A particular example
Given an apache fronted (mod_jk/ajp) struts 2 app on tomcat reached via the ErrorDocument 404 configuration in apache. With the following details:
-- Original request url (which triggers the 404) --
http://server/totally/bogus/path
-- http.conf --
ErrorDocument 404 /struts2app/lookup.action
-- struts action --
public String bogusUrlLookup() {
HttpServletRequest request = ServletActionContext.getRequest();
// contains /lookup.action as does request.getRequestURI();
String url = RequestUtils.getServletPath(request);
// PageContext is null, so I cannot reach ErrorData from it.
log.info("pageContext="+ServletActionContext.getPageContext());
// Not in the ENV
// Map env = System.getenv();
// Not in the ATTRIBUTES
// request.getAttributeNames()
// Not in HEADER
// request.getHeaderNames()
return ERROR;
}
Again all I need is the string "/totally/bogus/path", but in the above action the only url string that I can find is "/struts2app/lookup.action". I'm tied to the ErrorDocument because the totally/bogus/path is not likely to be within the namespace of my application because apache serves other non-tomcat resources.
request.getAttribute("javax.servlet.forward.request_uri")
baseUri = (String)request.getAttribute("struts.request_uri");
Use:
JkEnvVar REDIRECT_URL ""
in your httpd.conf file. Then use request.getAttribute("REDIRECT_URL"); to get the variable in your jsp/servlets.
If you don't wanna miss the query string part, this is better:
final String referrer = (String) request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
if(referrer != null) {
final String query = (String) request.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING);
if(query != null && query.length() > 0) {
url = referrer+ "?" + query;
}
else {
url = referrer;
}
// do something
}

Categories