17.8Servlet入门

一、 什么是Servlet?

Java Servlet 是运行在 Web 服务器或应用服务器上的程序;他是浏览器(HTTP客户端)请求和HTTP服务器上资源(访问数据库)之间的中间层。

二、什么是Servlet的运行环境?

Servlet容器是Java Servlet程序的运行环境,比如,常用的tomcat,同时它也是web服务器;

三、什么是Servlet的生命周期?

Servlet的创建到销毁的过程称为Servlet的生命周期;具体分为三个阶段:

  • Servlet初期化 init()
  • Servlet处理请求 service()
  • Servlet销毁 destroy()

四、创建一个Servlet示例程序

HellowordServlet.java

//@WebServlet(urlPatterns = {"/helloworldServet"})
public class HellowordServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HellowordServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**初始化方法
     * @see #init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        System.out.println("Servlet初期化");
    }

    /**
     * servlet销毁方法
     * @see #destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
        System.out.println("Servlet销毁");
    }

    /**
     * get请求
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //2.重新定义doGet
        response.setContentType("text/html;charset=UTF-8");   //3.设置响应类型
        PrintWriter out = response.getWriter();   //4.取得响应输出对象
        String name = request.getParameter("name");   //5.取得请求参数
        out.println("");
        out.println("");
        out.println("A Servlet");
        out.println("");
        out.println("

Hello!" + name + "

"); //6.数据输出到前端 out.print("This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" "); out.println(""); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

web.xml配置

 
        helloworldServet
        com.critc.servlet.HellowordServlet
    
    
        helloworldServet
        /helloworldServet
    

这里面配置一个servlet,指定名称和对应的class,再配置servlet-mapping,指定url映射的类型,这里设置为/helloworldServet,意思就是以http://localhost:8080/helloworldServet开头的请求都会指向这个servlet进行处理。

配置servlet有两种方式,在web3.0之前,一般都是通过配置web.xml来进行配置,就是上面说的这种,在web3.0之后,可以采用注解的方式,比如

@WebServlet(urlPatterns = {"/helloworldServet"})

这个注解写在HelloworldServet.java的定义上。这有一个限制,就是web.xml的最上方定义得是3.0级以上比如:



这里面的版本version得是3.0以上

这个工程部署,启动,在浏览器地址栏输入:http://localhost:8080/helloworldServet?name=java
可以看到如下界面:

17.8Servlet入门_第1张图片
servlet启动

servlet的get请求,通过获取name参数,并输出字符串的值。

这里只是最简单的介绍了一下servlet的配置和使用,servlet非常强大,目前最流行的SpringMVC的基础也是servlet,所以有必要深入学习一下servlet的主要使用。

源码下载

本例子详细源码

你可能感兴趣的:(17.8Servlet入门)