Servlet
    1,servlet介绍
        servlet是一项动态web资源开发技术.
        运行在服务器端.
        作用:处理业务逻辑,生成动态的内容,返回给浏览器.
        本质就是一个类
     servlet的入门
        1.编写servlet(类)--- 继承HttpServlet
        2.编写关系--- web.xml(在WEB-INF下)
        3.访问:
            路径:http://localhost:80/serveltDemo/helloWorld
    servlet的体系结构及其常见api
        Servlet-- 接口
            |
            |
        GenericServlet---(抽象类)
            |
            |
        HttpServlet--(抽象类)
       
        常用的方法:
            servlet的常用方法:
                void init(ServletConfig):初始化方法
                void service(ServletRequest,ServletResponse):服务--处理业务逻辑
                void destroy():销毁方法
               
                ServletConfig getServletConfig():返回一个servlet的配置对象
                String getServletInfo() :返回是servlet一些信息,比如作者 版本
           
            GenericServlet的常用方法:
                实现了除了service方法之外的所有方法
                init():自己重写init方法
            HttpServlet的常用方法:
                service(HttpServletRequest,HttpServletResponse):服务--处理业务逻辑
                doGet(HttpServletRequest,HttpServletResponse):处理get请求的
                doPost(HttpServletRequest,HttpServletResponse):处理post请求的
    代码示例:

 public class HelloWorldServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("hello world servlet");
}
}

HelloServlet.java

