Tomcat is not adding trailing slash to web app's context - java

I'd like to have Tomcat automatically add a trailing slash to my app's context if the url is entered without it.
When I test with Jetty, it automatically adds the trailing slash to my app's context, but Tomcat doesn't do this.
I'm uncertain what the context will be named once deployed, as I'm handing the WAR off to someone else, so any resource references in HTML is all relative. Is there any way to have Tomcat automatically redirect to the same context with a trailing slash added?
Currently Using Tomcat 7 with Spring 3.

It's an old post, but as of Tomcat 7.0.67, you need to add the following attribute to your context.xml file:
<Context mapperContextRootRedirectEnabled="true">...</Context>
As per the 7.0.67 changelog:
Move the functionality that provides redirects for context roots and directories where a trailing / is added from the Mapper to the DefaultServlet. This enables such requests to be processed by any configured Valves and Filters before the redirect is made. This behaviour is configurable via the mapperContextRootRedirectEnabled and mapperDirectoryRedirectEnabled attributes of the Context which may be used to restore the previous behaviour.
And in the Tomcat context documentation:
mapperContextRootRedirectEnabled: If enabled, requests for a web application context root will be redirected (adding a trailing slash) if necessary by the Mapper rather than the default Servlet. This is more efficient but has the side effect of confirming that the context path exists. If not specified, the default value of false is used.

It seems that your application's web.xml has a mapping to "/*". A servlet-mapping to "/*" causes tomcat to pass the request as-is to the web application (i.e. does not redirect).
To properly redirect, you must change the "/*" mapping to just "/", the latter means the default servlet.

Tomcat adds a trailing slash automatically. Just test it with the example application supplied with Tomcat..
If - due to some special configuration - it does not, I'd write a Filter that examines the query string and redirects as needed by the application. Many times this is needed anyways (doing http->https redirections, etc.)

Have you tried playing with URL Rewrite on Tomcat?
This might help: http://code.google.com/p/urlrewritefilter/
If that does not help, take a look at this: URL rewrite in tomcat web.xml

Pat's excellent answer helped me dig up a few more details on this. It seems this is related to some quirks in some versions of Tomcat (Tomcat 7 at 7.0.67+, and Tomcat 8 between 8.29 and 8.37) having to do with session cookies and URL redirection.
The bottom line seems to be that if the java server creates path-specific session cookies with a slash at the end (like "/app_name/"), then the server must also do an automatic initial redirect (/app_name --> /app_name/) ... otherwise, the session cookie will not get sent with the request, and it will never look to the server like you have a valid session. The may cause a redirect loop from the app to the authentication.
There are configurations in Tomcat that control both behaviors, but as far as I can tell, they were essentially out-of-sync in these versions, such that one might get the cookie with the trailing slash, without getting the redirect. There are several related issues/changes in the Tomcat changelog:
https://tomcat.apache.org/tomcat-8.0-doc/changelog.html
As Pat has already noted, this is resolved by adding this attribute to your app's Context element:
<Context mapperContextRootRedirectEnabled="true">

Related

404 with response.sendRedirect

