我知道,默认的servlet会自动返回静态资源。但是,我的网址很特别,我不希望它看起来像http://mysite/app/test.html
。也许是这样的:
http://mysite/app/dosomething/7419698f
我想将此请求映射(或转发?)到静态html文件,例如/WEB-INF/pages/dowork.html。更多信息,7419698f只是一个参数,http://mysite/app/dosomething/2926739e
也将映射到同一个静态文件。我知道这样的解决方法:
<servlet>
<servlet-name>test</servlet-name>
<jsp-file>/pages/dowork.html</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/dosomething/*</url-pattern>
</servlet-mapping>
仅当dowork.html是合法的jsp文件时才有效。如果我想像这样提供图像资源,它就会变成错误。
答案 0 :(得分:1)
使用default
servlet映射您的URL(您不需要声明它)
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/dosomething/*</url-pattern>
</servlet-mapping>
答案 1 :(得分:1)
Leos Literak的线索是正确的。我的要求不能通过简单的xml配置完成,我必须做更多的事情。
我需要一个过滤器。在web.xml中:
<filter>
<filter-name>summary-fw-filter</filter-name>
<filter-class>com.mycompany.mywebapp.filter.SummaryForwardFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>summary-fw-filter</filter-name>
<url-pattern>/summary/*</url-pattern>
</filter-mapping>
过滤器的代码:
public class SummaryForwardFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
String url = request.getRequestURL().toString();
String[] urlSegments = url.split("/");
String guid = urlSegments[urlSegments.length-1];
if(guid.matches("^[a-fA-F0-9]{8}(-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}$")){
request.getRequestDispatcher("/WEB-INF/pages/summary.jsp").forward(servletRequest, servletResponse);
return;
}
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
@Override
public void destroy() {
}
}
然后,url http://mysite/mywebapp/summary/ecef22d6-7aa6-49db-b0d3-6577a63d14c8
将映射到/WEB-INF/pages/summary.jsp。尝试映射到非jsp文件时也没问题。
guid参数可以通过javascript代码检索:
function extractGuid(value) {
var re = /[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i;
var match = re.exec(value);
return match ? match[0] : null;
}
var guid = extractGuid(window.location.href);