您的位置:首页 > 其它

Servlet笔记(一)

2017-01-17 23:10 78 查看

Servlet,用目前网上最流传的定义就是“Servlet是运行在服务器端的JAVA小程序,也是一个JAVA类”。

Servlet类是一个接口,它有着诸如init(),service(),destory(),getServletConfig(),servletRequset(),servletRequest()等方法。

Servlet的生命周期:服务器实例化该Servlet对象>初始化(init())>服务(service())>摧毁(destory())

GenericServlet实现了Servlet接口,并且只需要重写service()方法,相对来讲灵活了一点(适配器模式)

HttpServlet继承了GenericServlet类,这是JAVAWEB开发中最常用的类,其中我们主要用到doPost()和doGet()方法。

ServletConfig()主要是为了取得配置文件中某Servlet的配置信息,它本身就是一个类,取得配置信息的方法主要有三种:

1.

public class d1 extends HttpServlet {

private ServletConfig config;

@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
this.config = config;
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String encoding = config.getInitParameter("encoding");
//String encoding = this.getServletConfig().getInitParameter("encoding");
// String encoding = this.getInitParameter("encoding");
System.out.println(encoding);
}

2.
public class d1 extends HttpServlet {

// private ServletConfig config;
//
//
// @Override
// public void init(ServletConfig config) throws ServletException {
// // TODO Auto-generated method stub
// this.config = config;
// }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//String encoding = config.getInitParameter("encoding");
String encoding = this.getServletConfig().getInitParameter("encoding");
// String encoding = this.getInitParameter("encoding");
System.out.println(encoding);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

3.
public class d1 extends HttpServlet {

// private ServletConfig config;
//
//
// @Override
// public void init(ServletConfig config) throws ServletException {
// // TODO Auto-generated method stub
// this.config = config;
// }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//String encoding = config.getInitParameter("encoding");
//String encoding = this.getServletConfig().getInitParameter("encoding");
String encoding = this.getInitParameter("encoding");
System.out.println(encoding);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: