码迷,mamicode.com
首页 > 其他好文 > 详细

Servlet简介

时间:2014-05-25 21:26:21      阅读:438      评论:0      收藏:0      [点我收藏+]

标签:servlet   http协议   web服务器   application   web   

前言


1.servlet简介
  a.b/s  架构 
   browser/server,就是客户端采用浏览器,服务器端采用web server。浏览器和   服务器端之间采用http协议进行通讯。相对于c/s架构的优势:
    1.不需要关系通讯的问题,c/s架构需要自己写代码来定义通讯协议,难度比较大。
    2.浏览器不需要单独安装,可维护性更好,c/s架构需要下载客户端。
   服务器端负责通讯,我们可以使用servlet/jsp技术来显示业务逻辑,处理业务逻辑。
  b.组件和容器
    组件:符合规范的可以单独部署的程序模块。
   (部署:将该组件复制到容器的指定的目录,容器会自动调用)
    容器:符合规范的程序,主要用来管理组件的生命周期(比如,组件实例创建、组件的调用、组件销毁),
    同时给组件提供运行环境。
  c.servlet 
     就是sun公司提供的用于扩展web功能组件技术。         
   
    

正文

Servlet


 
 网页    静态网页(HTML)   动态网页   JavaEE规范   Servlet---Jsp

 


什么是Servlet?

Interface servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. Servlet是由sun公司开发的一组用来扩展服务器功能的规范/ 一组API的统称,也是一个顶层接口; 

1.servlet是java语言编写的程序,运行于支持java的web服务器或应用服务器中

2.servlet先于JSP出现,提供服务端和客户端动态交互的功能。

3.servlet可以处理来自客户端的HTTP请求,并生成响应给客户端。

4.servlet对于web服务器而言,就好像java Applet 对于web浏览器;servlet需要加载到web服务器并在web服务器内执行。
 
注: CGI(Common Gateway Interface,通用网关接口) 是一种运行在服务器端的程序,它接收浏览器客户端的请求,将 请求转发给服务器,将服务器处理的结果返回给浏览器。
 
1.CGI程序在执行过程中开销很大,同时在吞吐量较大的情况下执行效率比较慢; Servlet是在客户端请求之后创建一个线程来处理每个请求 吞吐量大时执行效率更高

2.servlet的优点

1)可移植性

2).安全:具有类型检查特性,并利用java的垃圾收集器和没有指针的设计,使得servlet避免了内存管理问题。

3)高效,servlet加载执行后会常驻服务器内存中,当再次收到客户端的请求时,服务器会产生新的线程而非进程为客户端服务,提高响应速度。

 

servlet接口的常用API

1.Servlet类结构

javax.servlet
Interface Servlet
All Known Subinterfaces:
HttpJspPage, JspPage
All Known Implementing Classes:
FacesServlet, GenericServlet, HttpServlet

2.Servlet的简介

Defines methods that all servlets must implement.

A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

 

3.Servlet的API

1)ServletConfig getServletConfig()

Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. The ServletConfig object returned is the one passed to the init method.
Implementations of this interface are responsible for storing the ServletConfig object so that this method can return it. The GenericServlet class, which implements this interface, already does this.获得servletContext对象

 

HttpServlet抽象类的常用API

1.javax.servlet.http Class HttpServlet 的类结构


java.lang.Object
  javax.servlet.GenericServlet
      javax.servlet.http.HttpServlet
All Implemented Interfaces:
java.io.Serializable, Servlet, ServletConfig

2.HttpServlet

public abstract class HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

?doGet, if the servlet supports HTTP GET requests
?doPost, for HTTP POST requests
?doPut, for HTTP PUT requests
?doDelete, for HTTP DELETE requests
?init and destroy, to manage resources that are held for the life of the servlet
?getServletInfo, which the servlet uses to provide information about itself

3.HTTPServlet抽象类的API

1)protected void service(HttpServletRequest req,  HttpServletResponse resp)    throws ServletException,       java.io.IOException

Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP-specific version of the Servlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) method. There‘s no need to override this method.

Parameters:
req - the HttpServletRequest object that contains the request the client made of the servlet
resp - the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
java.io.IOException - if an input or output error occurs while the servlet is handling the HTTP request
ServletException - if the HTTP request cannot be handled

 

GenericServlet抽象类的常用API

1.GenericServlet的类结构

javax.servlet
Class GenericServlet
java.lang.Object
  javax.servlet.GenericServlet
All Implemented Interfaces:
java.io.Serializable, Servlet, ServletConfig
Direct Known Subclasses:
HttpServlet

2.GenericServlet的介绍

Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.

GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it‘s more common to extend a protocol-specific subclass such as HttpServlet.

GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface.

To write a generic servlet, you need only override the abstract service method

3.GenericServlet的ap

1) java.lang.String getServletName()
          Returns the name of this servlet instance获取servlet配置时,声明在web应用内部使用的名字。

