如何使用url模式查找servlet类名?

时间:2016-11-18 00:47:57

标签: java servlets

我在Eclipse中使用@WebServlet注释。根据给定的url-pattern确定servlet类名的最佳方法是什么?在使用WebServlet之前,我能够在web.xml中搜索模式。但现在我不得不在整个项目中搜索网址模式。

一个具体的例子是:

  

servlet-name:MyServlet
   url-pattern:/ myPattern / *

让我们说在这种情况下我不知道servlet-name。我知道模式" / myPattern / *"。除了搜索" / myPattern / *"之外,我还能做些什么来快速查找名称MyServlet

1 个答案:

答案 0 :(得分:2)

您可以从上下文中获取所有ServlerRegistrations,并通过搜索给定urlPattern的匹配来查看每个ServlerRegistration。请参阅以下方法searchServletRegistrationByUrlPattern()。

如果您经常在项目中需要这个,可以使用urlPattern作为键创建一个Map,将servletName作为值创建。与createMapOfUrlPatternsToServletNames()+ searchServletRegistrationByUrlPattern2()类似。

package testingThings;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/myPattern/*")
public class FindServletByUrlPattern extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Search through all ServletRegistrations and return this which is mapped of the given urlPattern. 
     * If no match is found returns null.
     * 
     * @param urlPattern
     * @return ServletRegistration | null
     * @throws IOException
     */
    protected ServletRegistration searchServletRegistrationByUrlPattern(String urlPattern) throws IOException {
        Map<String, ? extends ServletRegistration> servletRegistrations = getServletContext().getServletRegistrations();

        for (Map.Entry<String, ? extends ServletRegistration> entry : servletRegistrations.entrySet()) {

            ServletRegistration servletRegistration = entry.getValue();
            Collection<String> mappings = servletRegistration.getMappings();

            if (mappings.contains(urlPattern)) {
                return servletRegistration;
            }
        }

        return null;
    }

    /**
     * Search in a map for given urlPattern. 
     * If no match is found returns null.
     * 
     * @param urlPattern
     * @return ServletRegistration | null
     * @throws IOException
     */
    protected ServletRegistration searchServletRegistrationByUrlPattern2(String urlPattern) throws IOException {
        // create urlPattern map
        Map<String, String> urlPatterns = createMapOfUrlPatternsToServletNames();

        String servletName = urlPatterns.get(urlPattern);

        if (servletName== null) {
            return null;
        }

        ServletRegistration servletRegistrationOfSearchedUrlPatternInMap = getServletContext().getServletRegistration(servletName);
        return servletRegistrationOfSearchedUrlPatternInMap;
    }

    protected Map<String, String> createMapOfUrlPatternsToServletNames() throws IOException {
        Map<String, String> urlPatters = new TreeMap<String, String>();

        Map<String, ? extends ServletRegistration> servletRegistrations = getServletContext().getServletRegistrations();

        for (Map.Entry<String, ? extends ServletRegistration> entry : servletRegistrations.entrySet()) {

            ServletRegistration servletRegistration = entry.getValue();
            Collection<String> mappings = servletRegistration.getMappings();

            for (String urlPattern : mappings) {
                urlPatters.put(urlPattern, entry.getValue().getName());
            }
        }

        return urlPatters;
    }

    protected void showInfoAboutServletRegistration(ServletRegistration servletRegistration, HttpServletResponse response) throws IOException {
        if (servletRegistration == null) {
            response.getWriter().append("there is not servlers for this url-pattern<br>");
        }
        else {
            response.getWriter()
                .append("Servlet Name: ").append(servletRegistration.getName()).append("<br>")
                .append("Servlet Class Name: ").append(servletRegistration.getClassName()).append("<br>")
                .append("Mapping: ").append(Arrays.toString(servletRegistration.getMappings().toArray())).append("<br>")
                .append("<br><br>")
            ;
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");

        // get ServletRegistration of the current servlet through servlet's name
        ServletRegistration servletRegistrationOfCurrentServlet = getServletContext().getServletRegistration(getServletName());
        // show in browser
        showInfoAboutServletRegistration(servletRegistrationOfCurrentServlet, response);

        // search ServletRegistration through url-pattern directly
        String urlPattern = request.getParameter("url-pattern");
        if (urlPattern == null) {
            response.getWriter().append("use a query string parameter 'url-pattern' in order to search servlets for a pattern");
        }
        else {
            ServletRegistration servletRegistrationOfSearchedUrlPattern = searchServletRegistrationByUrlPattern(urlPattern);
            // show in browser
            showInfoAboutServletRegistration(servletRegistrationOfSearchedUrlPattern, response);
        }

        // search ServletRegistration through url-pattern over map
        ServletRegistration servletRegistrationOfSearchedUrlPatternInMap = searchServletRegistrationByUrlPattern2(urlPattern);
        showInfoAboutServletRegistration(servletRegistrationOfSearchedUrlPatternInMap, response);

        showInfoAboutAllServletRegistrations(request, response);
    }

    protected void showInfoAboutAllServletRegistrations(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.getWriter()
            .append("<h3>All ServletRegistrations</h3>")
            .append("<table>")
            .append("<tr><th>")
            .append("servletName:" )
            .append("</th><th>")
            .append("servletClassName:" )
            .append("</th><th>")
            .append("Mapping:" )
            .append("</th></tr>")
        ;

        Map<String, ? extends ServletRegistration> servletRegistrations = request.getServletContext().getServletRegistrations();

        for (Map.Entry<String, ? extends ServletRegistration> entry : servletRegistrations.entrySet()) {

            ServletRegistration servlet = entry.getValue();
            String servletName = servlet.getName();
            String servletClassName = servlet.getClassName();
            Collection<String> mappings = servlet.getMappings();

            response.getWriter()
                .append("<tr><td>")
                .append(servletName)
                .append("</td><td>")
                .append(servletClassName)
                .append("</td><td>")
                .append(Arrays.toString(mappings.toArray()))
                .append("</td></tr>")
            ;

        }
    }

}

的JavaDoc