如何使URL过滤路由操作使用Servlet?(How to make a URL filter to

2019-07-30 15:44发布

我目前正在开发一个Java EE Web框架,我想知道我怎么会路线我的网址的......我要支持HMVC功能! 网址将遵循以下规则:

/ MODULE_NAME / CONTROLLER_NAME / ACTION_NAME,其中:

MODULE_NAME:路径由模块“X”斜线...例:子模块“Y”分隔:/ X / Y CONTROLLER_NAME:没有特殊字符控制器的名称ACTION_NAME:没有特殊字符的动作名称

我想图/ MODULE_NAME / CONTROLLER_NAME /到特定的servlet控制器! 行动部分是对类的公共方法! :)

我怎么能这样做? 使用过滤器? 我想一个例子,如果可能的话!

Answer 1:

我看到3种方式:滤波器,基本的servlet(经由主servlet的所有请求)或“小服务程序映射”

过滤

这个例子重写URL

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

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映射 - 简单地说,不灵活(具体路线规则)


文章来源: How to make a URL filter to route actions with Servlets?