danst_18
danst_18

Reputation: 497

Map controller to an absolute path in Spring MVC

I have a simple webapp with a search box visible from all JSP pages.

My controller looks like this:

@RequestMapping(value = "/search", method = RequestMethod.GET)
public String search(Map<String, Object> map, HttpServletRequest request) {
    /*...*/
    return "searchresult";
}

In my JSP I use: <form action="search" method="GET"> in order to make the request. So, for example, if I make a request from /myproject/index this works perfect and the resulting URL is /myproject/search. But now, if I do the same but from another level, e.g. /myproject/index/level2, the resulting URL is /myproject/index/search and doesn't work since it doesn't find a controller with that mapping.

What I want to do is to map the controller to an absolute path so, in the second case the resulting URL would be /myproject/search and not /myproject/index/search/

In my web.xml I have this:

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Upvotes: 0

Views: 2207

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279990

Use EL

<form action="${pageContext.request.contextPath}/search" method="GET" />

The EL expression will resolve to your application's context path. You then append your full path to it.

Alternatively, the core tag lib provides the url tag.

<form action="<c:url value="/search" />" method="GET" />

That does the same thing, more or less.

Spring also provides its own url tag which you can look into.

Upvotes: 3

Related Questions