我目前正在开发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控制器!动作部分是该类的公共方法!:)
我该怎么做?使用过滤器?如果可能,我想举个例子!
我看到3种方式:过滤器,基本servlet(通过主servlet的所有请求)或“ servlet映射”
过滤
这个例子重写URL
http://example.org/ <整数值>
至
http://example.org/user?id= <整数值>
即
http://example.org/1234-> http://example.org/user?id=1234
<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部分中,您可以指定路由规则
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>