问题
I have a web app with many JSP files and want to remove the .jsp extensions from displaying in the URL without having to map each servlet to a similar page name. To do this I would like to redirect all servlets to a JSP file in a generic manner such as mapping /Login to /Login.jsp.
I mapped all servlets to a filter as below. This works with respect to redirections to *.jsp except the end result is a blank page with the URL still containing the .jsp extension.
<servlet>
<servlet-name>PageNameFilter</servlet-name>
<servlet-class>PageName</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PageNameFilter</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
public class PageName extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String uri = request.getRequestURI();
if (!uri.endsWith(".jsp"))
{
String newPage = uri + ".jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(newPage);
dispatcher.forward(request, response);
}
else
{
// Here when we have a full URL (ie: /Login.jsp)
// ??? WHAT TO DO HERE ???
}
}
}
回答1:
I was able to get this working by automating the servlet mapping. So it comes down to running a script and a cut/past of the mappings into Web.xml. This script (windows cmd) generates a file named servletmap.xml with the mappings to include.
@echo off
set outFile=servletmap.xml
echo. > %outFile%
for /f %%i in ('dir ..\WebContent\*.jsp /b') do (
echo %%~ni
echo ^<servlet^> >> %outFile%
echo ^<servlet-name^>%%~ni^</servlet-name^> >> %outFile%
echo ^<jsp-file^>/%%i^</jsp-file^> >> %outFile%
echo ^</servlet^> >> %outFile%
echo ^<servlet-mapping^> >> %outFile%
echo ^<servlet-name^>%%~ni^</servlet-name^> >> %outFile%
echo ^<url-pattern^>/%%~ni^</url-pattern^> >> %outFile%
echo ^</servlet-mapping^> >> %outFile%
echo. >> %outFile%
echo. >> %outFile%
)
回答2:
I finally did this dynamically without servlet mappings using tuckey's urlrewrite. See the SO post here urlrewrite example
来源:https://stackoverflow.com/questions/40006723/generic-servlet-to-jsp-mapping