3月学习日志

来源:互联网 发布:杜兰特夺冠知乎 编辑:程序博客网 时间:2024/05/17 01:48

                   1)web服务软件作用: 把本地资源共享给外部访问

                   2)tomcat服务器基本操作  :

                                     启动:  %tomcat%/bin/startup.bat

                                     关闭: %tomcat%/bin/shutdown.bat

 

                                     访问tomcat主页:

                                                        http://localhost:8080

                   3)web应用目录结构

                                     |-WebRoot   根目录

                                               |-静态资源(html+css+javascript+images+xml)  可以直接被浏览器访问到的

                                               |-WEB-INF                                  不可以直接被浏览器访问到

                                                        |-classes     存放class字节码文件

                                                        |-lib         存放jar包文件

                                                        web.xml      web应用的配置文件,配置servlet

                                    

                   4)Servlet技术: 用java语言开发动态资源的技术

 

                                     开发一个Servlet程序的步骤:

                                                        1)创建一个java类,继承HttpServlet类

                                                        2)重写HttpServlet类的doGet方法

                                                        3)把写好的servlet程序交给tomcat服务器运行!!!!

                                                                 3.1把编译好的servlet的class文件拷贝到tomcat的一个web应用中。(web应用                                                                                       的WEB-INF/classes目录下)                
                                                                 3.2在当前web应用的web.xml文件中配置servlet

                                                                                    <!--servlet配置 -->

                                   <display-name>HelloHttpServlet</display-name>   //一定要加映射的类名

//更新web.xml文档必须重启tomcat服务器

                                                                                    <servlet>

                                                                                             <servlet-name>HelloServlet</servlet-name>

                                                                                             <servlet-class>gz.itcast.HelloServlet</servlet-class>//包名+类名

                                                                                            <load-on-startup>1</load-on-startup>//数值越大优先级越低

                                                                                             //servlet自动加载

