Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Request URLs in JSP

Tags:

I am writing a web application using Spring MVC. I am using annotations for the controllers, etc. Everything is working fine, except when it comes to actual links in the application (form actions, <a> tags, etc.) Current, I have this (obviously abbreviated):

//In the controller @RequestMapping(value="/admin/listPeople", method=RequestMethod.GET)  //In the JSP <a href="/admin/listPeople">Go to People List</a> 

When I directly enter the URL like "http://localhost:8080/MyApp/admin/listPeople", the page loads correctly. However, the link above does not work. It looses the application name "MyApp".

Does anyone know if there is a way to configure Spring to throw on the application name on there?

Let me know if you need to see any of my Spring configuration. I am using the standard dispatcher servlet with a view resolver, etc.

like image 565
Snowy Coder Girl Avatar asked Aug 07 '11 01:08

Snowy Coder Girl


Video Answer


2 Answers

You need to prepend context path to your links.

// somewhere on the top of your JSP <c:set var="contextPath" value="${pageContext.request.contextPath}"/>  ... <a href="${contextPath}/admin/listPeople">Go to People List</a> 
like image 76
craftsman Avatar answered Sep 26 '22 20:09

craftsman


The c:url tag will append the context path to your URL. For example:

<c:url value="/admin/listPeople"/> 

Alternately, I prefer to use relative URLs as much as possible in my Spring MVC apps as well. So if the page is at /MyApp/index, the link <a href="admin/listPeople"> will take me to the listPeople page.

This also works if you are deeper in the URL hierarchy. You can use the .. to traverse back up a level. So on the page at/MyApp/admin/people/aPerson, using <a href="../listPeople"> will like back to the list page

like image 31
Jason Gritman Avatar answered Sep 25 '22 20:09

Jason Gritman