I am using spring security login mechanism for my application and tested everything.Things were working fine.I have the following use case
If customer is not logged in , application will redirect customer to the login page.
On successful login, application will redirect customer back to same page from where they were redirected to the login page
this is the Java code used to redirect user to his original location
final SavedRequest savedRequest = this.requestCache.getRequest(request, response);
targetUrl = savedRequest.getRedirectUrl();
getRedirectStrategy().sendRedirect(request, response, targetUrl);
RedirectionStrategy being used here is DefaultRedirectStrategy, things were working fine. Application is now deployed on the Pre Production server and now this seems not working and I am getting 404 error.
When customer is being redirected to the home page,targetUrl is coming out as "/", I have a Spring controller named with this mapping
#RequestMapping("/")
public class HomePageController{ // home page code }
my application's current Pre-Prod urs is prepd-www.mysite.com so when sendredirect come in to action, webpage URL is getting changed to prepd-www.mysite.com/prepd-www.mysite.com
I am not sure what is causing this issue. is it because of the proxy server settings ?
Can any one suggest me about the possible root cause of this issue?
I have already tried it on all local machines and well on our QA but everything is working perfectly fine.
Current setup for the environment where this is happening is
We have 4 app server
We have one load balancer which is redirecting traffic to one of the app server.
Just a wild guess since you could not give the reverse proxy configuration, nor the exact URL used in pre prod and in developpement.
You say you are using DefaultRedirectStrategy from Spring security. This strategy has an option (contextRelative) that prepends the ServletContext path to the URL. If in your developpement system you were using the root context, that is if you were accessing home page at (for example) : http://localhost:8080/ the serlet context was empty.
But if now in preprod, the servlet context is no longer root but is say /myApp once translated by apache reverse proxy, when you redirect you get an URL of /myApp/myApp that could be translated back to what you gave.
You could try to control whether you have contextRelative as true in DefaultRedirectStrategy and if yes if you can set if to false and also control if you redirect to absolute or relative URLs.
If you are using apache in front check rewrite rule and redirect rules of apache config. Best way would be to ssh tunnel directly to application server(by skipping apache) and test. If it's working that means your application config is fine and it needs to be fixed in apache.
Are you using in preproduction tomcat or another application server?, normally if your war is calling foo and your commit to tomcat, the path for this war is
http://localhost:8080/foo/
So if you are using servlet you need specify in your web.xml that the main path is foo/*

Tomcat adds context-path to urls

In my application every link generated is surrounded by response.ecodeURL. On some servers encodeURL adds the context-path to the URL.
The application is named "appl". Creating a link /a/b/c.jsp creates on DEV-system the url /a/b/c.jsp, on Prod it creates /appl/a/b/c.jsp
The tomcat is behind an Apache Webserver which connects via ajp, not sure if thats a relevant fact.
EDIT:
The Webserver isn't relevant. I tried going directly on port 8080 and the same happend again.
<c:url> always pre-pends the context path to URLs: this is standard practice and should always be done. If you are using <c:url> then you shouldn't add your own prefix. Also note that <c:url> runs the URL through HttpServletResponse.encodeURL for you. That method adds URL-based session-tracking information (e.g. the ";jsessionid" path parameter) if appropriate.
You should always add the context prefix to all URLs, whether you use something like <c:url> or do it yourself. You just shouldn't do both. When you use the ROOT context, the context path with be "" (i.e. empty string) and nothing will be pre-pended to your URLs.

Spring security: using relative path

I have an application with name test.war.
Because of Apache installed on my server I have to use another port number for Tomcat applications so after deployment this application available at domain.com:8080/test/.
I decided to create a subdomain in order to remove that ugly 8080 from url, so I setted up the server like described here. So now test.domain.com reffers to domain.com:8080/test/.
Everything seems fine except of one problem - because my application is not ROOT.war and I am using spring:url function every url in the application is translated to /test/bla-bla. So I removed that function. But still have a problem with spring security because it still translates an urls relative to app name i.e. /test/bla-bla.
How can I solve that problem?
Thank you
UPD: I don't want to deploy it as a ROOT application because I have two or three such applications and I wanted to create a subdomain for each one of them
Spring Security doesn't "translate" URLs. In fact this isn't specific to Spring Security. You'll run into similar issues with any application which does redirects. If you want to hide the context paths of applications which are behind a proxy, then you need to rewrite the URLs at the proxy.
I'd recommend you read the Tomcat Generic Proxy Howto and the section on URL rewriting in particular, as it specifically addresses this issue.

Deploying Struts2 Application without ContextPath

I've got a struts2 application running under a contextpath "/path" on my local tomcat without problems. When I deploy it on a webserver (using a proxy to redirect from "http://www.domain.com" to "myserver:8080/path/") Struts does all kinds of strange things.
First, it includes the context in -tags. That can be turned off by an attribute. But sadly, it also includes the path in the action attributes of my forms, so a login form points to "http://www.domain.com/path/login.action" instead of "http://www.domain.com/login.action" ...
Is there a possibility so somehow change the default context that is added here or turn this off for forms? (I'd like to keep the -tags, only way round seems to be to use default HTML forms.) Thanks in advance!
I found that others also had the problem, but the framework makers don't seem to think that this is an issue. My solutions:
use includeContext="false" in all s:url-tags
instead of the s:form tag, use a usual form, set the action to "actionname.action" and include a simple table with tablerows () for each field. You still can use s:textfield and such.
sadly HTTP sessions won't work anymore as they get set for the path "/path" (the ApplicationPath). This is due to the cookie that saves the JSESSIONID being set to /path. This means that your visitors will only get session variables stored when they're at http://www.domain.com/path/login.action and that those will be lost when they get redirected back to http://www.domain.com/interestingstuff.action ... my solution is a hack that requires setting the JSESSIONID cookie clientside via JavaScript as described here: Struts2: Session Problem (after reverse proxy)
Hope this helps someone ... if you find nicer solutions, please let me know. :-)
Though am answering very late to this question, but I reached this page recently when I was facing the same problem.
The application that I was working upon was appending the context-root viz. 'myContextRoot' to my url on localhost and it was working perfectly there. For eg., as mentioned above the action 'myAction' was becoming
http://localhost:8050/myContextRoot/myAction.action
But the moment I deployed it on a server, it stopped working, then after searching like hell, I found a solution for me. I am deploying an EAR file on glassfish and there we have a file application.xml. In application.xml I had a tag 'context-root' whose value was 'myContextRoot' which I changed to '/' and after that I got my url as on localhost and
Hope it may help :)

Changing Tomcat web application context

I have a web application, which was designed and always worked under root context ("/"). So all css, js and links started with / (for example /css/style.css). Now I need to move this web application to some different context (let's say /app1). It is easy to change server.xml configuration file and bring up web application in new context app1 using [Context path=""] item. But web pages are broken because all links are now incorrect. They point to old root context /css/style.css instead of new app1 context.
Is there any magic way to fix this problem without fixing each link by prefixing with some "context" variable?
Used server - Tomcat 5. Application is written with Java and uses JSP, Struts2, Spring and UrlRewrite filter. More interesting is to hear real experience in fighting with such problems that theoretical debates.
Thank you.
P.S. I do not see how UrlRewrite filter can help me because it will work only in app1 context. So requests to links like /css/style.css will not be passed to it.
If you use URL rewriting to redirect ROOT to your application, won't that eliminate the ability to have a an application in ROOT? If so, what is gained by switching the context?
I think the general way to link resources is to either append a "context" variable and make the link absolute: ${pagecontext.request.contextpath}/css/style.css or just make the link relative: css/style.css
Unless you have specific reasons for being unable to modify the code, I would do a search/replace on the links and be done with it. You should have no more than three or four expressions to find, /css, /images, /javascript, etc.
You should always create urls via url re-writing, not only so that session info can be added to the url, if required, but also so that the context path can be added. You should create all urls as absolutely paths from the top of the application and then let url-rewriting handle adding the context-path to the front, as appropriate.
<c:url value="/css/site.css"/>
That will render /<context-path>/css/site.css or /<context-path>/css/site.css;jsessionid=134345434543 into a jsp file if they don't have cookies enabled. You can also use the c:url tag to render the url into a variable and then use that variable multiple times throughout your document. Just add a var="x" attribute to the tag and then ${x} will render the url into your doc. If you aren't using jsp to render your output, you'll need to find the appropriate mechanism for your view layer, but they will all have one. If you are rendering a url in java code, just take a look at the source code to the c:url tag and you'll see how it is done.
The one awkwardness is that CSS files (and js files) aren't processed, so urls in css and js files need to be relative paths or they will break whenever you change the context path. Most js already uses relative paths since library maintainers don't know what path you are going to install their library to. CSS backround images, on the other hand, are often specified as absolute urls, since the same CSS file may be included into html files at different levels of a file hierarchy. There is no easy fix for this that I am aware of other than to create appropriate symlinks such that the relative url always works or else serve up the problem CSS files via a JSP so that the urls can be rewritten as appropriate. I'm sure there are probably filters or apache modules you can run which will do the url replacement, but then you've still got to manually update your filter/module whenever you deploy to a new context path.

Categories