Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context path with url-pattern redirect in spring

I'm having a bit of a puzzle with paths and urls on a tomcat server, let me explain:

My tomcat webapp directory is: /server

I have deployed a spring application in directory /server/myapp/subfolder

This means my context path /server/myapp

My servlet has an url-pattern of /subfolder/*

My servlet can be reached at url http://server.com/myapp/subfolder/

In a many of my spring controllers i return a redirect:

return "redirect:/item/list";

This redirects the visitor to http://server.com/myapp/item/list

This of course results in a 404 cause the right url is: http://server.com/myapp/subfolder/item/list

This can easily be solved by just putting everything is a separate webapp or simply removing the url-pattern. But both aren't possible because a separate webapp means a different class-loader (causes problem with other systems) and url-pattern like / will conflict with other applications running on the server.

I can change my redirect to "redirect:/subfolder/item/list", that will fix the redirect.

Is there maybe a better solution so that i don't have to manually add "subfolder/" everywhere the contextpath is used?

like image 882
TinusSky Avatar asked Dec 02 '22 15:12

TinusSky


2 Answers

I know this is an old question, but if anyone is looking for the current answer, RedirectView (at least in the most recent 5.0.9 version) has a contextRelative boolean parameter that is false by default. Setting that to true makes the redirect context relative. For example:

return new RedirectView("/account", true);

Reference: docs

like image 167
Ethan Wood Avatar answered Dec 04 '22 03:12

Ethan Wood


Rather than hard wiring your apps context path, you can get it from the HttpServletRequest.getContextPath().

like image 22
thedoctor Avatar answered Dec 04 '22 04:12

thedoctor