views:

1708

answers:

6

I have a JSP web server, with pages that all end with the .jsp extension.

How can I hide it in my web server urls without resorting to non-java tricks (e.g., apache rewrite)?

For example: instead of typing http://www.sample.com/search.jsp?xxx the user would just type http://www.sample.com/search?xxx

+3  A: 
RewriteEngine On

RewriteRule ^([0-9a-zA-Z]+)$  $1.jsp

In your .htaccess should rewrite all URLs to .jsp. So search.jsp will just be search, as you described.

Logan Serman
It's not the answer he is looking for but I think its the simplest and therefore the best approach. +1
bmatthews68
A: 

I am not a JSP expert but I think you can define URL-mappings in web.xml to provide aliases for your servlets and jsps.

Rahul
+7  A: 

You can create a servlet mapping like this:

<servlet-mapping>
   <servlet-name>MappingServlet</servlet-name>
   <url-pattern>path/*</url-pattern>
 </servlet-mapping>

The url-pattern must be edited to suit your needs. You need of course to create the servlet in order to map the url to the actual jsp. This technique is used by most of the MVC frameworks.

kgiannakakis
Replace the URL-pattern tag above with a jsp-file tag and include in it's body the actual nice URL that you want...There is no need for apache URL rewriting - the servlet spec supports exactly what you want . The proper approach is what I jyst described...
mP
+1  A: 

Map the jsp as a servlet but use a jsp-file tag instead of url-mapping tag.

myjsp /myjsp.jsp

mP
+1  A: 

UrlRewrite is a good flexible Java-based framework-independent solution.

This is better than a Servlet mapping in web.xml, because that is too limited in what you can do, and better than an Apache based solution because it is part of your web application so you do not need to put Apache in front of your application server.

Peter Hilton
A: 

If you opt for the Apache rewrite rule, rather than the application server mapping/filter (as I did) you might also want to do more than just look for "^([0-9a-zA-Z]+)$"

You may want to confirm the url is not a directory or a file that does exist if apache is fronting and serving the non-jsp resources. And confirm that the JSP exists, and do a pass thru rather than redirect, and append any possible query string.

RewriteCond %{REQUEST_URI} !^/.*\.(jsp)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME}.jsp -f
RewriteRule ^(.+)$ /$1.jsp [PT,QSA,L]

And to make sure that users only see this via /search, not /search.jsp then you want to rewrite the reverse as well

RewriteRule ^(.+)\.jsp$ $1 [R=301,QSA,L]
RewriteRule ^(.+)index$ $1 [R=301,QSA,L]

This is a good idea for SEO purposes so that search engines dont ding you for duplicating content at multiple urls.

Ryan Watkins