2)java.util.Enumeration<java.lang.String> getInitParameterNames()
          Returns the names of the servlet‘s initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters

3)java.lang.String getInitParameter(java.lang.String name)
          Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.获取servlet配置信息中参数名为name的参数值。

 

 
书写执行一个Servlet程序


 server+applet


 步骤:


 1.新建JavaWeb Project
  在建好的包中创建自己的Servlet类
  implements Servlet 实现Servlet接口中的所有方法
  
 2.实现service方法  
  public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException {   
  }


 3.配置web.xml配置文件
1.  <servlet></servlet> 标签用于声明servlet,

它的子标签:

1)<servlet-name>用于声明servlet在web应用内部使用的名字。

2)<servlet-class> 用于声明servlet所对应的全限定名

2.  <servlet-mapping></servlet-mapping> 用于进行servlet映射

它的子标签:

1)<servlet-class> 需要和<servlet>的子标签的<servlet-name>的标签体内容保持一致。

2)<url-pattern>用于指明访问servlet对应的地址

注:

<servlet>和<servlet-mapping>应该成对出现。
  
 4.将工程部署在web服务器中


  1.将web服务器配置在MyEclipse   web服务器(容器)
1)     硬件上来说服务器是一台功能强大的计算机;     软件上来说除了自身的操作系统以为还必须装有第三方软件,   这种软件是一种运行在Internet之上用来连接后台程序与前台网页,      接收浏览器发送的请求,根据请求调用对应处理程序
2)      在计算机上监听特定端口,接收响应
3)      能够存储开发完成的web程序,      能够为web程序提供运行所需环境,为web组件提供服务      
4)   常用的web服务器软件:Tomcat/JBoss/Weblogic/websphere


  2.将目标工程配置在对应的web服务器
 
 5.启动服务器,访问目标程序


  访问:   http://服务器主机IP:web服务器监听的端口/工程URL名称/Servlet的映射路径


  
 
 Tomcat的目录结构

1.bin        可执行文件   .bat/.sh
2.  conf  Tomcat的配置文件:例如:server.xml中的<service name="catalina"><connector port ="8080"></service> 配置项目端口
3.     server.xml    <Connector port="8899"
4.     web.xml
5.  work  Jsp编译转换后的字节码文件
6.  webapps  存放启动执行的web程序
7.  temp  存储临时文件
8.  logs  Tomcat日志文件夹
9.  lib   执行依赖的JAR

 

 
 Servlet的生命周期


  1.servlet的生命周期分为初始化阶段,运行阶段,销毁阶段


  2.初始化阶段,销毁阶段在整个servlet的生命周期中只执行一次,   运行阶段可执行多次。


  3.初始化阶段执行init方法,运行阶段执行service方法,销毁阶段执行destory方法。


  4.生命周期

1)初始化阶段:web容器调用init方法,执行初始化操作,执行一些参数的初始化操作


2) 运行阶段:web容器调用service方法,将当前请求的信息封装成ServletRequest对象,     并且将要响应的信息对象ServletResponse对象创建并将这两个对象作为参数传递给service方法;
     在service方法中处理请求,并将响应结果封装在ServletResponse对象中,由web容器返回给浏览器


3  销毁阶段:当前容器关闭的时候执行,一般会将资源关闭回收的操作在其中执行。

4.servlet代码示例

5.servlet和JSP的关系

1)JSP在本质上就是servlet,web服务器总是把被访问的各个JSP文件先翻译成对应的servlet,然后在编译执行。

2)以tomcat服务器为例,JSP对应的servlet存放在Tomcat主目录的\work\catalina\locahost目录下

 3)jsp最终以servlet的形式为客户端提供服务。

6.在servlet的生命周期中常被调用的方法

1)void init(ServletConfig config)          throws ServletException

Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.

2)void service(ServletRequest req,   ServletResponse res)     throws ServletException,    java.io.IOException

Called by the servlet container to allow the servlet to respond to a request.
This method is only called after the servlet‘s init() method has completed successfully.每当用户请求servlet时,都会被调用,用来处理用户请求并返回响应结果。

3)void destroy()

Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. This method is only called once all threads within the servlet‘s service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet当servlet被卸载时,destroy方法被执行以回收servlet启用的资源

注:service方法 根据用户提交HTTP请求的方式,如果为get方式,则service方法调用servlet实现的doGet方法来为用户服务。如果为post方式,则service方法调用实现HTTPServlet类的doPost方法为用户提供服务。换言之,doGet或doPost方法才是真正处理用户请求的响应者。

由于在实际编程中,通常对这两种方式的处理相同,因此可以选择在doGetf方法中doPost方法。

7.实现HttpServlet类的servlet的代码示例

8.servlet中可以使用的对象

