Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Servlets 将参数放入webservlet的url中_Servlets - Fatal编程技术网

Servlets 将参数放入webservlet的url中

Servlets 将参数放入webservlet的url中,servlets,Servlets,我使用的是Webservlet,我想在url本身中传递参数。差不多 @WebServlet("/profile/{id}") public class ProfileServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse res) { String idstr = req.getParameter("id");

我使用的是Webservlet,我想在url本身中传递参数。差不多

@WebServlet("/profile/{id}")
public class ProfileServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) {
        String idstr = req.getParameter("id");
        int id = idstr == null ? (int)req.getSession().getAttribute("userid") : Integer.parseInt(idstr);
        Profile profile = ProfileDAO.getForId(id);
        req.setAttribute("profile",profile);
        req.getRequestDispatcher("/WEB-INF/profile.jsp").forward(req,res);
    }
}

但我似乎在文档中找不到任何允许我这样做的东西。我知道我可以做
/profile?idstr=1234
之类的事情,但有没有办法用WebServlet将其插入URL?或者我需要一个不同的框架来完成这项工作……

我花了足够长的时间寻找这个问题,并找到了解决方案。 您可以尝试获取当前放在浏览器url中的url,例如:

../profile/this\u id

你不能得到这个

这个

以一种简单的方式,但由于内部servlet转发调度,这并不总是绑定到。有时
request.getRequestURI()
会根据需要工作,您可以检查它:

String url = null;
url = (String) request.getAttribute("javax.servlet.forward.request_uri");
url = url == null ? ((HttpServletRequest) request).getRequestURI() : url;

如果您使用
如果你的URL是

www.example.com/profile/Ted

结果将是

简介/特德

所以你可以简单地得到你需要的。
有关更多信息,请查看此处

使用任何RESTfulWebService实现都会更容易:SpringWS/ApacheCxf。。否则,据我所知,您需要自己解析URL中的值,并根据解析结果分派正确的函数
request.getAttribute("javax.servlet.include.request_uri")