<servlet-mapping>
<servlet-name>HelloWroldServlet</servlet-name>
<url-pattern>/helloWorld</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>LifeServlet</servlet-name>
<servlet-class>cn.augmentum.b_life.LifeServlet</servlet-class>
</servlet>     

  2,servlet生命周期:
       生命周期:什么时候来的,什么时候走的.
            void init(ServletConfig):初始化方法
                 * 执行时间:默认情况来说,第一次的请求的时候执行
                 * 执行次数:一次
                 * 执行者:tomcat
            void service(ServletRequest,ServletResponse):服务--处理业务逻辑
                * 执行时间:有请求就执行
                * 执行次数:请求一次,执行一次
                * 执行者:tomcat
            void destroy():销毁方法   
                * 执行时间:服务器正常关闭的时候执行
                * 执行次数:一次
                * 执行者:tomcat
        servlet是单实例多线程的
            默认的情况下是第一次访问的时候创建(有服务器创建),每出现一次请求,创建一个线程,用来处理请求,
            直到服务器正常关闭或者项目移除的时候servlet销毁
   url-pattern编写
        1.完全匹配,----(servlet最常用的)以"/"开头
            例如:/a/b/c/hello
        2.目录匹配 以"/"开头,以"*"结尾(filter常用的)
            例如:/a/*
        3.后缀名匹配 以"*"开头 
            例如:  *.do   *.jsp
       
        优先级:
            完全匹配>目录匹配>后缀名匹配
       
        有如下的一些映射关系:
            Servlet1 映射到 /abc/*
            Servlet2 映射到 /*
            Servlet3 映射到 /abc
            Servlet4 映射到 *.do
        问题:
            当请求URL为“/abc/a.html”,“/abc/*”和“/*”都匹配,哪个servlet响应
                Servlet引擎将调用Servlet1。
            当请求URL为“/abc”时,“/abc/*”和“/abc”都匹配,哪个servlet响应
                Servlet引擎将调用Servlet3。
            当请求URL为“/abc/a.do”时,“/abc/*”和“*.do”都匹配,哪个servlet响应
                Servlet引擎将调用Servlet1。
            当请求URL为“/a.do”时,“/*”和“*.do”都匹配,哪个servlet响应
                Servlet引擎将调用Servlet2.
            当请求URL为“/xxx/yyy/a.do”时,“/*”和“*.do”都匹配,哪个servlet响应
                Servlet引擎将调用Servlet2。
         tomcat的defalutservlet处理别的servlet处理不了的请求.
   load-on-startup
       
在servlet标签下
        改变servlet初始化时机.
        若值>=0的时候,servlet会随着服务器的启动而创建.
        值越小,优先级越高
    浏览器的路径编写:
        1.浏览器直接输入
        2.a标签
        3.location.href
        4.表单提交
       
        路径的写法:
            1.绝对路径
                带协议的绝对路径--一般访问站外资源的时候用
                    http://localhost:80/servletDemo/helloWorld
               
不带协议的绝对路径--站内资源
                    /servletDemo/helloWorld
            2.相对路径
                ./(路径) 和 ../
                八字方针
                    当前路径  http://localhost/servletDemo/    index.html
                    访问路径  http://localhost/servletDemo/    demoa
                   
                    当前路径  http://localhost/servletDemo/   a/b/c    ../../demoa
                    访问路径  http://localhost/servletDemo/   demoa
        以后使用的是绝对路径(一般使用的是不带协议的绝对路径)
       
3,ServletConfig
   
他是当前servlet的配置对象.
    获取方式:
        ServletConfig config=this.getServletConfig();
    作用:
        1.可以获取到当前servlet初始化参数
        2.可以获得全局管理者
    常用方法:
        String getServletName():获取当前servlet的名称 --指的是web.xml中servlet名字
        String getInitParameter(name):获取指定的参数
        Enumeration getInitParameterNames():获取全部初始化参数名称
       
        ServletContext getServletContext():获取全局管理者
    当servlet初始化的时候,执行了init(ServletConfig config),就把创建好的servletConfig传给了servlet
        由tomcat创建

示例代码:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletConfig conf=this.getServletConfig();
//获取当前servlet名字
String name=conf.getServletName();
System.out.println(name); //获取名字为 "姓名"的参数值
String value = conf.getInitParameter("姓名");
System.out.println(value); //获取全部参数名称
Enumeration<String> names=conf.getInitParameterNames();
while(names.hasMoreElements()){
String name_=names.nextElement();
System.out.println(name_+":"+conf.getInitParameter(name_));
}
}

4,ServletContext
    全局管理者.
    每个应用在tomcat启动的时候,就会创建一个servletcontext对象,这个对象可以获取到当前应用的所有信息,实现资源共享.
    本质servletcontext就是对当前应用的一个引用.
    作用:
        1.实现资源共享
        2.获取全局初始化参数.
        3.获取资源.
    怎么获取:
        this.getServletConfig().getServletContext():
        getServletContext()也可以获取
    常见的方法:
        String getInitparameter(name);获取指定的参数
        Enumeration getInitParameterNames():获取全部的参数名称
            参数   
                <context-param>
                    <param-name>
                    <param-value>
                   
        String getRealPath(path):返回相应文件在tomcat的实际路径
            例如:D:\JavaTools\apache-tomcat-7.0.53\webapps\servletDemo\
        InputStream getResourceAsStream(String path) :以流的形式返回对应的文件.
       
        String getMimeType(String file)   可以获取一个文件的mimeType类型. 例如 text/html
        URL getResource(String path) 它返回的是一个资源的URL        例如:  localhost/day09/a.html
    域对象:
        把他看成一个map,
        xxxAttribute()
            setAttribute(String,Object):添加
            Object getAttribute(string):获取
            removeAttribute(string):移除
示例代码:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//首先获取ServletContext对象
ServletContext context=this.getServletContext(); //获取url
String url=context.getInitParameter("url");
//System.out.println(url); //获取全部的全局初始化参数
Enumeration<String> paramNames=context.getInitParameterNames();
while(paramNames.hasMoreElements()){
String name=paramNames.nextElement();
///System.out.println(name+":"+context.getInitParameter(name));
} //返回 "/"的路径
//String path=context.getRealPath("/");
//String path = context.getRealPath("/5.txt"); // 错误的
//System.out.println(path);
/*InputStream in = context.getResourceAsStream("/WEB-INF/classes/cn/itcast/e_servletcontext/5.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String readLine = reader.readLine();
System.out.println(readLine);*/ //获取index.htmlmime类型 String type = context.getMimeType("/a.html");
//System.out.println(type);
URL url_ = context.getResource("/a.html");
System.out.println(url_.getPath());
}


     

