• [Java拾遗三]JavaWeb基础之Servlet


    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请求的
        代码示例:

    1 public class HelloWorldServlet extends HttpServlet {
    2     @Override
    3     public void doGet(HttpServletRequest req, HttpServletResponse resp)
    4             throws ServletException, IOException {
    5         System.out.println("hello world servlet");
    6     }
    7 }
    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创建

    示例代码:

     1 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     2     ServletConfig conf=this.getServletConfig();
     3     //获取当前servlet名字
     4     String name=conf.getServletName();
     5     System.out.println(name);
     6     
     7     //获取名字为 "姓名"的参数值
     8     String value = conf.getInitParameter("姓名");
     9     System.out.println(value);
    10     
    11     //获取全部参数名称
    12     Enumeration<String> names=conf.getInitParameterNames();
    13     while(names.hasMoreElements()){
    14         String name_=names.nextElement();
    15         System.out.println(name_+":"+conf.getInitParameter(name_));
    16     }
    17 }
    View Code

         
    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:JavaToolsapache-tomcat-7.0.53webappsservletDemo
            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):移除
    示例代码:

     1 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     2     //首先获取ServletContext对象
     3     ServletContext context=this.getServletContext();
     4     
     5     //获取url
     6     String url=context.getInitParameter("url");
     7     //System.out.println(url);
     8     
     9     //获取全部的全局初始化参数
    10     Enumeration<String> paramNames=context.getInitParameterNames();
    11     while(paramNames.hasMoreElements()){
    12         String name=paramNames.nextElement();
    13         ///System.out.println(name+":"+context.getInitParameter(name));
    14     }
    15     
    16     //返回 "/"的路径
    17     //String path=context.getRealPath("/");
    18     //String path = context.getRealPath("/5.txt"); // 错误的
    19     //System.out.println(path);
    20     /*InputStream in = context.getResourceAsStream("/WEB-INF/classes/cn/itcast/e_servletcontext/5.txt");
    21     BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    22     String readLine = reader.readLine();
    23     System.out.println(readLine);*/
    24     
    25     //获取index.htmlmime类型
    26     
    27     String type = context.getMimeType("/a.html");
    28     //System.out.println(type);
    29     URL url_ = context.getResource("/a.html");
    30     System.out.println(url_.getPath());
    31 }
    View Code


         

    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/
    示例代码:

     1 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     2     //String path1 = PathServlet.class.getResource("/").getPath();
     3     // D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/
     4     //String path2 = PathServlet.class.getResource("").getPath();
     5     // D:/JavaTools/apache-tomcat-7.0.53/webapps/day09/WEB-INF/classes/cn/augmentum/h_classpath/
     6     // System.out.println(path1);
     7     // System.out.println(path2);
     8 
     9     //String path3 = PathServlet.class.getClassLoader().getResource("/").getPath();
    10     //String path4 = PathServlet.class.getClassLoader().getResource("").getPath();
    11 
    12     //System.out.println(path3);
    13     //System.out.println(path4);
    14     //       myeclipse                         tomcat路径                                             获取
    15     //1.txt  src                            /WEB-INF/classes/1.txt                            lei.class.getResource("/").getpath()
    16     //2.txt  webroot                        /2.txt                                            context.getRealPath
    17     //3.txt  web-inf                        /WEB-INF/3.txt                                    context.getRealPath
    18     //4.txt  cn.augmentum.h_classpath            /WEB-INF/classes/cn/augmentum/h_classpath/4.txt    lei.class.getResource("").getpath()
    19     
    20     ServletContext context=this.getServletContext();
    21     String path1 = PathServlet.class.getResource("/1.txt").getPath();
    22     String path2 = context.getRealPath("/2.txt");
    23     String path3 = context.getRealPath("/WEB-INF/3.txt");
    24     String path4 = PathServlet.class.getResource("4.txt").getPath();
    25     
    26     /*System.out.println(path1);
    27     System.out.println(path2);
    28     System.out.println(path3);
    29     System.out.println(path4);*/
    30     readFile(path1);
    31     readFile(path2);
    32     readFile(path3);
    33     readFile(path4);
    34 }
    View Code


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

     1 public class CountServlet extends HttpServlet {
     2 
     3     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     4         //访问计数
     5         //首先获取context对象
     6         ServletContext context=this.getServletContext();
     7         //请求一次,context取出访问次数
     8         Integer count=(Integer) context.getAttribute("count");
     9         //次数+1,放入context中
    10         if (count==null) {
    11             context.setAttribute("count", 1);
    12         }else{
    13             context.setAttribute("count", ++count);
    14         }
    15     }
    16 
    17     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    18         doGet(request, response);
    19     }
    20 
    21 }
    CountServlet.java
     1 public class ShowServlet extends HttpServlet {
     2 
     3     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     4         //首先获取context
     5         ServletContext context=this.getServletContext();
     6         //取次数
     7         Integer count=(Integer) context.getAttribute("count");
     8         System.out.println("访问的次数为:"+(count==null?0:count));
     9     }    
    10 
    11     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    12         doGet(request, response);
    13     }
    14 
    15 }
    ShowServlet.java
    1 <body>
    2     <a href="/servletDemo/count">显示次数</a><br/>
    3     <a href="/servletDemo/show">展示结果</a><br/>
    4 </body>
    index.html
     1 <servlet>
     2     <servlet-name>CountServlet</servlet-name>
     3     <servlet-class>cn.augmentum.showcount.CountServlet</servlet-class>
     4 </servlet>
     5 <servlet>
     6     <servlet-name>ShowServlet</servlet-name>
     7     <servlet-class>cn.augmentum.showcount.ShowServlet</servlet-class>
     8 </servlet>
     9 <servlet-mapping>
    10     <servlet-name>CountServlet</servlet-name>
    11     <url-pattern>/count</url-pattern>
    12 </servlet-mapping>
    13 <servlet-mapping>
    14     <servlet-name>ShowServlet</servlet-name>
    15     <url-pattern>/show</url-pattern>
    16 </servlet-mapping>
    web.xml
  • 相关阅读:
    课题论文之调研--贝叶斯网络
    Android开发--数据存储之数据库操作
    Android开发--数据存储之File文件存储
    ROS常用命令
    CMakeLists.txt实例运用(入门)
    乐视三合一奥比中光Orbbec Astra Pro在ROS中配置显示RGB、深度、IR图像的两种思路
    VTK显示CT图像视图
    手眼标定
    并联机器人位姿解算
    信息物理融合CPS
  • 原文地址:https://www.cnblogs.com/wang-meng/p/5389214.html
Copyright © 2020-2023  润新知