带变量的Servlet映射(Tomcat 7.0) [英] Servlet Mappings with Variables(Tomcat 7.0)

查看:111
本文介绍了带变量的Servlet映射(Tomcat 7.0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将URL映射到servlet(可能是Tomcat特有的),以便后面的两个URL({id}是从代码中检索的变量),

Is it possible to map URLs to servlets (maybe something specific with Tomcat) so that the two following URLs (with {id}'s being variables retrievable from code),

/users/{id}/a

/users/{id}/b

映射到两个不同的servlet,或者我是否必须为映射到 / users / * <的servlet实现我自己的某种过滤器/ code>?

map to two different servlets, or will I have to implement some sort of filter of my own for a servlet mapped to /users/*?

更清楚的是,任何带有 / users / * / a 应该映射到同一个servlet。 / users / * / b 也是如此。

To be more clear, any URL with the pattern /users/*/a should map to the same servlet. The same goes for /users/*/b.

推荐答案

你可以在 / users / * 上映射它,并从 HttpServletRequest#getPathInfo()

You could map it on /users/* and extract information from HttpServletRequest#getPathInfo():

@WebServlet("/users/*")
public class UsersController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String[] pathInfo = request.getPathInfo().split("/");
        String id = pathInfo[1]; // {id}
        String command = pathInfo[2]; // a or b
        // ...
    }

}

(省略了对数组大小的明显验证)

这篇关于带变量的Servlet映射(Tomcat 7.0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