将参数放入webservlet的url中

时间:2013-11-16 20:26:22

标签: servlets

我正在使用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?或者我需要一个不同的框架才能做到这一点......

1 个答案:

答案 0 :(得分:0)

我正在寻找自己这么久,并找到了解决方案。 您可以尝试获取当前放入浏览器网址的网址,例如:

  

../简档/ this_id

你无法得到这个

  

this_id

以简单的方式,但由于内部servlet正向调度,这并不总是绑定。有时request.getRequestURI()可以根据需要运行,您可以查看它:

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

request.getAttribute("javax.servlet.include.request_uri")

如果您使用<jsp:include tag> 如果您的网址是

  

www.example.com/profile/Ted

结果将是

  

简档/泰德

所以你可以简单地得到你需要的东西。 有关详细信息,请查看Java HttpServletRequest get URL in browsers URL bar

相关问题