servlet可以直接使用的对象只有HttpServletRequest类型的request对象和HttpServletResponse类型的response对象。其他的对象(比如,向客户端输出内容的out对象和维持会话的session对象)都需要通过这两个对象方法来获得。

 

9..小结

当客户端第一次请求servlet时,servlet被加载到内存,容器会创建servlet实例,并调用它的init方法进行初始化工作;容器创建请求对象和响应对象,然后调用servlet的service方法为客户端提供服务。;当servlet不再被需要的时候,容器调用servlet的destroy方法将servlet实例销毁;如果客户端请求的servlet已经存在于服务器内存时,容器会创建新的线程调用service方法来响应客户端请求;在servlet的整个生命周期中init方法和destroy方法只会被调用一次。

 


    
     默认当前servlet第一次被访问时执行初始化操作


     web.xml中当前servlet的配置中设置初始化时间


      <load-on-startup>0</load-on-startup>
     当配置参数小于0则为默认状态,在第一次访问初始化
     当配置参数大于等于0则在服务器启动时初始化
     当浏览器请求当前servlet时执行运行阶段
     当服务器关闭时调用销毁阶段
  
  


 Servlet访问

可以使用TCP/IP monitor插件测试(例如MyEclipse,window->show view ->MyEclipse Common->Tcp/Ip monitor)。


  1.浏览器地址栏
   http://127.0.0.1:8899/工程webURL/对应servlet
  2.超链接访问
   <a href="http://localhost:8899/hello129/tld" target="_self">点击这里</a>
  3.表单访问 action=""
   <form action="http://localhost:8899/hello129/tld"


  
 Servlet接收页面参数


  页面中参数以key=value的方式发送
  service方法中
  String value = request.getParameter("key");
  String[] values = request.getParameterValues("key");


  
 中文乱码问题


  接收中文参数乱码


1.   以get方式提交参数乱码
    在server.xml中   service---catalina    添加一个属性   URIEncoding="utf-8"
2.   以post方式提交参数乱码
    在接收参数前设置request对象的编码方式    request.setCharacterEncoding("utf-8");
   
3.  输出响应的HTML内容中文乱码


   HTML被浏览器解析时乱码
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


4.   response对象编码问题


    response.setCharacterEncoding("utf-8");
    //设置应答类型
    response.setContentType("text/html;charset=utf-8");
    输出文件类型:text/html / application/msword/ application/pdf


 浏览器响应码

1XX:信息,请求收到,继续处理

2XX,成功。行为被成功地接受、理解和采纳

3XX:重定向,为了完成请求,必须进一步的执行的动作

4XX:客户端错误,请求包含语法错误或者请求无法实现。

5XX:服务器错误,服务器不能实现一种明显、无效的请求。

例子:  404   访问路径不对;  500  后台代码出错 ;  503 服务器错误;  200 浏览器正常响应;302  重定向


 
 设置初始化参数


1.  web.xml中找到对应servlet配置
    <init-param>
       <param-name>url</param-name>
       <param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
      </init-param>
  
2.  在service方法中


   ServletConfig.getInitParameter("url");//获得参数名为URL的参数值
  ServletConfig对象封装的是当前servlet的配置信息,在初始化时由web服务器创建


 
 创建Servlet类型对象的其他方式


  1.通过继承GenericServlet抽象类来实现;   没有特定协议的支持
  2.通过继承HttpServlet类来实现;   有对于 HTTP协议的特定支持

 
    注:

1).重写service方法来实现接收处理请求;  或者  重写doPost和doGet方法也能处理请求。

2).如果同时实现了service方法来实现接收处理请求和 重写doPost和doGet方法也能处理请求时,服务器只调用service方法。


3.  代码示例


 

 
 
 转发和重定向
 
转发

   request.getRequestDispatcher("/view").forward(request, response);

重定向

response.sendRedirect("url全路径");

 

1.Redirect请求的过程

bubuko.com,布布扣

转发和重定向 的区别

1.在实现过程中转发的浏览器地址栏不会改变;重定向执行的时候浏览器地址栏改变。

2.转发也叫服务器内部跳转,书写的跳转路径参数是相对路径;重定向可以向任何URL路径完成跳转,书写跳转路径参数必须是全路径(浏览器发起了两次请求,服务器响应了了两个请求。)

3.通过转发跳转能够使用request对象来共享数据;重定向不能使用request对象来实现数据的共享。

 

ServletContext 对象

 

封装当前工程下所有servlet的配置信息(上下文环境)

1.ServletContext的类结构

javax.servlet
Interface ServletContext

2.ServletContext的简介

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

3.ServletContext的常用API

1)java.net.URL getResource(java.lang.String path)
          Returns a URL to the resource that is mapped to the given path.
2( void setAttribute(java.lang.String name, java.lang.Object object)
          Binds an object to a given attribute name in this ServletContext.
3) void removeAttribute(java.lang.String name)
          Removes the attribute with the given name from this ServletContext.

 