</servlet>

                                                                                   <!--  servlet的映射配置 -->

                                                                                   <servlet-mapping>

                                                                                             <servlet-name>HelloServlet </servlet-name>

                                                                                             <url-pattern>/hello</url-pattern>

                                                                                    </servlet-mapping>

                                                        精确匹配:/hello;模糊匹配:/*;  精确匹配优先级高

                                                        以后缀名结尾的模糊匹配优先级最低;

         4)访问servlet(可供外部访问)通过名字找类,构造类的对象找到httpservletdoget方法。过程由tomcat完成。

                                                                           http://localhost:8080/myweb/hello

 

今天的目标: http协议

伪代码演示servlet生命周期

2 Http协议入门

                     2.1什么是http协议

                                     http协议:对浏览器客户端 和  服务器端 之间数据传输的格式规范

(PrintWriter) response.getWriter().writer(); 字符内容

                                                         OutputStreamresponse.getOutputStream().writer(); 字节内容

 

获取用户输入:

Scanner scanner=newscanner(system.in);

Stringcommand=Scanner.next();

或者

bufferedReader buffer=bufferedReader(newInputstream(system.in));

                     2.2 查看http协议的工具

                                     1)使用火狐的firebug插件(右键->firebug->网络)

                                     2)使用谷歌的“审查元素”

                                     3)使用系统自带的telnet工具(远程访问工具)                              

                                                        a)telnet localhost 8080      访问tomcat服务器

                                                        b)ctrl+]     回车          可以看到回显

                                                        c)输入请求内容

                                                                

GET /day09/hello HTTP/1.1

Host: localhost:8080

                                                        d)回车,即可查看到服务器响应信息。

 

                     2.3http协议内容

                           

请求(浏览器-》服务器)

GET /day09/hello HTTP/1.1                                                           请求行

Host: localhost:8080                                                                请求头

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: keep-alive                                                               键值对

                                                                                  一个空行

                                                                                  实体内容

 

        

响应(服务器-》浏览器)

HTTP/1.1 200 OK

Server: Apache-Coyote/1.1

Content-Length: 24

Date: Fri, 30 Jan 2015 01:54:57 GMT

 

this is hello servlet!!!

 

3 Http请求

GET /day09/hello HTTP/1.1               -请求行

Host: localhost:8080                    --请求头(多个key-value对象)

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Connection: keep-alive

                                    --一个空行

name=eric&password=123456             --(可选)实体内容

 

              3.1 请求行

                            GET/day09/hello HTTP/1.1    

              #http协议版本

                   http1.0:当前浏览器客户端与服务器端建立连接之后,只能发送一次请求,一次请求之后连接关闭。

                   http1.1:当前浏览器客户端与服务器端建立连接之后,可以在一次连接中发送多次请求。(基本都使用1.1)

 

              #请求资源

                                     URL:  统一资源定位符。http://localhost:8080/day09/testImg.html。只能定位互联网资源。是URI                                                         的子集。

                                     URI:统一资源标记符。/day09/hello。用于标记任何资源。可以是本地文件系统,局域网的资源(//192.168.14.10/myweb/index.html),                                                   可以是互联网。

              #请求方式

                            常见的请求方式: GET 、 POST、 HEAD、 TRACE、 PUT、 CONNECT 、DELETE 

 

                            常用的请求方式: GET  和 POST     

 

                            表单提交:

                                     <formaction="提交地址"method="GET/POST">

 

                                     <form>

 

                            GET   vs POST 区别

 

                            1)GET方式提交

                                               a)地址栏(URI)会跟上参数数据。以?开头,多个参数之间以&分割。

GET /day09/testMethod.html?name=eric&password=123456 HTTP/1.1

Host: localhost:8080

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Referer: http://localhost:8080/day09/testMethod.html

Connection: keep-alive

 

                                               b)GET提交参数数据有限制,不超过1KB。

                                               c)GET方式不适合提交敏感密码。

                                               d)注意:浏览器直接访问的请求,默认提交方式是GET方式

                            2)POST方式提交

                                     a)参数不会跟着URI后面。参数而是跟在请求的实体内容中。没有?开头,多个参数之间以&分割。

POST /day09/testMethod.html HTTP/1.1

Host: localhost:8080

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-cn,en-us;q=0.8,zh;q=0.5,en;q=0.3

Accept-Encoding: gzip, deflate

Referer: http://localhost:8080/day09/testMethod.html

Connection: keep-alive

 

name=eric&password=123456

 

                                               b)POST提交的参数数据没有限制。

                                               c)POST方式提交敏感数据。

              3.2 请求头

Accept: text/html,image/*      -- 浏览器接受的数据类型

Accept-Charset: ISO-8859-1     -- 浏览器接受的编码格式

Accept-Encoding: gzip,compress  --浏览器接受的数据压缩格式

Accept-Language: en-us,zh-       --浏览器接受的语言

Host: www.it315.org:80          --(必须的)当前请求访问的目标地址(主机:端口)

If-Modified-Since: Tue, 11 Jul 2000 18:23:51 GMT  --浏览器最后的缓存时间

Referer: http://www.it315.org/index.jsp      -- 当前请求来自于哪里

User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)  --浏览器类型

Cookie:name=eric                     -- 浏览器保存的cookie信息

Connection: close/Keep-Alive            -- 浏览器跟服务器连接状态。close: 连接关闭  keep-alive:保存连接。

Date: Tue, 11 Jul 2000 18:23:51 GMT      -- 请求发出的时间

 

              3.3 实体内容

                                     只有POST提交的参数会放到实体内容中

 

              3.4HttpServletRequest对象

                            HttpServletRequest对象作用是用于获取请求数据。

l  Tomcat服务器接收到浏览器发送的请求数据,然后封装到HttpServletRequest对象

l  Tomcat服务器使用doget方法,把request对象传入到servlet中

l  从request对象取出请求数据。

默认get方式。

                                        核心的API:

                                               请求行:

                                                        request.getMethod();   请求方式

                                                        request.getRequetURI()   / request.getRequetURL()   请求资源

                                                        request.getProtocol()   请求http协议版本

                                              

                                               请求头:

                                                        request.getHeader("名称")  根据请求头获取请求值

                                                        request.getHeaderNames()   获取所有的请求头名称

 

                                               实体内容:

                                                        request.getInputStream()  获取实体内容数据

              3.5service 和 doXX方法区别

                           

HttpSevlet类的源码:

protected void service(HttpServletRequest req, HttpServletResponse resp)

        throws ServletException, IOException {

       //得到请求方式

        String method = req.getMethod();

 

        if (method.equals(METHOD_GET)) {

            long lastModified = getLastModified(req);

            if (lastModified == -1) {

                // servlet doesn't support if-modified-since, no reason

                // to go through further expensive logic

                doGet(req, resp);

            } else {

                long ifModifiedSince;

                try {

                    ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);

                } catch (IllegalArgumentException iae) {

                    // Invalid date header - proceed as if none was set

                    ifModifiedSince = -1;

                }

                if (ifModifiedSince < (lastModified / 1000 * 1000)) {

                    // If the servlet mod time is later, call doGet()

                    // Round down to the nearest second for a proper compare

                    // A ifModifiedSince of -1 will always be less

                    maybeSetLastModified(resp, lastModified);

                    doGet(req, resp);

                } else {

                    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);

                }

            }

 

        } else if (method.equals(METHOD_HEAD)) {

            long lastModified = getLastModified(req);

            maybeSetLastModified(resp, lastModified);

            doHead(req, resp);

 

        } else if (method.equals(METHOD_POST)) {

            doPost(req, resp);

           

        } else if (method.equals(METHOD_PUT)) {

            doPut(req, resp);       

           

        } else if (method.equals(METHOD_DELETE)) {

            doDelete(req, resp);

            

        } else if (method.equals(METHOD_OPTIONS)) {

            doOptions(req,resp);

           

        } else if (method.equals(METHOD_TRACE)) {

            doTrace(req,resp);

           

        } else {

            //

            // Note that this means NO servlet supports whatever

            // method was requested, anywhere on this server.

            //

 

            String errMsg = lStrings.getString("http.method_not_implemented");

            Object[] errArgs = new Object[1];

            errArgs[0] = method;

            errMsg = MessageFormat.format(errMsg, errArgs);

           

            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);

        }

    }

 

              3.6 案例-获取浏览器的类型(user-agent)

              3.7 案例- 防止非法链接(referer)

第1次                        CSDN/51CTO   ->  页面(点击下载)   -> 弹出广告页面(点击此处下载) -> 开始下载 

第2次         直接点击此处下载  -> 转回广告页面  ->  开始下载

 

                                     非法链接:                                                            

                                                        1)直接访问下载的资源

                                                        2)不是从广告页面过来的链接

 

                                     referer当前请求来自于哪里。

              3.8 传递的请求参数如何获取       

                             GET方式: 参数放在URI后面

                             POST方式: 参数放在实体内容中

 

                            获取GET方式参数:

                                               request.getQueryString();

                            获取POST方式参数:

                                               request.getInputStream();

 

                            问题:但是以上两种不通用,而且获取到的参数还需要进一步地解析。

                            所以可以使用统一方便的获取参数的方式:

                                    

                                    核心的API:

                                     request.getParameter("参数名"); 根据参数名获取参数值(注意,只能获取一个值的参数)

                                     request.getParameterValue("参数名“);根据参数名获取参数值(可以获取多个值的参数)

 

                                     request.getParameterNames();  获取所有参数名称列表 

              3.9 请求参数编码问题

                                     修改POST方式参数编码:

                                                        request.setCharacterEncoding("utf-8");

                                     修改GET方式参数编码:

                                                        手动解码:String name = newString(name.getBytes("iso-8859-1"),"utf-8");

4 Http响应

HTTP/1.1 200 OK                --响应行

Server: Apache-Coyote/1.1         --响应头(key-vaule)

Content-Length: 24

Date: Fri, 30 Jan 2015 01:54:57 GMT

                                   --一个空行

this is hello servlet!!!                  --实体内容

 

                     4.1响应行

                   #http协议版本

                      #状态码: 服务器处理请求的结果(状态)

                                               常见的状态:

                                                        200:  表示请求处理完成并完美返回

                                                        302:   表示请求需要进一步细化。
                                                        404:   表示客户访问的资源找不到。

                                                        500:   表示服务器的资源发送错误。(服务器内部错误)

                     #状态描述        

      4.2 常见的响应头

Location: http://www.it315.org/index.jsp   -表示重定向的地址,该头和302的状态码一起使用。

Server:apache tomcat                 ---表示服务器的类型

Content-Encoding: gzip                 -- 表示服务器发送给浏览器的数据压缩类型

Content-Length: 80                    --表示服务器发送给浏览器的数据长度

Content-Language: zh-cn               --表示服务器支持的语言

Content-Type: text/html; charset=GB2312   --表示服务器发送给浏览器的数据类型及内容编码

Last-Modified: Tue, 11 Jul 2000 18:23:51 GMT  --表示服务器资源的最后修改时间

Refresh: 1;url=http://www.it315.org     --表示定时刷新

Content-Disposition: attachment; filename=aaa.zip --表示告诉浏览器以下载方式打开资源(下载文件时用到)

Transfer-Encoding: chunked

Set-Cookie:SS=Q0=5Lb_nQ; path=/search   --表示服务器发送给浏览器的cookie信息(会话管理用到)

Expires: -1                           --表示通知浏览器不进行缓存

Cache-Control: no-cache

Pragma: no-cache

Connection: close/Keep-Alive           --表示服务器和浏览器的连接状态。close:关闭连接 keep-alive:保存连接

 

                     4.3HttpServletResponse对象

                            HttpServletResponse对象修改响应信息:

 

                                               响应行:

                                                                 response.setStatus()  设置状态码

                                               响应头:

                                                                 response.setHeader("name","value")  设置响应头

                                               实体内容:

                                                                 response.getWriter().writer();   发送字符实体内容

                                                                 response.getOutputStream().writer() 发送字节实体内容

字符:request.getwriter().write(“”);

字节:request.getoutputstream.write(“”.getbytes());

                     4.4案例- 请求重定向(Location)

Response.sendRedirect

                     4.5案例- 定时刷新(refresh)

Response.setHeader(“refresh”,”3;www.baidu.com”);//隔3秒刷新到百度;

                                     http协议:浏览器和服务器之间数据传输的格式规范

 

                                     1)http请求:

                                                        格式:

                                                                           请求行

                                                                           请求头

                                                                           空行

                                                                           实体内容(POST提交的数据在实体内容中)

                                                        重点:

                                                                使用HttpServletRequest对象:获取请求数据

 

                            2)http响应;

                                               格式:

                                                                 响应行

                                                                 响应头

                                                                 空行

                                                                 实体内容(浏览器看到的内容)

                                               重点:

                                                       使用HttpServletResponse对象:设置响应数据

 

乱码问题:

resp.setCharacterEncoding("UTF-8");

                            resp.setContentType("text/html;charset=UTF-8");

                            servlet在tomcat的运行机制:单实例多线程(多个线程同时访问servlet的共享数据,线程并发的安全问题)synchronized(response){}

synchronized(类对象.class){}//锁对象必须唯一;字节码

//会影响同步效率,哪里使用到了成员变量就同步那里。

1.        <init-param></init-param>

ServletConfig的API:

                                               java.lang.StringgetInitParameter(java.lang.String name)  根据参数名获取参数值

                                               java.util.EnumerationgetInitParameterNames()    获取所有参数

                                         ServletContext getServletContext()     得到servlet上下文对象

                                               java.lang.StringgetServletName()       得到servlet的名称

2.        一个web应用中只有一个servletcontext,多个servletconfig.

3.        config只能由当前的servlet获取,context是全局的。作用范围不一样。

4.        servletcontext常用的方法

java.lang.String getContextPath()  --得到当前web应用的路径

 

                            java.lang.StringgetInitParameter(java.lang.String name) --得到web应用的初始化参数

                            java.util.EnumerationgetInitParameterNames() 

 

voidsetAttribute(java.lang.String name, java.lang.Object object) --域对象共享、保存、获取数据)有关的方法

                            java.lang.ObjectgetAttribute(java.lang.String name) 

                            void removeAttribute(java.lang.Stringname) 

 

                            RequestDispatchergetRequestDispatcher(java.lang.String path)  --转发(类似于重定向)

 

                            java.lang.StringgetRealPath(java.lang.String path)     --得到web应用的资源文件

                            java.io.InputStreamgetResourceAsStream(java.lang.String path) 

5.        所有域对象(注意区分)

                                                                 HttpServletRequet域对象(转发)

                                                        ServletContext域对象(可能会覆盖对象)

                                                        HttpSession域对象(会话)session数据保存在服务器端;cookie保存在客户端。

                                                        PageContext域对象      

getrealPath

getResourceAsStream

6.        void setMaxAge(int expiry) :设置cookie的有效时间。

                                               正整数:表示cookie数据保存浏览器的缓存目录(硬盘中),数值表示保存的时间。

                                               负整数:表示cookie数据保存浏览器的内存中。浏览器关闭cookie就丢失了!!会话cookie

                                               零:表示删除同名的cookie数据

7.        过滤器

@WebFilter(filterName="log",urlPatterns={"/*"})

public class logFilter implements Filter {

     private FilterConfigconfig;

     @Override

     public void init(FilterConfigfilterConfig) throws ServletException {

              // TODOAuto-generated method stub

             

              this.config=config;

     }

     @Override

     public void destroy() {

              // TODOAuto-generated method stub

              this.config=null;

     }

     /**

      * 过路的核心方法

      */

     @Override

     public voiddoFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)

                       throwsIOException, ServletException {

              // TODOAuto-generated method stub

              //ServletContextcontext= this.config.getServletContext();

              longbefore=System.currentTimeMillis();

              System.out.println("开始过滤");

              HttpServletRequesthrequest = (HttpServletRequest)arg0;

              System.out.println("已经截获到用户的请求地址:"+hrequest.getServletPath());

              //filter为链式处理,请求依然放行到亩的地址;

              arg2.doFilter(arg0,arg1);

              longafter=System.currentTimeMillis();

              System.out.println("过滤结束");

              System.out.println("请求被定位到"+hrequest.getRequestURI()+"所花的时间为:"+(after-before));

     }

}

