ServletContext获取绝对地址与字节码目录

版权声明:最终解释权归属Hern所有,恒! https://blog.csdn.net/qq_36761831/article/details/85727069

注意:重写了Servlet的init方法后一定要记得调用父类的init方法 ,否则会抛异常!!!

重写init()方法

public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);//这一步很重要,否则service()方法下调用getServletContext()方法会抛异常
	}

 调用该方法

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		ServletContext ser = this.getServletContext();
		
	}

实例

package com.HttpServlet.Index;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SecondServlet
 */
@WebServlet("/22")
public class SecondServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SecondServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);//这一步很重要,否则service()方法下调用getServletContext()方法会抛异常
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		ServletContext ser = this.getServletContext();
		
		//当加载一个文档时要使用绝对路径
		String filePath = ser.getRealPath("");//获取绝对地址
		String filePath2 = ser.getRealPath("WEB-INF/a.txt");//获取绝对地址
		System.out.println(filePath);
		System.out.println(filePath2);
		
		//使用类加载器,获取字节码的路径
		//到字节码目录当中加载资源
		//如果不存在该文件将会抛异常
		String filePath3 = SecondServlet.class.getClassLoader().getResource("b.txt").getPath();
		String filePath4 = SecondServlet.class.getClassLoader().getResource("com/HttpServlet/Index/c.txt").getPath();
		System.out.println(filePath3);
		System.out.println(filePath4);
		
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
		
		
	}


}

猜你喜欢

转载自blog.csdn.net/qq_36761831/article/details/85727069