Servlets 将参数放入webservlet的url中
我使用的是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("/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")