Servlet知识点总结



Servlet知识点总结

Servlet是SUN公司提供的一门用于开发动态web资源的技术,用户若想开发一个动态web资源(即开发一个java程序向浏览器输出数据),需要完成:

1、  编写一个java类,实现Servlet接口

2、  把开发好的java类部署到web服务器中。

开发Servlet步骤:

1、  在tomcat中新建一个day04 WEB应用,然后在web应用中新建一个WEB-INF/classes目录

2、  在classes目录中新建一个FirstServlet

package cn.itcast;

import java.io.*;

import javax.servlet.*;

public class FirstServlet extends GenericServlet{

public void service(ServletRequest req,ServletResponse res)throws ServletException,java.io.IOException{

OutputStream out=res.getOutputStream();

out.write(“hello Servlet!!!”.getBytes());

}

}

3、  set classpath=—-servlet-api.jar;编译servlet—–javac –d . FirstServlet.java

4、  在WEB-INF目录中新建一个web.xml文件,配置servlet的对外访问路径

package cn.itcast;

import java.io.*;

import javax.servlet.*;

public class FirstServlet extends GenericServlet{

public void service(ServletRequest req,ServletResponse res)throws ServletException,java.io.IOException{

OutputStream out=res.getOutputStream();

out.write(“hello Servlet!!!”.getBytes());

}

}

 

Web.xml配置

<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<!–

Licensed to the Apache Software Foundation (ASF) under one or more

contributor license agreements.  See the NOTICE file distributed with

this work for additional information regarding copyright ownership.

The ASF licenses this file to You under the Apache License, Version 2.0

(the “License”); you may not use this file except in compliance with

the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software

distributed under the License is distributed on an “AS IS” BASIS,

WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

See the License for the specific language governing permissions and

limitations under the License.

–>

<web-app xmlns=”http://java.sun.com/xml/ns/javaee”

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”

version=”2.5″>

<servlet>

<servlet-name>FirstServlet</servlet-name>

<servlet-class>cn.itcast.FirstServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>FirstServlet</servlet-name>

<url-pattern>/FirstServlet</url-pattern>

</servlet-mapping>

</web-app>

Servlet的运行过程:

Servlet程序是由WEB服务器调用,web服务器收到客户端的Servlet访问请求后:

1、             Web服务器首先检查是否已经装载并创建了该Servlet的实例对象。如果是,则直接执行第四步,否则,执行第二步

2、             装载并创建该Servlet的一个实例对象

3、             调用Servlet实例对象的init()方法

4、             创建一个用于封装HTTP请求消息的HttpServletRequest对象和一个代表HTTP响应消息的HttpServletResponse对象,然后调用Servlet的service()方法并将请求和响应对象作为参数传递进去。

5、             WEB应用程序被停止或重新启动之前,Servlet引擎将卸载Servlet,并在卸载之前调用Servlet的destroy()方法。

MyEclipse开发Servlet:

集成Tomcat:àwindowàpreferencesàServersàtomcatàtomcat 6.x[Enable/home Directory]

发布project:MyEclipse下的两个图标进行配置!

Servlet的细节:

1、由于客户端是通过URL地址访问web服务器中的资源,所以Servlet程序若想被外界访问,必须把Servlet程序映射到一个URL地址上,这个工作在web.xml文件中使用<servlet>元素和<servlet-mapping>元素完成

2、<servlet>元素用于注册Servlet,它包含有两个主要的子元素:<servlet-name>和<servlet-class>,分别用于设置Servlet的注册名称和Servlet的完整类名

3、一个<servlet-mapping>元素用于映射一个已注册的Servlet的一个对外访问路径,它包含有两个子元素:<servlet-name>和<url-pattern>,分别用于指定Servlet的注册名称和Servlet的对外访问路径。

同一个Servlet可以被映射到多个URL上,即多个<servlet-mapping>元素的<servlet-name>子元素的设置值可以是一个Servlet的注册名;

如果在<servlet>元素中配置了一个<load-on-startup>元素,那么WEB应用程序在启动时,就会装载并创建Servlet的实例对象,以及调用Servlet实例对象的init()方法;

ServletConfig对象和它在开发中的应用场景:

   <init-param>

       <param-name>data1</param-name>


       <param-value>XXXXX</param-value>

   </init-param>

       <init-param>

       <param-name>data2</param-name>

       <param-value>YYYYY</param-value>

   </init-param>

       <init-param>

       <param-name>data3</param-name>

       <param-value>ZZZZZ</param-value>

   </init-param>

  </servlet>

    <servlet-mapping>

    <servlet-name>ServletDemo5</servlet-name>

    <url-pattern>/servlet/ServletDemo5</url-pattern>

      </servlet-mapping>

 

 

    publicvoid doGet(HttpServletRequest request, HttpServletResponse response)

          throws ServletException, IOException {

       Enumeration e=this.getServletConfig().getInitParameterNames();

       while(e.hasMoreElements()){

          String name=(String) e.nextElement();

          String value1=this.getServletConfig().getInitParameter(name);

          System.out.println(name+”:”+value1);

       }

    }

    publicvoid doPost(HttpServletRequest request, HttpServletResponse response)

          throws ServletException, IOException {

          doGet(request,response);

    }

应用场景:如指定码表、指定要连接的数据库(用户名、密码)、servlet读取哪个配置文件

servletConfig对象:用于封装servlet的数据信息;

 

ServletContext对象:

WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用,ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。

ServletContext域:

1.       这是一个容器

2.       ServletContext域这句话说明了这个容器作用范围,也就是应用程序范围

读取properties文件(以map集合的形式存放)中的内容

InputStream in=

this.getServletContext().getResourceAsStream(“/WEB-INF/classes/db.properties”);

       Properties props=new Properties();

       props.load(in);

       String url=props.getProperty(“url”);

       String username=props.getProperty(“username”);

       String password=props.getProperty(“password”);

       System.out.println(url);

       System.out.println(username);

       System.out.println(password);

    }

当要获取到读取文件的名称时,需要使用到传统方法:

    publicvoid doGet(HttpServletRequest request, HttpServletResponse response)

          throws ServletException, IOException {

    String path=this.getServletContext()

.getRealPath(“/WEB-INF/classes/db.properties”);

          FileInputStream in=new FileInputStream(path);

          String name=path.substring(path.lastIndexOf(“\\”)+1);

          System.out.println(“获取的资源的名称为”+name);

          Properties props=new Properties();

          props.load(in);

          String url=props.getProperty(“url”);

          String username=props.getProperty(“username”);

          String password=props.getProperty(“password”);

          System.out.println(“获取到的信息为:”);

          System.out.println(url);

          System.out.println(username);

          System.out.println(password);

    }

如果读取资源文件的程序不是servlet的话,只能通过类装载器去读—注意:文件不能太大:

InputStream in=(类加载器只加载一次,无法读取更新后的数据)

UserDao.class.getClassLoader().getResourceAsStream(“db.properties”);

另:String path=UserDao.class.getClassLoader()

.getResource(“db.properties”).getPath();

FileInputStream in=new FileInputStream(path);[为了读取到更新后的数据]