get current url of context - java

I want to get the current URL of my website.
Not the context, not the ports, not the scheme or the protocol. Only the relative url.
For example:
https://www.myurl.com/context/relative/url/site.mvc
I want to have:
/relative/url/site.mvc
${pageContext.request.contextPath} gives me: /context/
${pageContext.request.requestURL} gives me https://www.myurl.com/context/WEB-INF/tiles/relative/url/site/center.jsp
Thats where the site is located in my directory.
But I want the relative path of the website... without Javascript!

So, you want the base URL? You can get it in a servlet as follows:
String url = request.getRequestURL().toString();
String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/";
// ...
Or in a JSP, as , with little help of JSTL:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />
...
<head>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" />
</head>
Note that this does not include the port number when it's already the default port number, such as 80. The java.net.URL doesn't take this into account.
See also:
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
jsp file:
request.getAttribute("javax.servlet.forward.request_uri")

Thank you #jmail.
Your statement brought me on the right track. But I did not want the base url, but the solution would be this:
<c:set var="currentUrl" value="${pageContext.request.request.getAttribute('javax.servlet.forward.request_uri')}"/>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<c:forEach items="${paramValues}" var="paramItem">
<c:set var="urlParams" value="${urlParams}&${paramItem.key}=${paramItem.value[0]}"/>
</c:forEach>
<c:set var="urlParams" value="${fn:substring(urlParams, 1, fn:length(urlParams))}" />
<c:set var="relativeUrl" value="${fn:substring(currentUrl, fn:length(contextPath), fn:length(currentUrl))}?${urlParams}" />
You forgot the parameters, and your version extracted the base, instead of the relative path!

Related

How to inspect JSP request URL for String

I have the following processor.jsp file:
<%
response.sendRedirect("http://buzz.example.com");
%>
I want to change it so that it inspects the HTTP request URL for the presence of the word "fizz" and, if it exists, redirect the user to http://fizz.example.org instead.
So something like:
<%
String reqUrl = request.getURL().toLowerCase();
String token = null;
if(reqUrl.contains("fizz")) {
token = "fizz";
} else {
token = "buzz";
}
String respUrl = "http://%%%TOKEN%%%.example.com".replace("%%%TOKEN%%%", token);
response.sendRedirect(respUrl);
%>
However this doesn't work. Any ideas on what I should be using instead of request, or if I'm doing anything else wrong?
Always try to avoid Scriplet instead use JavaServer Pages Standard Tag Library and Expression Language that is more easy to use and less error prone.
Sample code using JSTL <c:choose> that is equivalent to Java switch case.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
...
<c:set var="defaultURL" value="xyz"/>
<c:choose>
<c:when test="${fn:containsIgnoreCase(request.getRequestURI(), 'fizz')}">
<c:redirect url="http://fizz.example.com" />
</c:when>
<c:when test="${fn:containsIgnoreCase(request.getRequestURI(), 'buzz')}">
<c:redirect url="http://buzz.example.com" />
</c:when>
<c:otherwise>
<c:redirect url="http://${defaultURL}.example.com" />
</c:otherwise>
</c:choose>
Read more about All Tags | Functions and Oracle Tutorial - Using JSTL

Can we redirect one jsp page to another jsp page

I want to open a jsp page without accessing my servlete code. i.e. I neither have to input my url in (action="url") my jsp code nor have to access my Servlete code.
<form id="main" method="post" name="main" action="dpRegPost" onsubmit="return validate();">
Can anyone help me in this?
You can add javascript to your jsp file
<script type="text/javascript">
window.location.href = "www.google.com";
</script>
or using jsp
<%
response.sendRedirect("www.google.com");
%>
You can also try this
<jsp:forward page = "abc.jsp" />
Use jstl taglibrary in your current jsp page.Make available the taglibrary using below code
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Use Following code in jsp to redirect
<c:redirect url="/xxx.jsp"/>
Try this:
<form id="main" method="post" name="main" action="" onsubmit="redirect(this);">
<input type="submit" name="submit"/>
</form>
function redirect(elem){
elem.setAttribute("action","somepage.jsp");
elem.submit();
}
You can also call page directly with:
<jsp:redirect page="xyz.jsp" />
use the following code to redirect on another page in js...
$('#abc_id').click(function() {
updateSubContent("abc.jsp");
});

Composing URL in JSP

Lets say my current URL is:
/app.jsp?filter=10&sort=name.
I have a pagination component in JSP which should contain links like:
/app.jsp?filter=10&sort=name&page=xxx.
How do I create valid URLs in JSP by adding new parameters to current URL? I dont want use Java code in JSP, nor end up with URLs like:
/app.jsp?filter=10&sort=name&?&page=xxx, or /app.jsp?&page=xxx, etc.
Ok, I found answer. First problem is that I have to preserve all current parameters in URL and change only page parameter. To do this I have to iterate over all current parameters and add those I don't want to change to URL. Then I added parameters I want to either change or add. So I ended up with solution like this:
<c:url var="nextUrl" value="">
<c:forEach items="${param}" var="entry">
<c:if test="${entry.key != 'page'}">
<c:param name="${entry.key}" value="${entry.value}" />
</c:if>
</c:forEach>
<c:param name="page" value="${some calculation}" />
</c:url>
This will create nice and clean URL independent of page parameter in request. Bonus to this approach is that URL can be just anything.
<c:url var="myURL" value="/app.jsp">
<c:param name="filter" value="10"/>
<c:param name="sort" value="name"/>
</c:url>
To show the url you can do something like this
Your URL Text
To construct a new URL based on the current URL, you first need to get the current URL from the request object. To access the request object in a JSP use pageContext implicit object defined by the JSP expression language:
${pageContext.request.requestURL}
Here is the simple example of constructing URL in a JSP page:
test.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Testing URL construction</h1>
<c:choose>
<c:when test="${pageContext.request.queryString != null}">
Go to page xxx
</c:when>
<c:otherwise>
Go to page xxx
</c:otherwise>
</c:choose>
</body>
</html>
This solution allows you to construct URLs depending on whether the current URL already contains some query string or not. So you respectively append either
?${pageContext.request.queryString}&page=xxx
or just
?page=xxx
to the current URL.
JSTL and the Expression Language were used to implement checking for a query string. And we used getRequestURL() method to obtain the current URL.

how to get the base url from jsp request object?

How to get the base url from the jsp request object?
http://localhost:8080/SOMETHING/index.jsp, but I want the part till index.jsp, how is it possible in jsp?
So, you want the base URL? You can get it in a servlet as follows:
String url = request.getRequestURL().toString();
String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/";
// ...
Or in a JSP, as <base>, with little help of JSTL:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />
...
<head>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" />
</head>
Note that this does not include the port number when it's already the default port number, such as 80. The java.net.URL doesn't take this into account.
See also:
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
JSP variant of Bozho's answer:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="baseURL" value="${req.scheme}://${req.serverName}:${req.serverPort}${req.contextPath}" />
new URL(request.getScheme(),
request.getServerName(),
request.getServerPort(),
request.getContextPath());
There is one major flaw in #BalusC accepted answer though. Substring should start from 0 and not 1. Instead of
<base href="${fn:replace(req.requestURL, fn:substring(uri, 1, fn:length(uri)), req.contextPath)}" />
it should be
<base href="${fn:replace(req.requestURL, fn:substring(uri, 0, fn:length(uri)), req.contextPath)}" />
With 1 you get double forward slash: http://localhost:8080//appcontext/
With 0 you get, http://localhost:21080/appcontext/
In my application, request.getSession(false) always returned null when it was ending in double slash!!!
Instead of doing all of that, just do this:
request.getServerName().toString()
just use isSecure()
{<%=request.isSecure()?"https":"http:"%>}

Why my included JSP file won't get processed correctly?

I am trying (and learning) to build a java web framework, and in the process of developing its' code generator based on the content of the database. In the view making process, I stumble in a difficulty, which I don't know how to solve it.
Firstly, I want all the pages to be created using the following index.jsp :
<body>
<%# include file="header.jsp" %>
<hr/>
<%# include file="body.jsp" %>
<hr/>
<%# include file="footer.jsp" %>
</body>
And, in the body.jsp, I want it to be like this :
<jsp:include page="${application_modul}" %>
Where application_modul is an attribute defined in its' controller this way :
request.setAttribute("application_modul","user_account\\view_user_account.jsp");
It can find the file correctly, but the processed jsp is not what I expected. Here :
<c:forEach items="[application.models.UserAccountModel#18a49e0, application.models.UserAccountModel#1f82982]" var="item" varStatus="status" >
<tr>
....
You can see the items attribute of jstl forEach, got its variable name (toString())...
Any Idea what the problem is????
I hope I describe my problem correctly
Many thanks!
PS :
I already create a quick fix for this, but not what I want it though. In the generated view_user_account.jsp, I do it like this :
<body>
<%# include file="header.jsp" %>
<hr/>
<c:forEach items="${row}" var="item" varStatus="status" >
<tr>
....
<hr/>
<%# include file="footer.jsp" %>
</body>
You can see that I create the whole file here...
EDITED:
PS : ${row} is an ArrayList populated with data from certain table
So, to summarize your problem in a single sentence, JSTL tags are not been parsed and they end up plain in generated HTML output?
You need to declare JSTL taglib in top of the JSP page where you're using JSTL tags to get them to run. For the JSTL core taglib, that'll be
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
I am not sure but, Try this...
index.jsp
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />

Categories