4.在文本.xml文件中配置全局共享数据。

 

5.向浏览器输出文件代码示例

 
 

 Interface  HttpServletRequest

Extends the ServletRequest interface to provide request information for HTTP servlets.

The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet‘s service methods (doGet, doPost, etc).

1.类结构

javax.servlet.http
Interface HttpServletRequest
All Superinterfaces:
ServletRequest
All Known Implementing Classes:
HttpServletRequestWrapper

2.常用API

1.)java.lang.String getRequestURI()
          Returns the part of this request‘s URL from the protocol name up to the query string in the first line of the HTTP request. 获取所请求的服务路径,

例如appname/url-pattern
2) java.lang.StringBuffer getRequestURL()
          Reconstructs the URL the client used to make the request. 获取请求的URL地址,包括协议名、服务器名、端口号和所请求的服务的路径,但不包括请求时所带事务参数。例如:http://localhost:7405/bbs/servlet/FirstServlet
3) java.lang.String getServletPath()
          Returns the part of this request‘s URL that calls the servlet. 获取Servlet的访问地址,例如url-pattern
4). java.lang.String getContextPath()
          Returns the portion of the request URI that indicates the context of the request.获取web应用的根路径,例如/appname

5) HttpSession getSession()
          Returns the current session associated with this request, or if the request does not have a session, creates one.
6) HttpSession getSession(boolean create)
          Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
 

Interface ServletRequestquest

Defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet‘s service method.

A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest.

1.ServletRequest类结构

javax.servlet
Interface ServletRequest
All Known Subinterfaces:
HttpServletRequest
All Known Implementing Classes:
HttpServletRequestWrapper, ServletRequestWrapper

2.ServletRequest的API

1) void setCharacterEncoding(java.lang.String env)
          Overrides the name of the character encoding used in the body of this request
2) ServletContext getServletContext()
          Gets the servlet context to which this ServletRequest was last dispatched
3) RequestDispatcher getRequestDispatcher(java.lang.String path)
          Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.获取请求转发对象,转向地址为path。获得的RequestDispatcher的实现类的方法void forward(ServletRequest request, ServletResponse response)     Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.实现真正的内部跳转。
 

Interface RequestDispatcher

Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.

This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.

 

1.RequestDispatcher的API

1)void forward(ServletRequest request, ServletResponse response)
          Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server

2) void include(ServletRequest request, ServletResponse response)
 
         Includes the content of a resource (servlet, JSP page, HTML file) in the response.
 

 

Interface ServletResponse

Defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet‘s service method.

To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.

The charset for the MIME body response can be specified explicitly using the setCharacterEncoding(java.lang.String) and setContentType(java.lang.String) methods, or implicitly using the setLocale(java.util.Locale) method. Explicit specifications take precedence over implicit specifications. If no charset is specified, ISO-8859-1 will be used. The setCharacterEncoding, setContentType, or setLocale method must be called before getWriter and before committing the response for the character encoding to be used.

 

1.ServletResponse类结构

javax.servlet
Interface ServletResponse
All Known Subinterfaces:
HttpServletResponse
All Known Implementing Classes:
HttpServletResponseWrapper, ServletResponseWrapper

2.ServletResponse的API

1)java.lang.String getCharacterEncoding()
          Returns the name of the character encoding (MIME charset) used for the body sent in this response.

2) void setCharacterEncoding(java.lang.String charset)
          Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.设置响应的编码字符集为charset

3) java.lang.String getContentType()
          Returns the content type used for the MIME body sent in this response.
4) void setContentType(java.lang.String type)
          Sets the content type of the response being sent to the client, if the response has not been committed yet.设置响应的内容类型为type.

5)java.io.PrintWriter getWriter()
          Returns a PrintWriter object that can send character text to the client返回一个PrintWriter对象,利用这个对象可以向客户端输出文本。这个对象的作用类似于JSP的内置对象out。

5) ServletOutputStream getOutputStream()
          Returns a ServletOutputStream suitable for writing binary data in the response

6)x boolean isCommitted()
          Returns a boolean indicating if the response has been committed.

 

 Interface HttpServletResponse

Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.

The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet‘s service methods (doGet, doPost, etc).

 

1.HttpServletResponse的类结构

javax.servlet.http
Interface HttpServletResponse
All Superinterfaces:
ServletResponse
All Known Implementing Classes:
HttpServletResponseWrapper

 

 

2.HttpServletResponse的API

1) void addCookie(Cookie cookie)
          Adds the specified cookie to the response.

2) void addHeader(java.lang.String name, java.lang.String value)
          Adds a response header with the given name and value.

3) java.lang.String encodeURL(java.lang.String url)
          Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.重写URL,使其携带sessionId.。这是会哈跟踪技术之一。

4) java.lang.String encodeRedirectURL(java.lang.String url)
          Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.

5) void sendRedirect(java.lang.String location)
          Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.

 