8.        entity实体;dao(data access object)数据访问对象;servlet; util工具类;test测试

9.        //String->String[]->collection

                   String[]str=prodList.split(",");

                   Collection col=Arrays.asList(str);

10.    Linklist方法(增删改查)

11.    1)创建或得到session对象

                                     HttpSessiongetSession() 

                                     HttpSessiongetSession(boolean create) 

                            2)设置session对象

                                     voidsetMaxInactiveInterval(int interval)  :设置session的有效时间

                                     voidinvalidate()     :销毁session对象

                                     java.lang.String getId()  : 得到session编号

                            3)保存会话数据到session对象

                                     voidsetAttribute(java.lang.String name, java.lang.Object value)  : 保存数据

                                     java.lang.ObjectgetAttribute(java.lang.String name)  :获取数据

                                     voidremoveAttribute(java.lang.String name) : 清除数据

12.    RDD,全称为ResilientDistributed Datasets,是一个容错的、并行的数据结构,可以让用户显式地将数据存储到磁盘和内存中,并能控制数据的分区。同时,RDD还提供了一组丰富的操作来操作这些数据。在这些操作中,诸如map、reduce、join、filter等转换操作实现了monad模式,很好地契合了Scala的集合操作。只读分区记录集和

<!-- 修改session全局有效时间:分钟 -->

    <session-config>

       <session-timeout>1</session-timeout>

1.            </session-config>

2.        request.getsession(false)//得到;;;request.getsession(true)//创建;;;invalidate()


0 0