Servlet简介

来源:互联网 发布:php数组到字符串转换 编辑:程序博客网 时间:2024/06/05 19:37

前言


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请求的过程

转发和重定向 的区别

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协议的工作流程

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 访问下,所有传输的数据都是经过加密的

 


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过滤器的原理图

 

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                 






J2EE&Servlet

一、BS

二、服务器

① Web服务器

IIS服务器。

Tomcat(JAVA开源、6M),Glassfish、JBoss、Weblogic(1G)

 

② Tomcat

Tomcat 6.0【安装版、绿色软件版】apache-tomcat6.tar.gz

 

服务器:1.就是一台主机    2.软件

 

③ 文件夹

Bin:启动脚本、关闭脚本以及其他脚本。

Bat:批处理问题

Sh:Shell编程

Startup.bat  启动服务器

Shutdown.bat 关闭服务器

第一次启动时,将需要设置JAVA_HOME,指向JDK文件夹

 

Conf:

Server.xml用于配置端口号。Tomcat默认端口号8080

如何进入Tomcat页面?

http://localhost:8080/

 

Lib:放置JAR包,用于Tomcat服务器启动时加载。

 

Webapps:放置已经编译的WEB工程。

 

Work:放置的是JSP编译之后的class文件以及java文件。

 

如果想打开JSP页面,必须让其运行在服务器。

 

War包:编译之后的工程压缩文件

 

 

1.创建WEB工程时,此时为源文件,那么只在WorkSpace有

2.将Web工程部署到Tomcat时,此时将会在Tomcat下的Webapps下有Web工程编译之后的文件,SRC的源代码将编译到WEB-INF下classes下。

3.将Tomcat服务器启动,此时将在Tomcat的Work目录下创建工程名的文件夹。但是此时其文件夹为空。

4.当请求具体的页面时,此时Tomcat将页面转化为JAVA代码并且将其进行编译。

 

两种模式:

1.开发模式 Debug

2.生产模式 Run

 

三、J2EE

SUN公司提出J2EE【Java EE】标准,为了企业级开发。

Servlet:用于处理用户请求并且给予浏览器响应的JAVA类。

JSP:HTML+JAVA代码,实质上为Servlet

服务器:应该保证解释Servlet或者JSP。

Web Service:可以将应用程序转换为网络应用程序。处理不同语言之间方法调用。

 

四、Servlet

开发模式:  MVC

Jsp + JSP   

JSP + Servlet  + JSP

 

v  Servlet概念

1.是一个用JAVA类编写程序

2.运行在WEB环境下【init、doGet、doPost、destroy】

3.用户处理用户的请求

4.对用户的请求作出响应,然后将响应的结果以HTML格式返回给客户端

 

v  第一个Servlet

1.新建一个Servlet

 

2.访问Servlet地址的配置

 

3.查看web.xml

<servlet>

   

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

    <servlet-class>com.csu.edu.servlet.HelloServlet</servlet-class>

  </servlet>

 

  <servlet-mapping>

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

  <url-pattern>/servlet/HelloServlet</url-pattern>

  </servlet-mapping>

  注意:访问Servlet类需要通过url-pattern访问,而不是写包名和类名。

4.访问Servlet

http://localhost:8080/b/servlet/HelloServlet

 

5.选择get或者post,默认是get

<formaction="servlet/HelloServlet"method="post">

        <inputtype="submit"value="提交">

</form>

Method如果为post,那么调用doPost方法。

 

 

v  Tomcat访问Servlet步骤

1.客户端发出请求,访问Servlet请求。路径必须为配置文件中url-pattern

2.Tomcat服务器利用已加载的web.xml,查找servlet-mapping中是否有对应的url-pattern。如果未匹配,将报404错误。如果匹配,将查找到这个servlet-mapping对应的servlet-name

 

404状态码:资源页面查找不到。

500状态码:服务器内部错误

 

3.利用查找到的servlet-name,去匹配servlet标签对应的servlet-name。如果未匹配,服务器启动时将报异常信息。如果查找到,将获取到Servlet对应的servlet-class。但是servlet-class只是一个字符串。