注:URL重写

1.如果客户端的浏览器不支持cookie,也可以通过URL重写来实现Session对象的唯一性。可以使用HttpServletResponse的encodeRedirectURL和encodeUrl方法来实现URL重写。

2.所谓的URL重写,就是当客户从一个页面重新连接到另一个页面时,通过向这个新的URL添加参数,把session对象的sessionId传递过去,这样就可以保证同一个客户在该网站各个页面中的session对象是完全相同的。

会话(Session)

业务的会话概念:任何业务的请求都是有上下文环境的,而往往上下文环境是受前面业务操作的结果,此时就诞生了会话这个概念..

SESSION是业务会话的技术实现,其中HttpSession是WEB会话的具体实现.

session对象

session对象用于在会话范围内,记录每个客户端的访问状态,以便于跟踪每个客户端的操作状态,在会话中存储的信息;在浏览器发出的后续请求时可以获得这些会话的有效数据。session对象所实现的接口为javax.servlet.http Interface HttpSession。

在JSP页面可以直接使用session对象,也可以通过pagecontext.getSession()或者HttpSession的getSession方法来重新获取session对象。

session工作原理

Session是存储于服务器内存当中的会话,我们知道Http是无状态协议,为了支持客户端与服务器之间的交互,我们就需要通过不同的技术为交互存储状态,而这些不同的技术就是Cookie和Session了。

Http协议是一种无状态协议。客户向服务器发出请求,然后服务器返回响应,连接就被关闭。在服务器端不保留连接的有关信息,因此当下一次连接时,服务器端已没有以前的连接信息,无法判断这一次连接和以前的连接是否属于同一个客户。因此必须使用会话来记录有关连接信息。从客户打开浏览器连接到服务器,到客户关闭浏览器离开这个服务器称为一个会话。当客户访问服务器时,可能会反复连接这个服务器的几个页面,反复刷新刷新一个页面或不断地向一个页面提交信息等。服务器应当通过某种办法知道这是同一个客户,这时就需要session对象。

1.session的工作原理如下:

1)客户首次访问服务器的一个页面时,服务器就会为该客户分配一个session对象,同时为该session对象指定一个唯一的id,并且将该id号发送到客户端并写入到cookie中,使得客户端与服务器端的session建立一一对应关系。

2)当客户继续访问服务器上的其它资源时,服务器不再为该客户分配新的session对象,直到客户端浏览器关闭、超时或调用session的invalidate方法使其失效,客户端与服务器的会话结束。

3)当客户重新打开浏览器访问网站时,服务器会重新为客户分配一个session对象,并重新分配sessionID.

 

HttpSession的本质

1, HttpSession是在服务器端划拨出的一个区域,一般来说此区
域是以内存的方式存在的.
2, 一般来说HttpSession的数据结构和Map类似,是以键值对的
形式存储用户的数据,key用来区分每个不同的用户.
3, key一般来说是存放在用户浏览器的cookie中,通过HTTP请求
中的cookie域上送到服务器,服务器应用既可以用该cookie值
定位到具体存放在服务器上的用户数据.

 

session的生命周期

1、session的默认过期时间是30分钟,可修改的最大时间是1440分钟(1440除以60=24小时=1天)。

2、服务器重启或关闭Session失效。
 
?注:浏览器关闭其实并不会让session失效!因为session是存储在服务器端内存当中的。客户端把浏览器关闭了服务器怎么可能知道?正确的解释或许应该是浏览器关闭后不会去记忆关闭前客户端和服务器端之间的session信息且服务器端没有将sessionId以Cookie的方式写入到客户端缓存当中,重新打开浏览器之后并不会带着关闭之前的sessionId去访问服务器URL,服务器从请求中得不到sessionId自然给人的感觉就是session不存在。

当我们关闭服务器时Tomcat会在安装目录workCatalinalocalhost项目名目录下建立SESSIONS.ser文件。此文件就是Session在Tomcat停止的时候 持久化到硬盘中的文件. 所有当前访问的用户Session都存储到此文件中. Tomcat启动成功后.SESSIONS.ser  又会反序列化到内存中,所以启动成功后此文件就消失了. 所以正常情况下 重启Tomcat用户是不需要登录的. 注意有个前提,就是存储到Session里面的user对象所对应的User类必须要序列化才可以。

HttpSession的常用方法

1. ServletContext getServletContext()
          Returns the ServletContext to which this session belongs

2. java.lang.Object getAttribute(java.lang.String name)
          Returns the object bound with the specified name in this session, or null if no object is bound under the name.如果属性不存在,则返回null。

3. void setAttribute(java.lang.String name, java.lang.Object value)
          Binds an object to this session, using the name specified.

4. java.lang.String getId()
          Returns a string containing the unique identifier assigned to this session.

5. void removeAttribute(java.lang.String name)
          Removes the object bound with the specified name from this session

