理。使用 Filter 的一个好 处是如果 URL 没有被任何 Controller 的映射方法匹配到,则可以简单地调用 FilterChain.doFilter() 将 HTTP 请求传递给下一个 Filter,这样,我们就不 必自己处理静态文件,而由 Web 服务器提供的默认 Servlet 处理,效率更高。 和 DispatcherServlet 类似,我们编写一个 DispatcherFilter 作为前置处理 器,负责转发请求,代码见清单 24。
清单 24. 定义 DispatcherFilter
public class DispatcherFilter implements Filter {
...
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) req;
HttpServletResponse httpResp = (HttpServletResponse) resp;
String method = httpReq.getMethod();
if ("GET".equals(method) || "POST".equals(method)) {
if (!dispatcher.service(httpReq, httpResp))
chain.doFilter(req, resp);
return;
}
httpResp.sendError (HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
}
如果用 DispatcherFilter 代替 DispatcherServlet,则我们需要过滤“/* ”,在 web.xml 中添加声明如清单 25 所示。
清单 25. 声明 DispatcherFilter
<filter>
<filter-name>dispatcher</servlet-name>
<filter- class>org.expressme.webwind.DispatcherFilter</servlet- class>
</filter>
<filter-mapping>
<filter-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
设计REST风格的MVC框架(11)
时间:2011-06-01 IBM 廖雪峰
访问 Request 和 Response 对象
如何在 @Mapping 方法中访问 Servlet 对象?如 HttpServletRequest, HttpServletResponse,HttpSession 和 ServletContext。ThreadLocal 是一个 最简单有效的解决方案。我们编写一个 ActionContext,通过 ThreadLocal 来 封装对 Request 等对象的访问。代码见清单 26。
清单 26. 定义 ActionContext
public final class ActionContext {
private static final ThreadLocal<ActionContext> actionContextThreadLocal
= new ThreadLocal<ActionContext>();
private ServletContext context;
private HttpServletRequest request;
private HttpServletResponse response;
public ServletContext getServletContext() {
return context;
}
public HttpServletRequest getHttpServletRequest() {
return request;
}
public HttpServletResponse getHttpServletResponse() {
return response;
}
public HttpSession getHttpSession() {
return request.getSession();
}
public static ActionContext getActionContext() {
return actionContextThreadLocal.get();
}
static void setActionContext(ServletContext context,
HttpServletRequest request, HttpServletResponse response) {
ActionContext ctx = new ActionContext();
ctx.context = context;
ctx.request = request;
ctx.
|