4

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.

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

How would you do this with Tuckey's UrlRewriteFilter? I've asked it here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.