6. void invalidate()
          Invalidates this session then unbinds any objects bound to it.设置session失效,并解绑对应的属性。

7. void setMaxInactiveInterval(int interval)
          Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.设置会话的最大持续时间,单位是秒。负数表明会话永不失效。

8. int getMaxInactiveInterval()
          Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.

9.long getLastAccessedTime()
          Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.
 long getCreationTime()
          Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.

注:

一般使用

Date(long date)
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

来转化获得对应的具体日期。

10. boolean isNew()
          Returns true if the client does not yet know about the session or if the client chooses not to join the session.

注:session实现购物车的功能

Cookie对象的介绍

Cookie是以文件形式[缓存在客户端]的凭证(精简下为了通俗易懂),cookie的生命周期主要在于服务器给设置的有效时间。如果不设置过期时间,则表示这个cookie生命周期为浏览器会话期间,只要关闭浏览器窗口,cookie就消失了。

cookie对象是web服务器保存在用户硬盘上的一段文本,保存路径在windows操作系统上一般为C:\Documents and Settings\Administrator(登录的用户名)\Cookies目录。

在cookie中,信息片段一“名/值”对的形式存储。当浏览器访问web服务器时,相应的cookie会自动发送到服务器端。

 

cookie文本示例:

 

1.Cookie对象通常用于在浏览器端保存会话工程中的一些参数,如用户名和会话id等信息。

2.cookie不属于JSP的内置对象。

3.cookie为用户提供个性化服务:

1)cookie可以实现:站点跟踪特定访问者的次数、最后访问的时间以及访问者进入站点的路径。

2)cookie能够帮助站点统计用户个人资料以实现个性化服务。

3)cookie在同一站点内可以实现自动登录功能,使得用户不需要输入用户名和密码就可以进入曾经浏览的站点。

 

cookie的类结构

javax.servlet.http
Class Cookie
java.lang.Object
  javax.servlet.http.Cookie
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable

 

cookie对象简介

 

1.Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie‘s value can uniquely identify a client, so cookies are commonly used for session management.

2.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.

3.The servlet sends cookies to the browser by using the HttpServletResponse#addCookie method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

4.The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest#getCookies method. Several cookies might have the same name but different path attributes.

5.Cookies affect the caching of the Web pages that use them. HTTP 1.0 does not cache pages that use cookies created with this class. This class does not support the cache control defined with HTTP 1.1.

cookie的写入和读取

 

cookie对象的写入

The servlet sends cookies to the browser by using the HttpServletResponse#addCookie method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

 

 创建cookie对象

1.Cookie(java.lang.String name, java.lang.String value)
          Constructs a cookie with the specified name and value.创建cookie对象需要指定名称和值,The name must conform to RFC 2109. However, vendors may provide a configuration option that allows cookie names conforming to the original Netscape Cookie Specification to be accepted. 其中cookie对象的名称只能使用可打印的ASCII字符,不能包含逗号、空格、分高并且不能以$符号开头。

The name of a cookie cannot be changed once the cookie has been created. 在cookie创建后值可以改变而名称不可改变。

The value can be anything the server chooses to send. Its value is probably of interest only to the server. The cookie‘s value can be changed after creation with the setValue method.

By default, cookies are created according to the Netscape cookie specification. The version can be changed with the setVersion method.

 

设置cookie的属性

 1.void setComment(java.lang.String purpose)
          Specifies a comment that describes a cookie‘s purpose.
2. void setDomain(java.lang.String domain)
          Specifies the domain within which this cookie should be presented.
3. void setHttpOnly(boolean isHttpOnly)
          Marks or unmarks this Cookie as HttpOnly.
4. void setMaxAge(int expiry)
          Sets the maximum age in seconds for this Cookie. 在将cookie对象发送到浏览器端保存时,需要指定cookie的有效期,有效期已过,浏览器就会删除该cookie对象。

注:cookie的有效期设置如下

1)属性是按秒为单位记录的,使用正整数。

2)负值表示该cookie的生存期是当前浏览器会话

3)零值表示立即删除该cookie

4)如果不设置cookie的有效期,就不能在硬盘上存储cookie的信息,一旦浏览器关闭,cookie信息就消失。


5. void setPath(java.lang.String uri)
          Specifies a path for the cookie to which the client should return the cookie.
6. void setSecure(boolean flag)
          Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.

注:Http和https简要介绍

1.http

HTTP协议是基于tcp/ip协议族的;HTTP协议永远都是客户端发起请求,服务器响应请求;HTTP协议是一个无状态的协议;HTTP协议(V1.1)默认是长连接的

2.HTTP协议的工作流程

bubuko.com,布布扣

3.http请求

GET / HTTP/1.1
Host: xxx.10086.cn
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
If-Modified-Since: Mon, 25 May 2009 03:19:18 GMT
Cookie: T_FPCid=227a89d92136543e4da1299123152907

4.HTTP应答

