ServletContext和request获取当前工程路径

1.方法
	1.ServletContext.getContextPath()  获取当前工程路径(当前的工程名字)
	2.Request.contextPath()  获取当前工程路径(当前的工程名字)
2.代码
	代码: 
	 
	public class ContextPathServlet_01 extends HttpServlet {
	 
		public void doGet(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			//找到ServletContext
			ServletContext context = this.getServletContext();
			//获取当前的工程名
			String contextPath = context.getContextPath();
			//System.out.println("当前工程的名字:"+ contextPath);
			//请求重定向 , 缺点:因为工程名写死了。  解决方案: 动态获取工程名
			//response.sendRedirect(contextPath+"/1.html");
			//为了大家方便获取当前工程名字,那么request对象也相应的增加该方法。
			response.sendRedirect(request.getContextPath()+"/1.html");
			
		}
	 
		public void doPost(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			doGet(request, response);
		}
	 
	}
	
	

猜你喜欢

转载自blog.csdn.net/chenzuen113113/article/details/80918518