Get current URL in Webapplication - java

I am in process to capture Current URL as its being displayed in the browser's address bar in my JSP page and have few options to get it done.
Using javax.servlet.include.request_uri and other defined in Servlet 2.4 specification.I refer this thread to get details about it java-httpservletrequest-get-url-in-browsers-url-bar.
In my current application, we are going to put web-server in front of our application server as than it seems that those values will be of not any use.
I have another way to take help of javascript's document.URL but i am not sure how reliable it is going to be.
I need to get the details about the location of the user and if I can use getRequestURI(), it will return me something like www.abc.com/abc/search.jsp.
In short, all I want to capture the URL being there in the address bar of the browser and save it in a hidden field of my JSP page.
I am not sure what is the best way to achieve this.

In Java, you can do this:
public static String getCurrentUrl(HttpServletRequest request){
URL url = new URL(request.getRequestURL().toString())
String host = url.getHost();
String userInfo = url.getUserInfo();
String scheme = url.getProtocol();
String port = url.getPort();
String path = request.getAttribute("javax.servlet.forward.request_uri");
String query = request.getAttribute("javax.servlet.forward.query_string");
URI uri = new URI(scheme,userInfo,host,port,path,query,null)
return uri.toString();
}

If you want a javascript solution, you can use window.document.location object and its properties:
console.log(window.document.location.protocol);
http:
console.log(window.document.location.host);
stackoverflow.com
console.log(window.document.location.port);
console.log(window.document.location.href);
http://stackoverflow.com/questions/10845606/get-current-url-in-webapplication
console.log(window.document.location.pathname);
/questions/10845606/get-current-url-in-webapplication
You can understand other parameters reading this article at MDN.

You can create a hidden field in your form
<input type="hidden" id="myurl" name="myurl"/>
then write a javascript
<script type="text/javascript">
document.getElementById('myurl').value = window.location.href
</script>
is that help?

Related

In Spring Boot, can we pass anchor tag, as a variable, through URL like #PathVariable or #RequestParam?

I would like to use URL http://localhost:8080/blog#section & obtain #section as a variable in getBlog() method.
// localhost:8080/blog#section
#GetMapping("/blog/{section}")
public String getBlog(Model model, #PathVariable("section") String section){
return "blog" + section; // localhost:8080/blog#section
}
The #section part is never sent to server (see this answer),so what you are demanding is impossible.
In fact #section is used for browser to locate the content of a web page, it's not used for server to decide which content to return.
What you are demanding can be easyily achieved with a query like localhost:8080/blog?section=? or a url path like localhost:8080/blog/section

Thymeleaf context URL processing - how to add language code to context-relative URLs (Spring + Thymeleaf)

I have written request filter and locale resolver for getting language code from URL. (for example: DOMAIN/en/, DOMAIN/cs/)
However, I don't know how to change programmatically the context path that Thymeleaf uses for its context-relative URLs (#{/css/main.css}).
For example, if on page with address "DOMAIN/en/test/" is following code
<a th:href="#{/test2/}">TEST 2</a>
it points at
DOMAIN/test2/
instead of
DOMAIN/en/test2/
I thought it would be good to create some filter that edits the URL before it goes to Thymeleaf templates, but I don't have any idea how.
Do you have any ideas how to solve it?
I've found solution that suits my expectations.
I just wanted to insert language code after context path (example.com/CONTEXT_PATH/CONTROLLER -> example.com/CONTEXT_PATH/LANGUAGE_CODE/CONTROLLER) for Thymeleaf templates, so I can still use Thymeleaf's url expression #{/controller}.
I have url filter that removes language code and adds it to request's attributes, so I have just edited the response's encodeURL method and it works as I wanted:
getServletContext().getRequestDispatcher(newUrl).forward(request, new HttpServletResponseWrapper(response) {
#Override
public String encodeURL(String url) {
String contextPath = getServletContext().getContextPath();
if (url.startsWith(contextPath))
url = new StringBuilder(url).insert(contextPath.length(), "/" + getLocale().getLanguage()).toString();
return super.encodeURL(url);
}
});
Anyway, thanks for your answers! :)
One solution is to put urls in message resource files:
<a th:href="#{#{orders.details.localized_url}(id=${order.id})}">
as described in: http://www.thymeleaf.org/doc/articles/standardurlsyntax.html
Or return appropriate template view for example:
#RequestMapping("/localized/**")
public String getTemplateView(HttpServletRequest request) {
String path = request.getRequestURI();
//path = /localized/en/mypage
return mypage_en.html;// or relative location in the configured folder
}
I like the first one better

