Generic Servlet to JSP Mapping

你。 提交于 2020-01-03 06:50:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!