@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String mn = req.getServletPath();
mn = mn.substring(1);
mn = mn.substring(0, mn.length() - 4);
Method method = null;
try {
method = this.getClass().getDeclaredMethod(mn, HttpServletRequest.class, HttpServletResponse.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
假定你的工程名称为projects,你在浏览器中输入请求路径:
http://127.0.0.1:8080/projects/pages/newForm.jsp
则执行下面向行代码后打印出如下结果:
1、 System.out.println(request.getContextPath());
打印结果:/projects
2、System.out.println(request.getServletPath());
打印结果:/pages/newForm.jsp
3、 System.out.println(request.getRequestURI());
打印结果:/projects/pages/newForm.jsp
4、 System.out.println(request.getRealPath("/"));
JSP servlet API提供了getRealPath(path)方法,返回给定虚拟路径的真实路径,如果转换错误,则返回null。
打印结果:C:\Tomcat5.0\webapps\projects\test