5,classpath
   
获取字节码文件的路径.
    通过字节码文件获取
        当前类.class.getResource("/").getPath():返回classes的目录
            D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/
        当前类.class.getResource("").getPath():返回当前类的字节码文件所在的目录
            D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/cn/itcast/h_classpath/
           
    通过类加载器获取文件路径
        当前类.class.getClassLoader().getResource("/").getPath():返回classes的目录
            D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/
        当前类.class.getClassLoader().getResource().getPath():返回classes的目录
            D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/
示例代码:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//String path1 = PathServlet.class.getResource("/").getPath();
// D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/
//String path2 = PathServlet.class.getResource("").getPath();
// D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/cn/augmentum/h_classpath/
// System.out.println(path1);
// System.out.println(path2); //String path3 = PathServlet.class.getClassLoader().getResource("/").getPath();
//String path4 = PathServlet.class.getClassLoader().getResource("").getPath(); //System.out.println(path3);
//System.out.println(path4);
// myeclipse tomcat路径 获取
//1.txt src /WEB-INF/classes/1.txt lei.class.getResource("/").getpath()
//2.txt webroot /2.txt context.getRealPath
//3.txt web-inf /WEB-INF/3.txt context.getRealPath
//4.txt cn.augmentum.h_classpath /WEB-INF/classes/cn/augmentum/h_classpath/4.txt lei.class.getResource("").getpath() ServletContext context=this.getServletContext();
String path1 = PathServlet.class.getResource("/1.txt").getPath();
String path2 = context.getRealPath("/2.txt");
String path3 = context.getRealPath("/WEB-INF/3.txt");
String path4 = PathServlet.class.getResource("4.txt").getPath(); /*System.out.println(path1);
System.out.println(path2);
System.out.println(path3);
System.out.println(path4);*/
readFile(path1);
readFile(path2);
readFile(path3);
readFile(path4);
}

小demo: 当访问index.html中的 链接则通过CountServlet计数, 每访问一次则count加1, 然后通过ShowServlet展示到控制台:

 public class CountServlet extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//访问计数
//首先获取context对象
ServletContext context=this.getServletContext();
//请求一次,context取出访问次数
Integer count=(Integer) context.getAttribute("count");
//次数+1,放入context中
if (count==null) {
context.setAttribute("count", 1);
}else{
context.setAttribute("count", ++count);
}
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }

CountServlet.java

 public class ShowServlet extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//首先获取context
ServletContext context=this.getServletContext();
//取次数
Integer count=(Integer) context.getAttribute("count");
System.out.println("访问的次数为:"+(count==null?0:count));
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }

ShowServlet.java

 <body>
<a href="/servletDemo/count">显示次数</a><br/>
<a href="/servletDemo/show">展示结果</a><br/>
</body>

index.html

 <servlet>
<servlet-name>CountServlet</servlet-name>
<servlet-class>cn.augmentum.showcount.CountServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ShowServlet</servlet-name>
<servlet-class>cn.augmentum.showcount.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CountServlet</servlet-name>
<url-pattern>/count</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ShowServlet</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>

web.xml