HTTP/1.1 200 OK
Cache-Control: private, max-age=30
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Expires: Mon, 25 May 2009 03:20:33 GMT
Last-Modified: Mon, 25 May 2009 03:20:03 GMT
Vary: Accept-Encoding
Server: Microsoft-IIS/7.0
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Mon, 25 May 2009 03:20:02 GMT
Content-Length: 12173
 
-消息体的内容(略)

5.HTTP响应代码

响应码分五种类型,由它们的第一位数字表示
1xx:信息,请求收到,继续处理
2xx:成功,行为被成功地接受、理解和采纳
3xx:重定向,为了完成请求,必须进一步执行的动作
4xx:客户端错误,请求包含语法错误或者请求无法实现
5xx:服务器错误,服务器不能实现一种明显无效的请求

6.Https 访问下,所有传输的数据都是经过加密的

bubuko.com,布布扣

 


Https 访问下,所有传输的数据都是经过加密的Https 访问下,所有传输的数据都是经过加密的Https 访问下,所有传输的数据都是经过加密的


7. void setValue(java.lang.String newValue)
          Assigns a new value to this Cookie.
8. void setVersion(int v)
          Sets the version of the cookie protocol that this Cookie complies with.

 

调用HttpServletResponse接口的addCookie方法将cookie写入到客户端

1.void addCookie(Cookie cookie)
          Adds the specified cookie to the response

 

写cookie的代码示例

 

cookie对象的读取

对cookie对象的读取要结合HttpServletRequest接口的方法

 Cookie[] getCookies()
          Returns an array containing all of the Cookie objects the client sent with this request.

1.每个站点在本地只对应一个cookie文件,而这个cookie文件可以有多个cookie对象的信息,因此所有的cookie信息应该封装在一个cookie对象数组中。如果想读取出其中一个cookie对象,必须通过循环遍历整个cookie数组。

2.获取cookie对象的代码示例

 

cookie和session的关系

session对象能和客户建立起一一对应的关系依赖于客户端的浏览器是否支持Cookie。

如果客户端的浏览器不支持Cookie,也可以通过URL重写来实现session对象的唯一性。

两者的不同之处

存放地点

Cooie 存放在客户端的硬盘中,属于离线存放;而session存放在服务器的内存中。

存活时间

Cookie可以长期存放在硬盘中。具体的存活时间可以由setMaxAge方法所指定的数值决定。额session随着用户访问服务器而产生,随着客户超时或下线而消失。

安全性

Cookie存放在客户端,可能会被别有用心的网站读取,安全性较差;而session存放在服务器端的内存中,用户不能修改,并且随着客户端的关闭而消失,安全性较好。

两者的联系

不管是Cookie还是session内置对象,它们都需要浏览器支持Cookie,并且没有禁用Cookie。

cookie实现自动登录的功能

 设计了三个文件

1)login.sp 用来进行登录并保持用户自动登录的时间

 

2)dealLogin.jsp 用来进行业务逻辑判断

 

 

3)index.jsp 主页,可通过request.getCookes方法获取用户信息。

 

Servlet过滤器

Servlet过滤器是一种java组件,它位于客户端和处理程序之间,能够对请求和响应进行检查以及修改。Servlet过滤器常用来完成一些通用的操作,例如统一字符集编码、字符的压缩和加密以及对访问路径的检查来实施安全控制。

 

 Servlet过滤器的原理图

bubuko.com,布布扣

 

1.当客户端对服务器资源发出请求时,服务器会根据应用配置文件设置的过滤规则进行检查,如果客户端的请求满足过滤规则,则对客户端请求进行拦截,对请求消息头和请求数据进行检查或改动,并依次通过过滤器链,最后把请求交给处理程序。

2.请求信息在过滤器链可以被修改,也可以根据条件不把请求发往处理程序,直接向客户端发回一个响应。

3.当处理程序完成了虽请求的处理后,响应信息将逐级逆向返回。同样在这个过程中,响应信息也可能被过滤器修改,从而完成一定的任务。

 

 

Servlet过滤器的API

与过滤器相关的API包含了三个接口,分别是Filter、FilterChain和FilterConfig

 

Filter

所有的过滤器都要实现Filter接口。该接口定义了void destroy()、end of the chain.和void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
方法。

1. void destroy()
          Called by the web container to indicate to a filter that it is being taken out of service. Servlet过滤器的初始化方法,Servlet容器创建Servlet过滤器实例后将调用这个方法。
2. void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
          The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. 用于完成实际的过滤操作,当客户端的请求满足过滤规则时,Servlet容器将调用过滤器的doFilter方法完成它想做的一切。
3. void init(FilterConfig filterConfig)
          Called by the web container to indicate to a filter that it is being placed into service 当doFilter方法中的所有线程退出或超时时,容器将调用destroy方法来释放过滤器占有的所有资源,以此表明过滤器已结束服务。

