小编典典

如何制作URL过滤器以使用Servlet路由动作?

jsp

我目前正在开发Java EE Web框架,我想知道如何路由我的URL。我想支持HMVC功能!URL将遵循以下规则:

/ module_name / controller_name / action_name,其中:

module_name:用斜杠分隔的路径…例如:模块“ X”的子模块“ Y”:/ X / Y
controller_name:不带特殊字符的控制器名称action_name:不带特殊字符的动作名称

我想将/ module_name / controller_name /映射到特定的servlet控制器!动作部分是该类的公共方法!:)

我该怎么做?使用过滤器?如果可能,我想举个例子!


阅读 320

收藏
2020-06-08

共1个答案

小编典典

我看到3种方式:过滤器,基本servlet(通过主servlet的所有请求)或“ servlet映射”

过滤

这个例子重写URL

http://example.org/ <整数值>

http://example.org/user?id= <整数值>

http://example.org/1234-> http://example.org/user?id=1234
  1. 确定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>

在init-param部分中,您可以指定路由规则

  1. 过滤器类
        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
    }}

基本Sevlet

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

servlet映射

    <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>
  • 过滤器-更灵活,不需要认真修改工作代码
  • 基本servlet-灵活,需要更改您的代码
  • Servlet映射-简单,不灵活(针对特定的路由规则)
2020-06-08