Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide .jsp extension in JSP project using servlet mapping

I am writing an application in JSP, and I need to remove the ".jsp" extension from the URL. For example, I need:

http://example.com/search.jsp?q=stackoverflow

To be:

http://example.com/search?q=stackoverflow

I know that this can be done using the ".htaccess" file, but I need some other way. I have tried the following code:

<servlet-mapping>
   <servlet-name>jsp</servlet-name>
   <url-pattern>*.</url-pattern>
</servlet-mapping>

However, this did not work. Does anyone have some suggestions for ways to accomplish this? Thanks in advance for any help.

like image 611
ramesh Avatar asked Dec 16 '22 10:12

ramesh


1 Answers

With a servlet mapping you need to specify each JSP individually like follows:

<servlet>
    <servlet-name>search</servlet-name>
    <jsp-file>/search.jsp</jsp-file>
</servlet>
<servlet-mapping>
    <servlet-name>search</servlet-name>
    <url-pattern>/search</url-pattern>
</servlet-mapping>

It's easier if all those JSPs are in a common path. E.g. /app/*.

<servlet>
    <servlet-name>app</servlet-name>
    <servlet-class>com.example.FriendlyURLServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>app</servlet-name>
    <url-pattern>/app/*</url-pattern>
</servlet-mapping>

with

request.getRequestDispatcher("/WEB-INF" + request.getPathInfo() + ".jsp").forward(request, response);

This assumes the JSPs to be in /WEB-INF folder so that they cannot be requested directly. This will show /WEB-INF/search.jsp on http://example.com/app/search.

Alternatively, you can use Tuckey's URLRewriteFilter. It's much similar to Apache HTTPD's mod_rewrite.

like image 67
BalusC Avatar answered Dec 18 '22 23:12

BalusC