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>
相关推荐
土了个豆子的几秒前
02.继承MonoBehaviour的单例模式基类
开发语言·visualstudio·单例模式·c#·里氏替换原则
帧栈2 分钟前
我的创作纪念日
java
qq_172805597 分钟前
Go 自建库的使用教程与测试
开发语言·后端·golang
久绊A13 分钟前
Hydra-SSH 破解安全防范
开发语言·php
阿昭L20 分钟前
c++中获取随机数
开发语言·c++
3壹26 分钟前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
悟乙己35 分钟前
使用 Python 中的强化学习最大化简单 RAG 性能
开发语言·python·agent·rag·n8n
bug攻城狮37 分钟前
Spring Boot Banner
java·spring boot·后端
max50060039 分钟前
图像处理:实现多图点重叠效果
开发语言·图像处理·人工智能·python·深度学习·音视频
黑马源码库miui520861 小时前
JAVA同城打车小程序APP打车顺风车滴滴车跑腿源码微信小程序打车源码
java·微信·微信小程序·小程序·uni-app