37 Servlet Technology (Part 1)

1 Basic Concepts

1.1 C/S Architecture

C/S architecture (client/server mode) is an early software architecture and a very common structure. The feature of this structure is that the business to be processed will be reasonably allocated to the client and the server. , the client is responsible for completing the interaction with the user, and the server is responsible for data management.

The advantage is:

  • The interface and functions of the client can be very rich
  • Application server is lightly loaded
  • quick response

weakness is:

  • Narrow scope of application, fixed user groups
  • High maintenance and upgrade costs, once updated requires all clients to be upgraded

1.2 B/S Architecture

B/S architecture (browser/server mode) is a software architecture emerging from the Internet. The feature of this architecture is that the main business logic of business function realization is concentrated on the server side, and only a few business logic needs to be processed by the client side. , the same browser is responsible for completing the task of interaction with the user, and the browser is responsible for data management.

The advantage is:

  • No need to install the client, as long as there is a browser
  • Wide range of applications, user groups are not fixed
  • The purpose of multi-customer access is realized through permission control, and the interaction is strong
  • Low maintenance and upgrade costs, no need to update all clients

weakness is:

  • Application server is under heavy load
  • It takes a lot of cost to achieve the richness of the client's interface and function of the browser
  • It is not satisfactory on cross browsers, and the adaptation is more troublesome

1.3 JavaWeb

The original meaning of web is the meaning of webpage, which means the resources on the Internet for the outside world to visit, and the resources on the Internet for the outside world to visit are mainly divided into:

  • Static resources: The data in the web page for people to browse is unchanged

  • Dynamic resources: The data in the web page for people to browse is generated by the program, and different content is seen when visiting the page at different time points

    JavaWeb refers to the general term for dynamic Web resource development technology using Java language, and it is the sum of technologies to solve related Web Internet fields

1.4 HTTP protocol

The HTTP protocol (Hypertext Transfer Protocol) is an application layer protocol, which is mainly used to standardize the data format of how the browser and the server communicate, mainly involving the sending request of the browser and the response format of the server.

The default port of HTTP is 80, and the default port of HTTPS is 443. The following will introduce the HTTP request format and HTTP response format.

HTPP request format: The request message that the client sends an HTTP request to the server mainly includes: request line, request header, blank line and request body.

请求行说明请求类型和要访问的资源以及所使用的时间HTTP版本,格式如下:
请求类型 请求路径 协议的版本号
请求头是紧接着请求行之后的部分,主要用来说明服务器要使用的附加信息,格式(key,value)如下:
主机 请求长度 请求的浏览器相关信息
空白行就是请求头部的空行,即使后面的请求数据为空也必须有空行

请求体,可以添加任意的其他数据
复制代码

Example

