当前位置:编程学习 > JAVA >>

Servlet中getServletConfig()


package web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PricingServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();
ServletConfig config = this.getServletConfig();
out.println("</HTML>");
out.flush();
out.close();
}
}



在上述代码的第十八行有个ServletConfig config = this.getServletConfig();此处的this指代的是哪个类?GenericServlet?为什么? Servlet --------------------编程问答-------------------- this 指的是PricingServlet类,getServletConfig()方法调用的是GenericServlet类的方法,因为PricingServlet继承了HttpServlet类,而HttpServlet类继承了GenericServlet类。 --------------------编程问答-------------------- 可是我改成PricingServlet之后,会报Cannot make a static reference to the non-static method getServletConfig() from the type GenericServlet错误。 --------------------编程问答-------------------- 可是我改成PricingServlet之后,会报Cannot make a static reference to the non-static method getServletConfig() from the type GenericServlet错误。  --------------------编程问答-------------------- 建议楼主先学习Java基础 在开始 Javaweb 学习 --------------------编程问答--------------------
引用 3 楼 MM19920401 的回复:
可是我改成PricingServlet之后,会报Cannot make a static reference to the non-static method getServletConfig() from the type GenericServlet错误。 

首先,getServletConfig() 在GenericServlet中没有被定义成static。其次,PricingServlet继承了GenericServlet,因此相当于PricingServlet这个类中含有getServletConfig(),因此可以使用this来调用(this关键字可以调用本身对象或者属性等)。最后,如果不想用this,可以直接用getServletConfig() --------------------编程问答--------------------
this指的就是PricingServlet 因为this是在当前类的方法中,至于GenericServlet 为PricingServlet 的父类
--------------------编程问答-------------------- this指代的是当前类的实例对象。实例方法只能用类的实例对象来调用。
补充:Java ,  Java EE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,