[Java拾遗三]JavaWeb基础之Servlet的更多相关文章

  1. [Java面试三]JavaWeb基础知识总结.

    1.web服务器与HTTP协议 Web服务器 l WEB,在英语中web即表示网页的意思,它用于表示Internet主机上供外界访问的资源. l Internet上供外界访问的Web资源分为: • 静 ...

  2. [Java拾遗四]JavaWeb基础之Servlet_Request&&Response

    今天来回顾下之前学过Servle的Resquest以及Response的知识.1,Request和Response技术:    rr的作用:        request是请求,封装用户的请求信息.若 ...

  3. JavaWeb基础:Servlet

    Servlet 基本概念 Servlet是Sun公司提出的一种用于开发动态Web资源的技术规范: Servlet是一个Java接口, 用户想要开发自定义的Servlet可以通过以下步骤: 编写实现Se ...

  4. java前三本基础知识总结

    基础软件:1:JDK,JRE,JVM(一些参数和作用),GC(机制和算法),Class,Loader(机种作用,加载顺序) 2:环境搭建:JAVA_HOME,path,class 语言基础:引用类型: ...

  5. JavaWeb基础之Servlet简单实现用户登陆

    学习javaweb遇到了一些坑,一些问题总结下来,记个笔记. 学习servlet遇到的一些坑: servlet实现用户登陆遇到的坑解决办法: https://www.cnblogs.com/swxj/ ...

  6. JavaWeb基础:Servlet Response

    ServletResponse简介 ServletResponse代表浏览器输出,它提供所有HttpResponse的设置接口,可以设置HttpResponse的响应状态,响应头和响应内容. 生命周期 ...

  7. Java的三个基础排序算法(其余将在以后补充)

    第一个:冒泡排序算法 原理:相邻的两个值进行比较,如果前面的比后面的大就交换位置 eg:假设有5个元素的一个array 第一次:会比较4次,将最大的值放在最右边 第二次:会比较3次,又排出剩余4个元素 ...

  8. java(三)基础类型之间的转换

    自动类型转换:容量小的类型自动转换成为容量大的数据类型,数据类型按容量大小排序为: 有多种类型的数据混合运算时,系统首先自动将所有数据转换成容量最大的那种数据类型,然后在进行运算: byte.shor ...

  9. 从零开始学Java (三)基础语法

    1. 基本数据类型 整数类型:byte,short,int,long 浮点数类型:float,double 字符类型:char 布尔类型:boolean java最小单位是bit,一个byte占用8个 ...

随机推荐

  1. Looping Techniques

    [Looping Techniques] 1.When looping through dictionaries, the key and corresponding value can be ret ...

  2. Groovy basic

    1. print println "Hello Groovy!" you can use java in Groovy System.out.println("Hello ...

  3. Servlet 利用Session实现不重复登录

    import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.It ...

  4. POJ 1637 Sightseeing tour (混合图欧拉回路)

    Sightseeing tour   Description The city executive board in Lund wants to construct a sightseeing tou ...

  5. 搭建DHCP服务器以及DHCP中继服务器

    一.DHCP服务器   1.首先配置DHCP服务器的IP地址(DHCP服务器网卡桥接在VMnet1)   .配置好IP后重启DHCP服务 3.安装DHCP服务器,在这里我用的是YUM安装的(关于YUM ...

  6. Python-Windows下安装BeautifulSoup和requests第三方模块

    http://blog.csdn.net/yannanxiu/article/details/50432498 首先给出官网地址: 1.Request官网 2.BeautifulSoup官网 我下载的 ...

  7. C++11 删除链表重复数值

    #include <memory> #include <iostream> #include <chrono> #include <thread> us ...

  8. 【java】:生成excel

    //生成报表公用方法 //excelName: 生成的文件名 //list:时间/日期/描述 //listSelectFiled:  标题 //showContent :  文件内容bean //生成 ...

  9. 基本套接字编程(3) -- select篇

    1. I/O复用 我们学习了I/o复用的基本知识,了解到目前支持I/O复用的系统调用有select.pselect.poll.epoll.而epoll技术以其独特的优势被越来越多的应用到各大企业服务器 ...

  10. hibernate报错及解决方式

    1 java.sql.BatchUpdateException: ORA-01438: 值大于为此列指定的允许精度 原因:pl/sql number(n),插入的位数大于n