是Java Applet的简称。称为小服务程序或服务连接器,用Java编写的服务端程序,主要功能在于交互式地浏览和修改数据,生成动态Web内容。
不能直接在JVM上运行,需要在Servlet容器中运行,本质上是个没有Main方法的Java类。
service方法被调用后,跟进请求类型再转发给相应的方法,例如doGet和doPost。


可以理解为Servlet是一个接口,定义了Java类的被浏览器访问到(tomcat识别)的规则;
需要自定义一个类,实现Servlet接口,那么此方法可以被tomcat识别。
实现原理

服务器接收客户端请求后,解析url,获取访问的Servlet的资源路径;
查找web.xml文件,是否有对应的
如果有,找到servlet-class
tomcat将这个字节码加载进内存并创建对象
调用这个对象的service方法
路径问题
可以通过在首部添加如下信息,然后在使用的时候,base_path加指定别名就可以<%=base_path>别名
<%String base_path = request.getScheme()+":"+"//"+request.getServerName()+":"+request.getServerPort()+request.getServletContext().getContextPath()+"/";%>
请求与响应
浏览器对服务器一次访问称为一次请求,请求用HttpServletRequest对象来表示
服务器给浏览器的一次反馈称为一次响应,响应用HttpServletResponse对象来表示;
下面的jsp文件提交表单之后,值会传递到调用的服务中。
LoginServlet.java
package cn.java.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub// 这里获取的参数,就是jsp文件对应的参数String username = request.getParameter("username");String password = request.getParameter("password");System.out.println("username is:"+username);System.out.println("password is:"+password);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(req,resp);}}
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><%String base_path = request.getScheme()+":"+"//"+request.getServerName()+":"+request.getServerPort()+request.getServletContext().getContextPath()+"/";%><!DOCTYPE html><html><head><meta charset="utf-8"><title>Insert title here</title></head><body><form action="<%= base_path %>LoginServlet" method="post"><table align="center"><tr><td>账号:</td><td><input type="text" name = "username"></td></tr><tr><td>密码:</td><td><input type="password" name = "password"></td></tr><tr ><td ><input type = "submit" value="登录"></td><td ><input type = "reset" value="重置"></td></tr></table></form></body></html>