GET/sample.jspHTTP/1.1
Accept:image/gif.image/jpeg,*/*
Accept-Language:zh-cn
Connection:Keep-Alive
Host:localhost
User-Agent:Mozila/4.0(compatible;MSIE5.01;Window NT5.0)
Accept-Encoding:gzip,deflate

username=jinqiao&password=1234
复制代码

HTTP响应格式:服务器接收并处理客户端发过来的请求后会返回一个HTTP响应消息,主要包括:响应行、响应头、空白行和响应体。

响应行用来说明HTTP协议的版本号和状态码以及状态消息,格式如下:
协议的版本 状态码 状态信息
响应头说明客户端要使用的一些附加信息,格式(key,value)
空白行就是响应头部的空行,即使后面的响应数据为空也必须有空行

响应体是用来返回给客户端的文本信息
复制代码

实例

HTTP/1.1 200 OK
Server:Apache Tomcat/5.0.12
Date:Mon,6Oct2003 13:23:42 GMT
Content-Length:112
Content-Type:text/html
Last-Moified:Mon,6 Oct 2003 13:23:42 GMT
Content-Length:112
/Users/bijinxiong/Tomcat/bin
复制代码

2 Tomcat服务器

Tomcat服务器是一个轻量级的Web应用服务器,在中小型系统和并发量小的场合下被普遍使用,是开发和调试Servlet、JSP程序的首选。

安装完Tomcat服务器后,看看目录结构:

  • bin 存放二进制可执行文件
  • conf 存放 各种配置文件
  • lib 存放Tomcat运行时需要加载的jar包
  • logs 存放Tomcat在运行过程中产生的日志文件
  • temp 存放Tomcat在运行过程中产生的临时文件
  • webapps 存放应用程序,当Tomcat启动时会去加载该目录下的应用程序
  • work 存放Tomcat在运行时的编译后文件,例如JSP编译后的文件

3 Servlet的概念和使用

Servlet是Java Servlet的简称,称为小服务程序或服务连接器,是Java语言编写的服务器端程序,简单来说,Servlet就是运行在服务器上的Java类。

Servlet用来完成B/S架构下客户端请求的响应的处理,也就是交互式的浏览和生成数据,生成动态Web内容。

Servlet的编程步骤:

  1. 建立一个Java Web Application项目并配置Tomcta服务器
  2. 自定义类实现Servlet接口或继承HttpServlet(推荐),重写service方法
  3. 将自定义的信息配置到web.xml文件并启动项目,配置方式如下:
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.bjx.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
复制代码

在浏览器上访问的方式为:

http://localhost:8080/工程名/url-pattern的内容
复制代码

3.1 Servlet接口

java.servlet.Servlet接口定义了所有Servlet必须实现的方法,常用方法如下:

方法声明 功能介绍
void init(ServletConfig con) 由servlet容器调用,以向servlet指示servlet正在被放入到服务中
void service(ServletRequest req,ServletResponse res) 由servlet容器调用,以允许servlet响应请求
ServletConfig getServletConfig() 返回ServletConfig对象,该对象包含此servlet的初始化和启动参数
String getServletInfo() 返回有关servlet的信息
void destroy() 由servlet容器调用,以向servlet指示servlet正在退出服务

3.2 GenericServlet类

GenericServlet类主要定义一个通用的、与协议无关的Servlet,该类实现Servlet接口,其中常用的方法是:

方法声明 功能介绍
abstract void service(ServletRequest req,ServletResponse res) 由servlet容器调用允许servlet响应请求

3.3 HttpServlet类

HttpServlet类是个抽象类并继承了GenericServlet类,用于创建适用于各种网站的HTTP Servlet,该类的子类至少重写一个方法(service方法),该类的常用方法如下:

方法声明 功能介绍
void doGet(HttpServletRequest req,HttpServletResponse resp) 处理客户端的GET请求
void doPost(HttpServletRequest req,HttpServletResponse resp) 处理客户端的POST请求
void inti() 进行初始化操作
void service(HttpServletRequest req,HttpServletResponse resp) 根据请求决定调用doGet还是doPost方法
void destroy() 删除实例时释放掉资源

3.4 Servlet生命周期

img

构造方法只会被调用一次,当第一次请求Servlet时调用构造方法来创建Servlet实例

init方法也只被调用一次,当创建好Servlet实例后立即调用该方法实现Servlet的初始化

service方法可以被调用多次,每当有请求时都会调用该方法用于响应请求

destory方法只被调用一次,当该Servlet实例所在的Web应用被卸载前调用该方法来释放当前占用的资源

3.5 POST和GET请求

GET请求只会出现在:

  1. 在浏览器输入URL按回车
  2. 点击< a>超链接
  3. 点击submit按钮,提交< form method="get">表单

GET请求特点是:会将请求数据添加到请求URL地址的后面,只能提交少量的数据,并且是不安全的

POST请求只会出现在:

  1. 点击ubmit按钮,提交< form method="post">表单

POST请求的特点:请求数据添加到HTTP协议体中,可提交大量的数据,且安全性好

3.6 ServletRequest接口

ServletRequest接口主要用于向Servlet提供客户端的请求信息,可以从中获取到任何请求信息。

Servlet容器创建了一个ServletRequest对象,并将对象作为参数传递给Servlet的service方法,关于ServletRequest接口常用方法如下:

方法声明 功能介绍
String getParameter(String name) 以字符串形式返回请求参数的值,不存在,就返回null
String getParameterValues(String name) 返回一个字符串对象数组,其中包含给定的请求参数所具有的所有值
Enumeration getParameterNames() 返回包含此请求对象中包含的参数名称的字符串对象枚举
Map<String,String> getParameterMap() 返回请求参数的键值对,一个键可以对应多个值
String getRemoteAddr() 返回发送请求的客户端最后一个代理的ip地址
int getRemotePort() 返回发送请求的客户端最后一个代理的端口号

3.7 HttpServletRequest接口

HttpServletRequest接口是ServletRequest接口的字接口,主要用于提供HTTP请求信息的功能。

不同于表单数据,在发送HTTP请求时,HTTP请求头直接由浏览器设置

可直接通过ServletRequest对象提供的一系列get方法获取请求头的数据信息,具体get方法如下:

方法声明 功能介绍
String getRequestURI() 返回此请求的资源路径信息
StringBuffer getRequestURL() 返回此请求的完整路径信息
String getMethod() 返回发出此请求的HTTP方法的名称,例如GET
String getQueryString() 返回路径后面请求中附带的参数
String getServletPath() 返回此请求调用servlet的路径部分

3.8 ServletResponse接口

ServletResponse接口用于定义一个对象来帮助Servlet向客户端发送响应。

Servlet容器创建ServletResponse对象,并将其作为参数传递给servlet的service方法,关于ServletResponse常用方法如下:

方法声明 功能介绍
PrinWriter getWriter() 返回可向客户端发送字符文本的PrintWriter对象
String getCharacterEncoding() 获取响应内容的编码方式
void setContentType(String type) 如果尚未提交响应,则设置发送到客户端响应的内容类型,内容类型可以包括字符编码规范,例如text/html;charset=UTF-8

3.9 HttpServletResponse接口

HttpServletResponse接口继承ServletResponse接口,以便在发送响应时提供特定于HTTP的功能,其常用方法如下:

方法声明 功能介绍
void sendRedirect(String location) 使用指定的重定向位置URL向客户端发送临时重定向响应

4 Servlet接收中文乱码

接收乱码原因:浏览器在提交表单时,会对中文参数值进行自动编码。当Tomcat服务器接收到浏览器请求后自动解码,当编码方式和解码方式不一致时,就会乱码。

解决POST接收乱码

接受之前设置编码格式:
request.setCharacterEncoding("utf-8")
提示:
  必须在调用request.getParameter("name")之前设置
复制代码

解决GET接收乱码

将接收到的中文乱码重新编码:
String name=request.getParameter("name"); //接收到get请求中的中文字符串
String username=new String(name.getBytes("ISO-8859-1"),"utf-8");//将中文字符重新编码,默认编码ISO-8859-1
复制代码

5 ServletConfig接口

ServletConfig接口用于描述Servlet本身的相关配置信息,在初始化期间用于将信息传递给Servlet配置对象

配置方式实例:

    <servlet>
        <servlet-name>ConfigServlet</servlet-name>
        <servlet-class>com.bjx.ConfigServlet</servlet-class>
        <init-param>
            <param-name>key</param-name>
            <param-value>value</param-value>
        </init-param>
    </servlet>
复制代码

常用方法:

方法声明 功能介绍
String getServletName() 返回Servlet的别名
String getInitParameter(String name) 返回包含初始化参数值的字符串
Enumeration getInitParameterNames() 将servlet的初始化参数的名称作为字符串对象的枚举返回
ServletContext getServletContext() 返回对调用方法正在其中执行的ServletContext的引用

6 ServletContext接口

ServletContext接口主要用于定义一组方法,servlet使用这些方法与它的Servlet容器通信。

服务器容器在启动时会为每个项目创建唯一的一个ServletContext对象,用于实现多个Servlet之间的通信和信息共享

在Servlet中通过this.getServletContext()方法获得ServletContext对象

在web.xml中配置ServletContext初始化参数

    <context-param>
        <param-name>username</param-name>
        <param-value>bi</param-value>
    </context-param>
   <context-param>
       <param-name>password</param-name>
       <param-value>666666</param-value>
   </context-param>
复制代码

ServletContext接口的常用方法:

方法声明 功能介绍
String getInitParameter(String name) 返回包含初始化参数值的字符串
Enumeration getInitParameterNames() 将servlet的初始化参数的名称作为字符串对象的枚举返回
String getRealPath(String path) 返回包含给定虚拟路径的实际路径的字符串
String getContextPath() 返回与此上下文关联的主路径
InputStream getResourceAsStream(String path) 将位于指定路径的资源作为InputStream对象返回
voud setAttribute(String name,Object object) 将指定的属性名和属性值绑定到当前对象
Object getAttribute(String name) 根据执行的属性名获取属性值
void removeAttribute(String name) 删除指定的属性名信息

Guess you like

Origin juejin.im/post/6955052532380991501