javaWeb之Servlet

来源:互联网 发布:linux tar.bz2 解压 编辑:程序博客网 时间:2024/06/08 17:35

servlet 是什么?

servlet是运行在 Web 服务器中的小型 Java 程序(即:服务器端的小应用程序)。

servlet 通常通过 HTTP(超文本传输协议)接收和响应来自 Web 客户端的请求。

那么如何用呢?

1,首先要创建一个web项目,同时制定Tomact 服务器

2,方式有三种,其实这三种之间都是有关系.

方式一:实现Servlet 接口

代码如下:

/*创建一个类Test 实现 Servlet 重写该接口中的所有方法     这种类是不能直接new 对象的.是交给Tomact去new 对象的.*/public class Test implements Servlet {    //生命周期:实例化对象的.    //刚创建时运行一次.    public Test() {        System.out.println("this is a test");    }    //生命周期:初始化数据.    //第一次被访问时调用.    @Override    public void init(ServletConfig arg0) throws ServletException {        System.out.println("-------init----------");    }//生命周期:服务器活动方法.//一般用来接收请求,并响应用户的请求//每次用户请求都会执行该方法.    @Override    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {        res.getWriter().write("hello world");        System.out.println("-----------service---------------");    }    //生命周期:servlet程序被卸载时调用    @Override    public void destroy() {        System.out.println("-----------destroy-------------");    }    @Override    public ServletConfig getServletConfig() {        return null;    }    @Override    public String getServletInfo() {        return null;    }}

方式二:继承GenericServlet 类

代码如下:

/* 由于GenericServlet 是一个抽象类(适配器模式),它实现了Servlet 接口,    也就是说GenericServlet 类的内部已经帮我们做好很多工作    而我们只需自己重写Service() 就OK了.*/public class Test2 extends GenericServlet{    @Override    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {        res.getWriter().write("i love you");        System.out.println("0000000000000000000");    }}

方式三:继承HttpServlet类(模板设计模式)常用这种.

代码如下:

/*HttpServlet类其实是继承GenericServlet类,也就是说子类比父类一般都是强大的.这里就是重写doGet方法和doPost方法,处理不同请求.那么HttpServlet 底层已经将其父类的service()方法重写判断不同的请求,调用不同的doxxx()方法.*/public class Test3 extends HttpServlet{    public Test3() {    }    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        System.out.println("ggggggggggggggg");    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        System.out.println("hhhhhhhhhhhhhhhhhhh");        doGet(req, resp);    }}

以上操作还是无法实现其效果的,需要在web.xml中配置相应的属性才可以.(因为java类需要配置好才能显示给外部,如果没限制全部暴露,那就不好了.)

所以一般配置如下:
特别地:如果找不到web.xml可以右键项目–>javaEE Tools–>Generate…

web.xml 配置如下属性就可以了.

<web-app>    .....    <servlet>        <!-- 别名 -->      <servlet-name>test</servlet-name>      <!-- 全类名 / -->      <servlet-class>com.zero.test.Test</servlet-class><!-- 这句设置Tomact启动时就启动该servlet,一般是从2开始,越小优先级越高 -->      <load-on-startup>3</load-on-startup>    </servlet>    <servlet-mapping><!-- 映射 -->      <servlet-name>test</servlet-name>      <url-pattern>/test</url-pattern><!-- 一定要加 / -->    </servlet-mapping>    ....  </web-app>

将以上任意一种方式并在web.xml中配置好,部署到Tomact就可以实现.打一个浏览器,输入http://localhost:8080/DemoServlet/test 地址即可访问.

总结一下流程:

1,servlet的执行流程:
一个浏览器—–>通过http协议的地址——>Tomact服务器 ——>web.xml中的servlet的配置 ——->找到对应的类,并实例化—->走该实现Servlet接口的子类的生命周期——>service()方法,处理后—–>响应 请求—>Tomact服务器 —->浏览器等客户端.