FilterChain

A FilterChain is an object provided by the servlet container to the developer giving a view into the invocation chain of a filtered request for a resource. Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain, to invoke the resource at the end of the chain.用于访问过滤器链上的下一个过滤器。

该接口的void doFilter(ServletRequest request, ServletResponse response)
          Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.用于调用过滤器链中的下一个过滤器,如果这个过滤器是链上的最后一个过滤器,则将请求交给处理程序或将响应发给客户端。

FilterConfig

A filter configuration object used by a servlet container to pass information to a filter during initialization。用于读取web.xml文件中的Servlet过滤器的初始化参数,在过滤器初始化阶段提供过滤器名、初始化参数和Servlet上行文等信息。

该接口提供了以下的java.lang.String getFilterName()、java.lang.String getInitParameter(java.lang.String name)、ServletContext getServletContext()和ServletContext getServletContext()四个方法:

 java.lang.String getFilterName()
          Returns the filter-name of this filter as defined in the deployment descriptor.
 java.lang.String getInitParameter(java.lang.String name)
          Returns a String containing the value of the named initialization parameter, or null if the initialization parameter does not exist.
 java.util.Enumeration<java.lang.String> getInitParameterNames()
          Returns the names of the filter‘s initialization parameters as an Enumeration of String objects, or an empty Enumeration if the filter has no initialization parameters.
 ServletContext getServletContext()
          Returns a reference to the ServletContext in which the caller is executing. 返回调用者所处的Servlet上下文。

<filter>标签的配置示例

 

过滤器小结

1.一个Servlet过滤器可以有多个映射(这个过滤器指定多个URL规则。)

2.反过来一个URL可对应多个Servlet过滤器,这些过滤器根据在配置文件中出现的先后顺序组成一个过滤器链。

 

 

会话跟踪技术

session、Cookie、URL重写和隐藏表单域

监听器

与Java中的监听器类似,只不过Servlet监听器监听的web组件。Servlet共提供8个监听端口和6个事件类,分别实现了对Servlet上下文、HTTP会话和客户端请求的监听。

 

1.Servler里可以用一个名字绑定一个对象,并且在应用中传递和使用这个对象。

 

作用域对象

属性操作方法

作用域范围说明

ServletContext(上下文)

Void setAttribute(String,Object)

Object getAttribute(String)

void removeAttribute(String)

Enumeration getAttributeNames()

整个WEB应用程序

HttpSession(会话)

一个会话交互过程

ServletRequest(请求)

一次请求过程

监听器接口和相对应的监听器事件类

 

事件类型

描述

Listener

servletContext事件

生命周期

servlet上下文刚被创建并可以开始为第一次请求服务,或者servlet上下文将要被关闭发生的事件

servletContextListener

属性改变

servlet上下文内的属性被增加,删除或者替换时发生的事件

servletContexAttributeListener

httpsession事件

生命周期

httpsession被创建,无效或超时时发生

httpsessionlistener

httpsessionActivationlistener

会话迁移

httpsession被缴活或纯化时发生

属性改变

在httpsession中的属性被增加,删除,替换时发生

httpsessionAttributelistener

HttpsessionBindingListener

对象绑定

对象被绑定到或者移出httpsession时发生

ServletRequest事件

生命周期

在Servlet请求开始按web组件处理时发生

ServletRequestListener

属性改变

在ServletRequest对象中的属性被增加、删除、替换时发生

ServletRequestAttributeListener

 

注:

初始化顺序:init Filter--》ListerNER--》Servlet。

 

总结

开发一个servlet程序


  tomcat使用:
    1.安装tomcat    2.配置环境变量:      JAVA_HOME:      CATALINA_HOME:C:\Program Files\tomcat-6.0.14      PATH:C:\Program Files\tomcat-6.0.14\bin  
    3.开启和关闭tomcat      开启 tomcat   startup      关闭  tomcat   shutdown      在浏览器中输入http://localhost:8080    


  开发servlet程序步骤:


     step1. 写一个java类,实现Servelt接口或者继承Httpservlet类,一般     继承Httpservlet类(实现了Servelt接口).
     step2.编译(servlet-api.jar).
     step3.打包
           appname(目录,程序名)
                WEB-INF(目录,不能自己定义)
                  classes(存放servlet class文件)
                  lib(存放程序所需要的第三方包,数据库驱动包)
                  web.xml(是一个xml的文件,
                     要按照servlet的规范来写,称为部署描述文件)
     step4.部署
          将step3的打包的文件复制到服务器指定的目录下面,在tomcat中复制到         webapps目录。
     step5.运行程序            在浏览器中输入           http://localhost:8080/appname/url-pattern                 

Servlet简介,布布扣,bubuko.com

Servlet简介

标签:servlet   http协议   web服务器   application   web   

原文地址:http://blog.csdn.net/z929118967/article/details/25969273

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!