How to add a parameter to a URL in GWT?

I have a Java/GWT application. In that there is a list of items. If I click on any item title then that item is opened with full description.
I am using Anchor for the item title, so what I want is when user clicks on item title then in the URL the id of that item is appended to the current URL.
For example, this is my URL:
"http://127.0.0.1:8888/MyApp.html?gwt.codesvr=127.0.0.1:9997#listItem?list"
and I have to append id to the end of the URL like:
"http://127.0.0.1:8888/MyApp.html?gwt.codesvr=127.0.0.1:9997#listItem?list&itemId=55"
Using Window.Location should do your trick : see the doc here
Something like this :
String url = Window.Location.getHref();
url = url + "&itemId=" + itemId;
Window.Location.replace(url);
Although of course, as Crollster pointed out, you should insert your url parameter before the # sign. Give more details on what you're looking for exactly (why do you have to add the parameter manually, does the page have to reload ...)
you can use redirect command in order to add this parameter
response.sendRedirect(your url + itemId=55);
Then you can extract this variable.
I hope this will help.
You can try with javascript coding.When the user clicks on link, get this URL and appends your id to it and reconstruct the URL.
You see that # in the URL? Thats an anchor - you will need your parameter to be added before that, so it looks like this:
http://127.0.0.1:8888/MyApp.html?gwt.codesvr=127.0.0.1:9997&itemId=55#listItem?list
HTH
URIBuilder of Apache HttpComponents offers a convenient method to add parameters and will deal with existing query parameters and anchors.

How do I reverse route a static file?

At first I had this link to a twitter icon:
#{'/public/images/twitter-icon.png'/}
But now I want to show a Twitter-, Facebook- or LinkedIn icon depending on type. So, I created a FastTag that takes the type as a parameter and the code looks like this:
In the view:
#{myApp.icon contact.type/}
FastTag Java Code:
String type = (String) args.get("arg");
out.print("/public/images/" + type + "-icon.png");
It works fine. But, on our build server we run the app with a prefix on the uri like this
http://ourdomain.com/appname/...
Obviously /public/images... won't work here. So I figured I have to ask the Router for the proper address. I've tried the following with no success:
Router.reverse("/public/images/" + type + "-icon.png");
Router.reverse("/public/");
Router.reverse("staticDir:public");
All three result in a NoRouteFoundException. How can I get the correct route for my icons?
In the routes file I have the default route for static files
GET /public/ staticDir:public
I believe this is what you want:
String imageUrl = Router.reverse(VirtualFile.fromRelativePath("public/images/" + type + "-icon.png"));
Router.reverse be used generate URL form one action!
maybe you can define a route which include your app name and route one action eg:
GET /appname/public/ TestController.test
now,you can use
Router.reverse("TestController.test")
get the URL.
I think it's better to do something like:
GET /img/ staticDir:public/images
And in the template just:
out.print("/img/" + type + "-icon.png");

Liferay request current page name

What is the smartest way to get current page name where request came from? By page I mean the real page name that contains current portlet.
By using something like that you should be ok
ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
String title = themeDisplay.getLayout().getName(themeDisplay.getLocale());
just be aware,themeDisplay.getLocale() could result different char encoding format, use with caution, may cause certain string functions to fail

Categories

Resources