2, Servlet –> GenericServlet –> HttpServlet (继承HttpServlet)

ServletConfig的使用

  • 1,获取servlet的配置信息

    • String getInitParameter(String name) //获取配置文件的属性值

    • Enumeration getInitParameterNames() //获取所有配置属性

    • ServletContext getServletContext()

    • String getServletName()

  • 2,获取ServletContext

    • ServletContext: 代表的是整个应用。一个应用只有一个ServletContext对象。单实例。
    • 其实servlet也是单实例的.每个客户端请求获取一个servlet ,那么多个人呢,就会各自创建自己的servlet .(所以千万不要在servlet中定义全局变量.)

ServletContext常用方法:

//向ServletContext对象的map中添加数据void setAttribute(String name,object value);//从ServletContext对象的map中取数据Object getAttribute(String name);//根据name去移除数据void rmoveAttribute(String name);

其实ServletContext的用途1

域对象:在一定范围内(当前应用),使多个Servlet共享数据。

这里写图片描述

代码演示如下:

servlet1的代码如下:

package com.zero.test.servletcontext;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 TestContext */@WebServlet("/TestContext")public class TestContext extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public TestContext() {        super();    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         ServletContext sc = this.getServletContext();         //使用servleContext设置某对键值对        sc.setAttribute("name", "zero");        System.out.println(sc.getClass().getName());    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        doGet(request, response);    }}

servlet2的代码如下

package com.zero.test.servletcontext;import java.io.IOException;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 TestContext2 */@WebServlet("/TestContext2")public class TestContext2 extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public TestContext2() {        super();    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        ServletContext sc = this.getServletContext();        //从servletContext中获取.该参数在servlet1中设置的.        String name = (String) sc.getAttribute("name");        if(name == null)            System.out.println("出现null");        else            System.out.println(name);    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        doGet(request, response);    }}

servletContext的用途2

String getRealPath(String path);//根据资源名称得到资源的绝对路径.
可以得到当前应用任何位置的任何资源。

特别的当前应用位置是指服务器部署的位置,不是你的磁盘的该类的保存的windows路径

public class Test5 extends HttpServlet {    private static final long serialVersionUID = 1L;    public Test5() {        super();    }    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        ServletContext sc = this.getServletContext();    //String path = sc.getRealPath("/WEB-INF/c.properties");//这是获取WEB-INF目录下的文件        //String path = sc.getRealPath("/WEB-INF/classes/a.properties");//这是获取src目录下的文件        //这是获取自定义的com/zero/test包目录下的文件        String path = sc.getRealPath("/WEB-INF/classes/com/zero/test/b.properties");        Properties prop = new Properties();        prop.load(new FileInputStream(path));        String value = prop.getProperty("key");        System.out.println(value);    }    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        doGet(request, response);    }}

servletContext的用途3

实现Servlet的转发。
RequestDispatcher getRequestDispatcher(String path) ;//参数表示要跳转到哪去
这里写图片描述

在某个HttpServlet的子类中的doGet()方法中添加
servlet1代码中添加

ServletContext sc = this.getServletContext();        System.out.println("test6 give test1 to do it ");        RequestDispatcher rd = sc.getRequestDispatcher("/test");        rd.forward(request, response);        System.out.println("well done ");

对应的servlet2的代码中执行相应的处理就可以了.
此处是模拟,并不相对应,就是为了说明一下是可跳转过去的.

public class Test implements Servlet {    public Test() {        System.out.println("this is a test");    }    @Override    public void destroy() {        System.out.println("-----------destroy-------------");    }    @Override    public ServletConfig getServletConfig() {        return null;    }    @Override    public String getServletInfo() {        return null;    }    @Override    public void init(ServletConfig arg0) throws ServletException {        System.out.println("-------init----------");    }    @Override    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {        res.getWriter().write("hello world");        System.out.println("-----------service---------------");    }}
0 0
原创粉丝点击