How to make a URL filter to route actions with Servlets?

前端 未结 1 886
心在旅途
心在旅途 2021-02-04 22:41

I\'m currently developing a Java EE web framework and I would want to know how I could route my URL\'s... I want support HMVC feature! URL\'s will follow this rule:

/mod

相关标签:
1条回答
  • 2021-02-04 22:57

    i see 3 ways: filter, basic servlet(all requests via main servlet) or "servlet-mapping"

    filter

    This example rewrite url

    http://example.org/<int value>
    to
    http://example.org/user?id=<int value>
    i.e

    http://example.org/1234 -> http://example.org/user?id=1234
    1. determinate filter in web.xml
    <filter>
        <filter-name>Router</filter-name>
        <filter-class>org.example.Router</filter-class>
        <init-param>
            <param-name>param1</param-name>
            <param-value>valueOfparam1</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Router</filter-name>
        <url-pattern>/*</url-pattern> 
    </filter-mapping>
    

    in init-param section you can specify route rules

    1. filter class

      public class Router implements javax.servlet.Filter {
      
      private static final Pattern REWRITE_PATTERN = Pattern.compile("(^[1-9]\\d*)$");
      
      @Override
      public void destroy() {
      }
      
      @Override
      public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
      //this method calling before controller(servlet), every request
      
          HttpServletRequest request = (HttpServletRequest) req;
          String url = request.getRequestURL().toString();
          String number = url.substring(url.lastIndexOf("/")).replace("/", "");
      
          Matcher m = REWRITE_PATTERN.matcher(number);
          if(m.find()) {
              RequestDispatcher dispatcher = request.getRequestDispatcher("user?id=" + m.group(1));
              dispatcher.forward(req, res);
          } else {
              fc.doFilter(req, res);
          }
      }
      
      @Override
      public void init(FilterConfig fc) throws ServletException {
          //here you may read params from web.xml
      }}
      

    basic sevlet

    public class BasicServlet extends HttpServlet {
       //route rules here, and rewrite
    }
    

    servlet-mapping

    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <uri-mapping>/user/*</uri-mapping>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>PostServlet</servlet-name>
        <uri-mapping>/post/*</uri-mapping>
    </servlet-mapping>
    
    • filter - more flexible and not require serious modify working code
    • basic servlet - flexible, require change you code
    • servlet mapping - simply, not flexible(for specific route rules)
    0 讨论(0)
提交回复
热议问题