4.利用查找到servlet-class,利用反射原理,实例化对应的对象。将执行HttpServlet中service方法。该方法可以利用request对象查找发送请求的方式(get\post),从而决定调用doGet或者doPost方法。

5.代码进行对应的方法开始执行,此时将会把HTML代码响应给浏览器。

 

 

要求:

HTML页面做内容展示

CSS做页面美化

JAVASCRIPT做客户端验证

Servlet接收数据以及响应数据

Service和Dao层做业务和数据库处理,并将数据返回给Servlet。

 

五、Servlet和Servlet容器

Tomcat是一个服务器,Tomcat是Java EE的标准产品,因此Tomcat必须支持Servlet,可以Tomcat就是一个Servlet容器。

区别:

1.Servlet是一个JAVA类,其初始化调用init方法,其销毁调用destroy方法,其实例化和生命周期由Servlet容器决定。

2.Servlet是在Servlet容器中运行,Servlet容器决定Servlet生命周期。

 

六、Servlet生命周期

继承HttpServlet。

生命周期:初始化阶段、运行阶段、销毁阶段。

1.init:初始化,加载比较耗资源的对象现象。

默认情况是当发送请求到对应的Servlet时,那么该类中的init方法将执行。但是只执行一次。当下次发送请求时,不会执行到init方法。

但是如果配置了load-on-startup,那么将在服务器启动时将调用init方法。

<servlet>

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

   <servlet-class>com.csu.edu.servlet.HelloServlet</servlet-class>

    <load-on-startup>1</load-on-startup>

  </servlet>

只运行一次。

Load-on-startup配置数字:

① 如果未配置load-on-startup,那么需要在客户端发送请求时调用Servlet

② 如果配置了load-on-startup,需要根据情况决定

当值为0或者大于0时,表示服务器启动时加载。

当值小于0或者不指定时,表示Servlet被请求时加载并初始化

当值为0或者大于0时,值越小级别越高。0级别最高。

当值相等时,加载顺序按照XML编写顺序一致。

 

Init方法获取初始化参数:

<init-param>

        <param-name>name</param-name>

        <param-value>123</param-value>

</init-param>

 

@Override

    public void init(ServletConfig config) throws ServletException {

       String name = config.getInitParameter("name");

       System.out.println(name);

    }

 

2.运行阶段

Servlet接收到一个请求,Servlet会针对这个请求创建ServletRequest和ServletResponse,然后调用service方法。该方法会判断请求方式,从而决定调用Servlet的哪个方法。

 

3.销毁阶段

Web应用终止时,Servlet容器会调用Servlet的destroy方法,然后销毁Servlet对象。

只运行一次。

销毁比较耗资源对象,例如数据库连接、IO流关闭。

 

七、Servlet接收和响应

v  Request

1.乱码处理

第一步采用JAVA代码进行处理

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

 

如果第一步处理完仍然有乱码,那么采取方式对Tomcat设置进行处理?

<Connector port="8080" protocol="HTTP/1.1"  URIEncoding="UTF-8"

               connectionTimeout="20000"

               redirectPort="8443" />

 

利用JAVASCRIPT对字符编码进行加密解密。

window.encodeURI("中文","utf-8")

URLDecoder.decode("%E4%B8%AD%E6%96%87","utf-8")

 

2.获取参数数据

1.方法为getParameter

   针对的元素标签为name属性对应的值。表单元素

   传递的参数都为String类型。

   String username = request.getParameter("username");

   传递的URL地址  ?name1=“123” 该方式获取的数据会带上双引号。建议不要带双引号。

 

2.打印参数的名字

Enumeration<String> enumeri = request.getParameterNames();

       while(enumeri.hasMoreElements()){

           String msg = enumeri.nextElement();

           System.out.println(msg);

       }

 

3.获取参数值  复数情况

String [] passwords = request.getParameterValues("password");

System.out.println(passwords[0]+"====="+passwords[1]);

 

4.获取参数值  Map情况

Map<String,String[]> map = request.getParameterMap();

