简体   繁体   中英

${pageContext.request.contextPath} Working locally, but not remotely

I am in a strange situation where I found I currently have to use two different path-naming conventions depending on whether I am testing on localhost or my app is deployed to my domain.

Locally when I run my app, I access it here: localhost:8080/MyApp/welcome and on my domain, here: mydomain.com/welcome

On this welcome page (a JSP), I want to link to another page, say /welcome/foobar. If my link is of this style (note the pageContext prefix):

<form action="${pageContext.request.contextPath}/welcome/foobar ... >
    <button type="submit">Admin Login</button>
</form> 

Then locally, I will correctly be directed to localhost:8080/MyApp/welcome/foobar . The kicker is, that when I deploy and click this link on my domain, I am directed incorrectly to http://welcome/foobar/ . I also receive the opposite result (incorrect locally, correct remotely) if I use a simple <form action="/welcome/foobar" ... > path.

Does anyone have a solution that would eliminate this mismatch? Also, I do not fully understand why this is happening, so bonus points to anyone who would also give me an explanation.

The first thing is to understand what is a contextPath and why it's used.

Let's take the example of your local URL.. localhost:8080/MyApp/welcome

What all information is available here..

hostName = localhost

port = 8080

contextPath = MyApp

Now take your real environment URL mydomain.com/welcome

hostName = mydomain.com

port = default ie 80

contextPath = /

So for your domain, the contextPath is just / which is how generally configured to shorten URL. The idea behind using the contextPath is generate relative LINKS for your jsp pages. It should better be used with <anchor> tags

If you just want a link to another page, you should use <a href="${pageContext.request.contextPath}/welcome/foobar">Submit </a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM