How to use a servlet filter in Java to change an incoming servlet request url?

后端 未结 3 1275
春和景丽
春和景丽 2020-11-22 07:24

How can I use a servlet filter to change an incoming servlet request url from

http://nm-java.appspot.com/Check_License/Dir_My_App/Dir_ABC/My_Obj_123

3条回答
  •  耶瑟儿~
    2020-11-22 07:59

    A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.

    public class UrlPrettyfierFilter implements Filter {
    
        private static final String JSF_VIEW_ROOT_PATH = "/ui";
    
        private static final String JSF_VIEW_SUFFIX = ".xhtml";
    
        @Override
        public void destroy() {
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
            String requestURI = httpServletRequest.getRequestURI();
            //Only process the paths starting with /ui, so as other requests get unprocessed. 
            //You can register the filter itself for /ui/* only, too
            if (requestURI.startsWith(JSF_VIEW_ROOT_PATH) 
                    && !requestURI.contains(JSF_VIEW_SUFFIX)) {
                request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
                    .forward(request,response);
            } else {
                chain.doFilter(httpServletRequest, response);
            }
        }
    
        @Override
        public void init(FilterConfig arg0) throws ServletException {
    
        }
    
    }
    

提交回复
热议问题