System.out.println(map.get("username")[0]);

System.out.println(map.get("password")[1]);

 

5.获取值

List<EmpVo> lists = new ArrayList<EmpVo>();

       lists.add(new EmpVo("1","a","IT"));

       lists.add(new EmpVo("2","a","IT"));

       lists.add(new EmpVo("3","a","IT"));

      

       request.setAttribute("list", lists);

      

       List<EmpVo> lists1 =

 (List<EmpVo>)request.getAttribute("list");

       for (EmpVo empVo : lists1) {

           System.out.println(empVo.getEmpName());

       }

 

6.传递值

request.setAttribute("list", lists);

request.getRequestDispatcher("/emp.jsp").forward(request, response);  转发,将setAttribute设置的值传递到对应的jsp页面

注意路径,如果直接采用/,后面接页面,那么表示根目录下的资源文件。

 

JSP相关知识:

JAVA代码段:<%   %>

JAVA变量输出:<%=basePath%>

JAVA导入:<%@pageimport="com.csu.edu.vo.EmpVo"%>

 

request.getAttribute("list");

 

问题:getParameter和getAttribute有没有区别?

1.获取值类型不一样  String  Object

2.页面表单数据传递的值     必须要setAttribute,而且要转发的方式

 

MVC:

V:JSP  M:Service\DAO   C:Servlet

JSP---》Servlet---》Service----》DAO----》Service----》Servlet--》转发JSP---》页面的展示

 

 

 

 

SVN  代码版本控制工具

SVN服务器:将代码上传到服务器

SVN客户端:1、先下载SVN服务器上的代码   2、每个人有对应的修改  3、将修改的代码上传到SVN服务器  4 更新客户端代码,从服务器上下载

 

功能测试,压力测试、性能测试   www.51testing.com

 

Junit[Xunit系列]:单元测试,保证代码质量。  傻瓜测试

版本:Junit3、Junit4   注解Annotation   @Override

宗旨:保证绿色条一直出现

 

3.获取请求信息

String path = request.getContextPath();

String basePath = request.getScheme()

+"://"+request.getServerName()+":"+request.getServerPort()+path

+"/";

利用该basePath 写绝对路径地址。

<basehref="<%=basePath%>">

 

getRequestURL():获取URL地址

 

Locale locale = request.getLocale(); //获取本地化信息 国际化

System.out.println("国家:"+locale.getCountry());

System.out.println("语言:"+locale.getLanguage());

 

v  Response

1.发送错误状态码

response.sendError(404,"该Servlet找不到");

<error-page>

    <error-code>404</error-code>

    <location>/404.html</location>

  </error-page>

  <error-page>

    <error-code>500</error-code>

    <location>/500.html</location>

  </error-page>

 

2.获取输出流对象

response.getWriter().write(1);

 

3.转向

response.sendRedirect("../index.jsp");

 

转发转向区别:

场景:

1.有一个人向A借钱,A钱不够,但是A比较好面子,向B借钱,再给该人。【转发】

2.有一个人向A借钱,A钱不够,他告诉该人B有钱,向B借钱。【转向】

 

1.转发是一次请求一次响应。转向是两次请求,两次响应。

2.转发的地址是第一次请求的地址,转向是第二次请求的地址。

3.转发在数据传递过程中不会丢失数据,而转向在数据传递过程中会丢失数据。

4.转发刷新的时候是第一次请求的地址,转向刷新的时候是第二次请求的地址。

   转发如果是对数据库进行修改操作时,每刷新一次将会对数据进行更新。

   如何避免该情况?   Session

   令牌  

 

5.转向能定位到外部资源地址。而转发不能。转发不能跨系统。

6.转发链接地址前面带上/表示根目录,但是转向表示到了Tomcat服务器。

 

ServletConfig

1.获取局部数据

<init-param>

        <param-name>a</param-name>

        <param-value>123</param-value>

</init-param>

@Override

    public void init(){

       System.out.println("<><>"

+this.getServletConfig().getInitParameter("a"));

    }

 

    @Override

    public void init(ServletConfig config)throws ServletException {

       System.out.println("<><>"+config.getInitParameter("a"));

    }

