Java:Servlet详解

目录

一、什么是Servlet

二、Servlet原理

Servlet的生命周期

[三、 Servlet注释](#三、 Servlet注释)

@WebServlet


一、什么是Servlet

Servlet是JavaWeb开发的一种技术,Servlet程序需要部署在Servlet容器(服务端)中才能运行,常见的Servlet容器有Tomcat,Jetty等。

其主要功能在于交互式地浏览和修改数据,生成动态Web内容。这个过程包括以下4个阶段。

(1)、Client向Server发送请求。

(2)、Server将请求信息发送至Servlet。

(3)、Servlet根据请求信息生成响应内容(包括静态或动态内容)并将其传给Server。

(4)、Server将响应返回给Client。

二、Servlet原理

从UML类图中我们可以看出Servlet是一个接口,定义了init初始化、service响应服务、destroy销毁等方法,而GennericServlet作为抽象类实现了Servlet接口,而HttpServlet抽象类继承了GennericServlet类,同时定义了doGet方法,doPost方法来完成相应的Http处理。

其中还可以发现HttpServletRequest和HttpServletResponse是接口,其具体的实现类是web服务器tomcat的两个类。也就是说Servlet必须运行在Servlet容器里

Servlet的生命周期

1.初始化init(),仅在第一次加载Servlet时被调用。

2.执行服务,调用service()方法响应客户请求。

3.销毁调用destory()杀掉Servlet对象。

三、 Servlet注释

我们平时使用部署描述符(web.xml文件)将应用程序部署到Web服务器中。tomcat7以上版本、Servlet API 3.0引入了一个名为javax.servlet.annotation的新程序包。它提供了可用于对Servlet类进行注释的注释类型。如果使用批注,则不需要部署描述符(web.xml)。

@WebServlet

|-------------|----------------------|
| 属性 | 用处 |
| String name | Servlet的名称 |
| urlPatterms | 过滤器的URL格式数组(支持使用通配符) |
| value | URL格式数组 |

使用valueurlPatterns属性中必须声明至少一个URL模式 ,但不能两者都声明(两者不能同时存在)。

实例:

编写了一个带有注释的servlet,url格式为:/Login,它会匹配的请求路径为/Time/Login,其中Time为Web项目名。

java 复制代码
package com.example.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 com.example.utils.JDBCUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet",urlPatterns = "/Login")
public class LoginServlet extends HttpServlet {
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //处理客户端的post请求  
    response.setContentType("text/html;charset=utf-8");   
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    //解决乱码问题!设置内容都为utf-8格式
    PrintWriter out = response.getWriter();
    String username = request.getParameter("name");
    String password = request.getParameter("secret");
    HttpSession session=request.getSession();
    //创建一个会话对象!
    
    JDBCUtils.registerDriver();
    Connection connection=JDBCUtils.getConnection();
    PreparedStatement pStatement=null;
    try {
      ResultSet resultSet=JDBCUtils.checkExit(username, pStatement, connection);
      if(resultSet.next()){
        if(!password.equals(resultSet.getString("password"))){
          out.write("<script language='javascript'>alert('密码错误,请重新输入!');window.location.href='/Todoproject/login.html'</script>");
        }else{
          session.setAttribute("username", username);
          out.write("<script language='javascript'>alert('登录成功!');window.location.href='/Todoproject/menu.html'</script>");
        }
      }else{
        //如果没有找到!
        out.write("<script language='javascript'>alert('该用户不存在!');window.location.href='/Todoproject/login.html'</script>");
      }
    } catch (SQLException e) {
      e.printStackTrace();
      out.write("<script language='javascript'>alert('系统发生错误!');window.location.href='/Todoproject/login.html'</script>");
    }finally{
      JDBCUtils.closeConnection(connection);
    }
  }
}

以下为表单发起的请求

html 复制代码
<form method="post" action="/Time/Login"  id="Login" onsubmit="return checklogin()">
    用户名:<input  type="text" placeholder=" 账号" name="name" id="name"><br><br>
    密码:&emsp;<input  type="password" placeholder=" 密码" name="secret" id="secret">
    <button id="submit" type="submit" >登录</button>
    <button id="register" type="button" onclick="window.open('register.html') " >注册     </button>
</form>
相关推荐
跟着珅聪学java几秒前
spring boot 整合 activiti 教程
android·java·spring
yanqiaofanhua1 分钟前
C语言自学--预处理详解
c语言·开发语言
沐知全栈开发9 分钟前
Vue3 计算属性
开发语言
冰糖雪梨dd42 分钟前
JS中new的过程发生了什么
开发语言·javascript·原型模式
junnhwan1 小时前
【苍穹外卖笔记】Day04--套餐管理模块
java·数据库·spring boot·后端·苍穹外卖·crud
川石课堂软件测试1 小时前
全链路Controller压测负载均衡
android·运维·开发语言·python·mysql·adb·负载均衡
程序员清风1 小时前
Dubbo RPCContext存储一些通用数据,这个用手动清除吗?
java·后端·面试
摇滚侠1 小时前
Spring Boot 3零基础教程,条件注解,笔记09
java·spring boot·笔记
南瓜小米粥、1 小时前
从可插拔拦截器出发:自定义、注入 Spring Boot、到生效路径的完整实践(Demo 版)
java·spring boot·后端
Huangmiemei9112 小时前
Spring Boot项目的常用依赖有哪些?
java·spring boot·后端