Servlet生命周期

32 篇文章 0 订阅
8 篇文章 0 订阅

一、Servlet简介

  • 小服务程序或服务连接器,是用Java编写的服务器端程序。

  • 它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。

  • 工作流程:客户端发送请求至服务器;服务器启动并调用 Servlet,Servlet 根据客户端请求生成响应内容并将其传给服务器;服务器将响应返回客户端。相当于用来扩展服务器性能的一个程序。

二、HttpServlet和Servlet的区别

1. Servlet是一个接口

interface Servlet {
    void init(ServletConfig var1) throws ServletException;
    void service(ServletRequest var1, ServletResponse var2) throws
ServletException, IOException;
    void destroy();
    // 省略了部分我们不关心的方法
}

2. HttpServlet是Servlet接口的实现类

abstract class HttpServlet implements Servlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
        // 根据 request 的 method 不同,调用不同的方法
   }
    
    // GET 时调用
    protected void doGet(protected void service(HttpServletRequest req, 
HttpServletResponse resp) throws ServletException, IOException {
       ...
   }
                         
    // POST 时调用
    protected void doPost(protected void service(HttpServletRequest req, 
HttpServletResponse resp) throws ServletException, IOException {
       ...
   }
                          
    // 省略了 HTTP 协议支持的其他方法
}

三、Servlet生命周期

1. Servlet生命周期的方法,是servlet对象从创建直到毁灭的整个过程。

  • Servlet 通过调用 init () 方法进行初始化。
  • 在 Servlet 的生命期中,仅执行一次 init() 方法。
public void init() throws ServletException {  
    // 初始化代码...
}
  • Servlet 调用 service() 方法来处理客户端的请求。
  • 每当一个客户请求一个HttpServlet 对象,该对象的service() 方法就要被调用。
public void service(ServletRequest request,ServletResponse response)
    throws ServletException, IOException{
}
  • Servlet 通过调用 destroy() 方法终止(结束)。
  • destroy() 方法仅执行一次,在调用 destroy() 方法时,要确保线程已终止或完成。
public void destroy() {    
    // 终止化代码...  
}
  • 最后,Servlet 是由 JVM 的垃圾回收器进行垃圾回收的。 

2. Servlet普通方法

  • doGet
  • 当不会修改服务器端的数据时,应该使用 doGet() 方法。
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet 代码
}
  • doPost
  • 当需要修改服务器端的数据时,应该使用 doPost() 方法。
public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // Servlet 代码
}

四、一个简单的Servlet练习

1. login类

package com.jun.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

//浏览器访问/login路径,就可以执行servlet中的service方法
@WebServlet("/login")
public class Login  extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码及响应类型:在servlet中都要进行
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");//设置响应体
        //设置浏览器解析的类型,响应头Content-Type值
        resp.setContentType("text/html; charset=UTF-8");

        //获取请求数据,通过键获取值,如果获取不到值就为null
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //响应数据给客户端
        PrintWriter pw = resp.getWriter();
        //模拟用户登录的校验步骤
        if(!"stu".equals(username) || !"123".equals(password)){
            resp.setStatus(403);
            pw.println("<p>用户名或密码不正确</p>");
        } else {
            //getSession()=getSession(true)
            //表示获取当前用户Session信息,如果不存在就创建一个
            HttpSession session = req.getSession();
            //键值对形式保存
            session.setAttribute("user",username+"="+password);
            pw.println("用户登录成功");
        }
        pw.flush();
    }
}

2. ForwordServlet类 

package com.jun.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/f")
public class ForwordServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码及响应类型:在servlet中都要进行
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");//设置响应体
        //设置浏览器解析的类型,响应头Content-Type值
        resp.setContentType("text/html; charset=UTF-8");

        String key = req.getParameter("key");
        if("1".equals(key)){
            //重定向:不限制是否在本域名内
            resp.sendRedirect("http://127.0.0.1:8080/ss/shenlong");
        } else {
            //转发:限制在本域名+本项目
            req.getRequestDispatcher("/shenlong").forward(req,resp);
        }
    }
}

3. CallShenlongServlet类

package com.jun.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/shenlong")
public class CallShenlongServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码及响应类型:在servlet中都要进行
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");//设置响应体
        //设置浏览器解析的类型,响应头Content-Type值
        resp.setContentType("text/html; charset=UTF-8");

        //响应数据给客户端
        PrintWriter pw = resp.getWriter();

        //获取当前http请求的用户session信息,如果获取不到,返回null
        HttpSession session = req.getSession(false);
        if(session == null){
            pw.println("小花走了,找不到诶");
        } else {
            String user = (String)session.getAttribute("user");
            //校验用户是否有访问当前url的权限
            if("stu=123".equals(user)){
                //模拟校验
                pw.println("呼唤小花成功,biubiubiu~");
            } else {
                pw.println("呼唤来的不是小花");
            }
        }
        pw.flush();
    }
}

4. html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>登录</title>
    </head>
    <body>
        <p>用户登录</p>
        <form method="post" action="login">
            <input type="text" name="username" placeholder="用户名">
            <input type="password" name="password" placeholder="密码">
            <input type="submit" value="提交">
        </form>
    </body>
</html>

5. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jun</groupId>
    <artifactId>servlet-study</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <!-- 打包后的包名(和我们部署的项目名一致) -->
        <finalName>ss</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值