2.获取全局数据

this.getServletContext().getInitParameter("b")

<context-param>

       <param-name>b</param-name>

       <param-value>AAA</param-value>

</context-param>

 

作业:

1.当资源查找不到或者系统内部错误时,跳到对应的页面

2.利用转向实现页面跳转

3.获取全局配置信息。

八、过滤器

Servlet过滤器是Web开发非常有用的技术,目的是减少代码量,方便维护。

过滤器是用户请求和处理程序之间的一层处理程序,可以用来对请求和响应的结果进行处理,例如:字符编码过滤、权限的控制等。

AOP编程:面向切面编程    //JDK 代理接口

1.写Filter类

public class CharacterFilter implements Filter{

 

    public void destroy() {

    }

 

    public void doFilter(ServletRequest request, ServletResponse response,

           FilterChain chain) throws IOException, ServletException {

       request.setCharacterEncoding("utf-8");

       response.setCharacterEncoding("utf-8");

chain.doFilter(request, response);//让其他过滤器发生作用

    }

 

    public void init(FilterConfig config) throws ServletException {

    }

 

}

2.配置过滤器

<filter>

    <filter-name>character</filter-name>

  <filter-class>com.csu.edu.filter.CharacterFilter</filter-class>

  </filter>

 

  <filter-mapping>

    <filter-name>character</filter-name>

    <url-pattern>/*</url-pattern>

  </filter-mapping>

 

 

过滤器链:

多个过滤器组成的链,会挨个发生作用。

过滤器作用在Servlet之前和之后。

 

过滤器链中的过滤器加载顺序与web.xml中配置有关。

过滤器中init方法是在服务器启动时加载的。

Struts1采用Servlet方式load-on-startup。Struts2采用Filter方式

 

作业:

工程中假如有十个页面,假若现在想统计每个页面访问的次数,如何进行处理。

要求每访问一次页面,那么将访问的时间、访问的页面存储入数据库中。日志

 

 

1.获取Filter的参数

<filter>

    <filter-name>character1</filter-name>

  <filter-class>com.csu.edu.filter.CharacterFilter1</filter-class>

    <init-param>

       <param-name>encode</param-name>

       <param-value>utf-8</param-value>

    </init-param>

  </filter>

public void init(FilterConfig config) throws ServletException {

       this.encode = config.getInitParameter("encode");

    }

 

 

2.过滤器链地址匹配方式

① 只要带上/标识,那么只能接文件夹以及*,不能接文件名后缀

② 如果带上的是文件名后缀,就一定不能带/

③ 一个filter可以匹配多个Filter-mapping

<filter-mapping>

    <filter-name>character1</filter-name>

    <url-pattern>*.jsp</url-pattern>

  </filter-mapping>

 

  <filter-mapping>

    <filter-name>character1</filter-name>

    <url-pattern>/a/*</url-pattern>

  </filter-mapping>

 

3.模拟实现过滤器链

责任链模式:

 

 

4.JfreeChart在Web应用

v  Web.xml配置

<servlet>

    <servlet-name>DisplayChart</servlet-name>

    <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>

  </servlet>

 

  <servlet-mapping>

    <servlet-name>DisplayChart</servlet-name>

    <url-pattern>/servlet/display</url-pattern>

  </servlet-mapping>

v  页面代码

String fileName =

 ServletUtilities.saveChartAsJPEG(LineChartDemo2.getJfreeChart(),

400,400,session);

String graphPath = path + "/servlet/display?filename=" +fileName;

 

v  图片引入

 <imgalt=""src="<%=graphPath%>">

 

 

1.友好的登录界面及后台管理界面,其中登录界面提供用户名、密码、部门。界面需要进行一定的美化,并且需要对客户端填入数据进行验证。HTML、CSS、JAVASCRIPT

2.数据库设计  ORACLE、PowerDesigner

3.数据库访问  JDBC、CRUD[增删改查]

4.MVC架构设计


3 0
原创粉丝点击